Go Down

Topic: Help in serial communication (Read 8241 times) previous topic - next topic

Sep 05, 2013, 03:47 pm Last Edit: Sep 07, 2013, 01:32 pm by AWOL Reason: 1
Aim : send "hello" to Arduino. Arduino sends back "hi" if "hello" is received, else it sends "write hello"...via serial comm.
Code: [Select]

int x = 0;
char buffer[5];
char reply1[] = "hi";
char reply2[] = "write hello";
int i = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
if (Serial.available() > 0&&i<5)
{
buffer[i]=Serial.read();
i++;
}

if(i==5)
{
if(buffer[0]=='h'&&buffer[1]=='e'&&buffer[2]=='l'&&buffer[3]=='l'&&buffer[4]=='o')
{
Serial.write(reply1);
i=0;
}
else
{
Serial.write(reply2);
for (int x=0; x<5; x++)
{
buffer[x]='\0';
}
Serial.flush();
i=0;
}
}
}

This code works when i type hello in serial monitor window...but for other strings, it doesn't work.
I know the logic in the code is wrong somewhere...but can't figure it out. :(
Please HELP!!


Moderator edit: code tags.

Abhik

Hi,
I checked your code by uploading it into my Arduino and the code seems to work pretty well. Can you describe your problem in detail; as simply saying "it doesn't work" explains noting about the problem.
I think limiting the length of your 'buffer' array may be a part of the problem that you are facing. Also, try to replace
Code: [Select]

if (Serial.available() > 0&&i<5)
{
    buffer[i]=Serial.read();
    i++;
}

with a loop.

Hey Abhik!
Thanks,
You're right. I tried increasing the length of the buffer. I also added a longer pause to let the buffer fill completely. It worked!

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy