Saturday, 25 January 2020

Serial (UART) communication


I just have a few general questions that those with more experience could easily answer.


I am working with an arduino, and interfacing with various devices such as the PC that I use to write the arduino C code, which is obviously plugged in via USB, and I have had success with a serial link to an iphone by connecting the tx/rx pins.





  • What sort of data integrity guarantees are there for the serial link? For example if the cable connecting two devices becomes frayed or damaged, what sort of changes might I expect my data stream to undergo? Could it start receiving garbled data, or will it just cut off?




  • Is its functionality fully encapsulated by a byte stream? Suppose I want to relay 16-bit numbers. My first and only instinct is that I must come up with my own protocol (big-endian or little, for example) to pack my data into a byte stream and write to the port? It functions more or less like a network socket (minus the concept of packets) does it not?





Answer






  • Async serial has no data integrity guarantees. If data integrity is important to your application, add a checksum. But if everything is connected properly, it should be pretty solid.




  • You get a series of bytes. The rest is up to you.




  • If the serial is connected while transmission is underway, it will not automatically synchronize. Some garbage will appear on the line.




One common scheme is to represent data with packets. Then the packet format is like:



[sync byte][data length byte][data bytes][checksum byte]


There are a lot of variations on it. The sync byte lets the receiver synchronize if it gets a partial message. The sync byte can be escaped if it appears elsewhere in the packet, or not. Checksum can be a sum of all bytes, or XOR, or CRC16, etc.


An alternative is to only use ASCII for the serial communications. Then you can synchronize on the '\n' at the end of the message. This is a nice format for debugging, because you can use your favorite terminal emulator.


No comments:

Post a Comment

arduino - Can I use TI's cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...