Projet

Général

Profil

Feature #13385 » serial_communication.ino

Anonyme, 10/11/2021 14:59

 
/* TODO
While there is something to read then:
-Check to see if what we read is part of or message OR a terminating character
-If it is part of our message, then save it to a character array
-If it is terminating character, then output the message and prepare for the next message
-If the message has exceeded the max message length in the protocol, then stop reading in any more bytes and output the message

*/

const unsigned int MAX_MSG_LN = 12;

void setup()
{
Serial.begin(115200);

}

void loop()
{
//Check to see anything is available in the serial receive buffer
while (Serial.available())
{
//Create a place to hold the incoming message
static char msg[MAX_MSG_LN];
static unsigned int msg_pos = 0;

//Read the next available byte in the serial receive buffer
char inByte = Serial.read();

//Message coming in (check not terminating character)
if (inByte != '\n' && (msg_pos < MAX_MSG_LN - 1 ))
{
msg[msg_pos] = inByte;
msg_pos++;
}
//Full message received
else
{
msg[msg_pos] = '\0';
//Print the message (or do other things)
Serial.println(msg);

//Or convert to integer and print
//int number = atoi(msg);
// Serial.println(number);

//Reset for the next message
msg_pos = 0;
}
}
}
(2-2/2)