Hi guys, I´m trying to receive some serial data at any time, so I found a way to do it using interrupts (credits: My code is bug free.: Arduino : Serial communication with interrupt). In my own tests, I can parse only the first arrangement of data sent over serial, the rest of the data is received with some variations.
My code is:
// To use this example, you have to connect Rx pin (digital pin 0) to interrupt 0 pin (digital pin 2).
int value = 1;
boolean Message_Completed = false;
String Message = "";
void setup()
{
Serial.begin(9600);
attachInterrupt(0, serialInterrupt, CHANGE);
}
void loop()
{
Serial.print(value);
value = value + 1;
delay(1000);
Message = "";
Message_Completed = false;
}
// Volatile, since it is modified in an ISR.
volatile boolean inService = false;
void serialInterrupt()
{
if (inService) return;
inService = true;
interrupts();
while(Serial.available())
{
char ReadChar = (char)Serial.read();
if(ReadChar == '>') // ">" indica el final del string
{
Message_Completed = true;
}
else { Message += ReadChar; }
}
if(Message_Completed)
{
parsedata();
}
inService = false;
value = 1;
}
void parsedata()
{
Serial.println();
Serial.print("Mensaje: ");
Serial.println(Message);
int SP1 = Message.indexOf(',');
Serial.print("SP1: "); Serial.println(SP1);
int SP2 = Message.length();
Serial.print("SP2: "); Serial.println(SP2);
// String Variable = Message.substring(0, SP1);
// Serial.print("Variable: "); Serial.println(Variable);
// String ValorString = Message.substring(SP1+1, SP2);
// Serial.print("ValorString: "); Serial.println(ValorString);
// int Valor = ValorString.toInt();
}
If you want to test it, send RESET,1> over serial, the first try will give this answer:
123
Mensaje: RESET,1
SP1: 5
SP2: 7
Which is OK, the next time the same command is sent, the SPs increment in 2 units:
Mensaje:
RESET,1
SP1: 7
SP2: 9
Which is not OK.
My second problem is that the debug information is shown twice even when in code I only call it once.
Does anybody have an idea what is going on?