Reputation: 81
i need communicate with the arduino by using C++,i have tried this code for c++:
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int j=5;
main()
{
fstream arduino;
arduino.open("/dev/ttyACM0",ios::in | ios::out);
//Opening device file
if(!arduino)
cout<<"error";
arduino<<2;
arduino.clear();
arduino>> j;
cout <<j;
arduino.close();
return 0;
}
Arduino code:
int p;
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
p=Serial.read();
if(p!=-1)
{
Serial.write(1);
digitalWrite(13,HIGH);
delay(5000);
}
}
else
{
digitalWrite(13,LOW);
delay(1000);
}
}
So according to this code when ever c++ code runs the led of pin 13 on arduino sould glow for 5 seconds and cout should print 1. But instead the led is not glowing and cout is printing 5 which(see that initially j=5).I am using this program to test serial communication between c++ and arduino. But I don't know what's happening.Also do we require any any special library for serial communication? Is my code alright? Please help me out.
Upvotes: 1
Views: 1628
Reputation: 944
If j
keeps its old value, it is likely that the attempt to read it is failing. Try checking the stream state, and checking for possible error conditions. For example:
if(arduino >> j)
cout << "Value received: " << j << '\n';
else if(arduino.eof())
cerr << "Premature EOF.\n";
else if(arduino.bad())
cerr << "Attempt to read from device failed.\n";
else
cerr << "Logical I/O error.\n";
Upvotes: 0