Hey there, looking to get a second opinion on the following code:
unsigned long serialdata;
int inbyte;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()){
getSerial();
}
}
long getSerial()
{
serialdata = 0;
while (inbyte != '/')
{
inbyte = Serial.read();
if (inbyte > 0 && inbyte != '/')
{
serialdata = serialdata * 10 + inbyte - '0';
}
}
Serial.println(serialdata);
return serialdata;
inbyte = 0;
}
It prints the first serialdata value, but any value after that it prints 0. Have no idea why...
Well, let's see...suppose the incoming data is "123/"
long getSerial()
{
serialdata = 0;
while (inbyte != '/')
{
inbyte = Serial.read();
if (inbyte > 0 && inbyte != '/')
{
serialdata = serialdata * 10 + inbyte - '0';
}
}
Serial.println(serialdata);
return serialdata;
inbyte = 0;
}
On the first read, a '1' is read, so we find serialdata is 0, so we end up with ASCII 49 - ASCII 48 equals 1, so serialdata now equals 1. When the 2 comes in, we get 1 * 10 + 2 = 12. When the 3 comes in we get 12 * 10 + 3 = 123. The next byte is your termination character, so it appears that this is a convoluted replacement for atol().
BTW, the inbyte = 0 statement at the bottom is never executed and you could simplify the code by using Serial.readBytesUntil().
return serialdata;
inbyte = 0;
What is the reason for the useless code after the return statement?