system
June 10, 2009, 6:41pm
1
Hello All,
I'm very basic and have a basic question (did search but couldn't find an answer)
I'm expecting to receive two characters from serial port but as I understand arduino receives one character at a time. I would highly appreciate if someone could guide me the way to receive more than one characters and how to use it a single value (i.e. x="abc")
thank you for your time and help
cheers
system
June 10, 2009, 7:00pm
2
You can map each reading onto a char array. Then just read the char array.
char input[2];
if(Serial.available()) {
input[0] = Serial.read();
input[1] = Serial.read();
}
Serial.print(input);
This does ignore the fact that there might not be data there for both reads.
system
June 10, 2009, 7:01pm
3
This code will echo a recieved string back to you. The last four characters will be printed.
const byte MAX_LENGTH_OF_INPUT = 4;
char recieved[MAX_LENGTH_OF_INPUT+1] = {'\0'};
void setup ()
{
Serial.begin(9600);
}
void loop ()
{
byte index = 0;
if (Serial.available()) {
delay( 50 );
do {
recieved[index++]=Serial.read();
} while(Serial.available()&&index<MAX_LENGTH_OF_INPUT);
}else{
Serial.println(recieved);
}
}
system
June 10, 2009, 7:01pm
4
if(Serial.available()) {
input[0] = Serial.read();
input[1] = Serial.read();
}
What if "Serial.available()" only returns 1?
system
June 10, 2009, 7:15pm
5
Yep AWOL. I put a note at the end that said it assumes there is data for both available.
system
June 10, 2009, 7:47pm
6
you guys rock, thanks a lot "icecool2" n "AlphaBeta"
westfw
June 10, 2009, 8:52pm
7
What you want is probably something like:
void serial_readstring(byte *buffer, byte length)
{
while (length > 0) {
if (Serial.available()) {
*buffer++ = Serial.read();
length -= 1;
}
}
}
Call it like:
byte serialbuf[10];
void loop()
{
serial_readstring(serialbuf, 5);
Serial.println((char *)serialbuf);
}
system
June 11, 2009, 3:04am
8
lovely that should do the trick for me
cheers westfw