A code sample showing the use of the asynchronous Serial APIs.
Dependencies: mbed
Beware: this example is only compatible with boards supporting the asynchronous APIs!
Information
All examples in this repo are considered EXPERIMENTAL QUALITY, meaning this code has been created as one-off proof-of-concept and is suitable as a demonstration for experimental purposes only. This code will not be regularly maintained by Silicon Labs and there is no guarantee that these projects will work across all environments, SDK versions and hardware.
main.cpp
- Committer:
- stevew817
- Date:
- 2015-05-13
- Revision:
- 1:f6715f1bf6a6
File content as of revision 1:f6715f1bf6a6:
#include "mbed.h" /*------------ Constant definitions --------------*/ #define TX_PIN USBTX #define RX_PIN USBRX #define BRATE 115200 #define LED_PIN LED0 #define TOGGLE_RATE (0.5f) #define BUFF_LENGTH 5 /*-------- Check if platform compatible ----------*/ #if DEVICE_SERIAL_ASYNCH Serial test_connection(USBTX, USBRX); #else #error "Platform not compatible with Low Power APIs for Serial" #endif /*------------------ Variables -------------------*/ LowPowerTicker blinker; bool blinking = false; event_callback_t serialEventCb; DigitalOut LED; char rx_buf[BUFF_LENGTH + 1]; /*------------------ Callbacks -------------------*/ void blink(void) { LED = ~LED; } void serialCb(int events) { /* Something triggered the callback, either buffer is full or 'S' is received */ unsigned char i = 0; if(events & SERIAL_EVENT_RX_CHARACTER_MATCH) { //Received 'S', check for buffer length for(unsigned char i; i < BUFF_LENGTH; i++) { //Found the length! if(rx_buf[i] == 'S') break; } // Toggle blinking if(blinking) { blinker.detach(); blinking = false; } else { blinker.attach(blink, TOGGLE_RATE); blinking = true; } } else if (events & SERIAL_EVENT_RX_COMPLETE) { i = BUFF_LENGTH - 1; } else { rx_buf[0] = 'E'; rx_buf[1] = 'R'; rx_buf[2] = 'R'; rx_buf[3] = '!'; rx_buf[4] = 0; i = 3; } // Echo string, no callback test_connection.write(rx_buf, i+1, (event_callback_t*)0, 0); // Reset serial reception test_connection.read(rx_buf, BUFF_LENGTH, &serialEventCb, SERIAL_EVENT_RX_ALL, 'S'); } /*-------------------- Main ----------------------*/ int main() { /* Very Simple Main (tm) */ serialEventCb.attach(serialCb); /* Setup serial connection */ test_connection.baud(BRATE); test_connection.printf("Low Power API test\n\nSend 'S' to toggle blinking\n"); test_connection.read(rx_buf, BUFF_LENGTH, &serialEventCb, SERIAL_EVENT_RX_ALL, 'S'); /* Let the callbacks take care of everything */ while(1) sleep(); }