Serial read question (newbie)


hi,

i'm complete newbie, , i'm trying stuff out.

why doesn't work expect?
what want use serial monitor send number (as text) , arduino should blink number of times sent. seems read first byte. if add delay of 50, still weird things... supposed read number of bytes returned serial.available() instead of looping , checking if there's more?

thanks million!

code: [select]
int outputpin = 13;
int val;
int counter;
int nroftimestoblink;

void setup()
{
 serial.begin(9600);
 pinmode(outputpin, output);
}

void loop()
{
 counter = 0;
 val = 0;
 nroftimestoblink = 0;
 while (serial.available() > 0) {
   val = serial.read() - 48;
   if (val >= 0 && val < 10)
     nroftimestoblink = (nroftimestoblink * 10) + val;
 }
 
 while (counter < nroftimestoblink) {
   digitalwrite(outputpin, high);
   delay(200);
    digitalwrite(outputpin, low);
   delay(200);
   counter++;
 }
}


arduino diecemilla
arduino - 0011 alpha
ubuntu linux 8.10

mrwhammy,

the problem serial slow compared arduino.  let's typed "50" in serial monitor.  as first '5' arrives, serial.available() returns 1, top loop goes work , nroftimestoblink set 5.  now serial.available called again.  the '0' still isn't due arrive until many, many microseconds later, loop terminates , second loop causes 5 blinks.  now we're top.  the '0' has arrived.  this causes nroftimestoblink set 0, obvious results.

two solutions come mind: (a) force count 2 characters long , wait in top loop until serial.available() == 2, or (b) invent kind of termination character, $, must type, , break out of upper loop when see it.

mikal


Arduino Forum > Forum 2005-2010 (read only) > Software > Syntax & Programs > Serial read question (newbie)


arduino

Comments

Popular posts from this blog

CAN'T INSTALL MAMBELFISH 1.5 FROM DIRECTORY - Joomla! Forum - community, help and support

error: expected initializer before 'void'

CPU load monitoring using GPIO and leds - Raspberry Pi Forums