Just a small test for frames and serial (RS232) communication, with ideas from http://eli.thegreenplace.net/2009/08/20/frames-and-protocols-for-the-serial-port-in-python/
main.cpp
- Committer:
- janwesterkamp
- Date:
- 2012-05-02
- Revision:
- 0:566fc5f530fe
File content as of revision 0:566fc5f530fe:
#include "mbed.h"
#include "parser.h"
#include "string"
#include "list"
Serial pc(USBTX, USBRX); // initialize RS232 via USB
DigitalOut prg_activity_led(LED1); // some LED to show activity
DigitalOut rx_activity_led(LED2);
DigitalOut tx_activity_led(LED3);
DigitalOut message_led(LED4);
// we need some storage for the messages we want to send and receive
string singleSendMessageBuffer;
string singleReceiveMessageBuffer;
// and a buffer for those messages, until they are processed
list<string> sendMessagesBuffer;
list<string> receiveMessagesBuffer;
// Interupt Routine to read in data from serial port
void Rx_interrupt() {
rx_activity_led=!rx_activity_led;
// Loop just in case more than one character is in UART's receive FIFO buffer
while (pc.readable()) {
char c = pc.getc();
unwrap_protocol(&c, &singleReceiveMessageBuffer, &receiveMessagesBuffer);
// pc.putc(c); // echo
}
return;
}
// Interupt Routine to write out data to serial port
void Tx_interrupt() {
char c;
int finished = WRAP_SEND;
int messageAvailable = !sendMessagesBuffer.empty();
tx_activity_led=!tx_activity_led;
// Loop to fill more than one character in UART's transmit FIFO buffer
while ( pc.writeable() && messageAvailable && (finished == WRAP_SEND)) {
finished = wrap_protocol( &c, &singleSendMessageBuffer, &sendMessagesBuffer );
if (finished != WRAP_ABORT)
pc.putc(c);
}
//tx_activity_led=0;
return;
}
int main() {
string sendString;
pc.baud(115200); // other high speed: 921600
// Setup a serial interrupt function to receive data
pc.attach(&Rx_interrupt, Serial::RxIrq);
// Setup a serial interrupt function to transmit data
pc.attach(&Tx_interrupt, Serial::TxIrq);
// enable interrupt
NVIC_EnableIRQ(UART1_IRQn);
set_time(0); // needed to initialize rtc
while (1) {
prg_activity_led = !prg_activity_led; // toggle LED
time_t seconds = time(NULL); // get current time
//printf("Time as a string = %s\r\n", ctime(&seconds));
if (!receiveMessagesBuffer.empty()) {
//pc.printf("\r\nMessage: %s\r\n", receiveMessagesBuffer.front().c_str());
sendString = "Message '";
sendString += receiveMessagesBuffer.front().c_str();
sendString += "' received at ";
sendString += ctime(&seconds);
sendString += "\r";
sendMessagesBuffer.push_back(sendString);
receiveMessagesBuffer.pop_front();
} else {
//sendString = "Hallo Welt!\r\n";
sendString = ctime(&seconds);
sendString += "\r";
sendMessagesBuffer.push_back(sendString);
}
// trigger sending interrupt
char c;
int finished = wrap_protocol( &c, &singleSendMessageBuffer, &sendMessagesBuffer );
if (finished != WRAP_ABORT)
pc.putc(c);
wait(1); // wait and don't flood the RS232
}
}