dumb noob question on passing strings via serial UART

Status
Not open for further replies.

albireo13

Active member
I have my BT module working now with my Teensy 2.0.
I can pass individual characters, or bytes, across but I am not handling strings correctly.
As a test, I want to send a character string via BT to serial UART, to the Teensy.
How do I read strings from the serial port, not knowing ahead of time how long the string will be?

HTML:
/* Teensy 2.0 UART test with BT module.

  This code takes a serial input from the BT module, 
  modifys the test, and then spits it back out via 
  serial to the BT module, as char format data. This tests BT connectivity 
  and the interfacing between the BT module and Teensy 2.0
  
*/

String inByte = 'Nyet!';         // incoming string

// This line defines a "Uart" object to access the serial port
HardwareSerial Uart = HardwareSerial();

void setup()  {
  Uart.begin(9600); 
}

void loop()  {
  if (Uart.available() > 0) {
    inByte = Uart.read();
    Uart.print("Here it is, fatso!!! : ");
    Uart.println(inByte);
  }
  
}
 
If you are creating a system out of whole cloth that uses serial communications of your own design, it would be a great idea to design a robust protocol that you can use to build data packets that can be easily and reliably passed from one device to another. There are many ways to do this, for example:

Byte..... Function
0..... Starting Code identifying the start of a packet, e.g. 0x7E (ASCII "~") or ASCII <STX>
1,2.....Message length, in Bytes, applied to Bytes 3 through n
3 to 7.....Addressing, etc.
8 to n.....Your Data (Payload)
n+1.....Checksum, (e.g. 1-Byte, 1's Compliment), applied to Bytes 3 through n

Other common ways to do this could, for example, eliminate the Length bytes, and instead, put a unique character(s) as an end code, such as ASCII <CR> or <CR><LF>.

Personally, I prefer using a start code and length bytes, skipping the end-codes, which makes a premature packet terminations less likely. This, by the way, is how XBee radios communicate with their host processors in API mode. A checksum is always a good idea to ensure data integrity.

Good luck!

(BTW- the only "dumb" questions are the ones you are too proud to ask!)
 
Last edited:
Status
Not open for further replies.
Back
Top