Pages: [1]   Go Down
Author Topic: Help in serial communication  (Read 7641 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Aim : send "hello" to Arduino. Arduino sends back "hi" if "hello" is received, else it sends "write hello"...via serial comm.
Code:
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. smiley-sad
Please HELP!!


Moderator edit: code tags.
« Last Edit: September 07, 2013, 06:32:13 am by AWOL » Logged

Bokaro, Jharkhand, India
Offline Offline
Jr. Member
**
Karma: 1
Posts: 61
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
if (Serial.available() > 0&&i<5)
{
    buffer[i]=Serial.read();
    i++;
}
with a loop.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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!
Logged

Pages: [1]   Go Up
Jump to: