简体   繁体   中英

serial communication with ARDUINO in C++

#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;

char j='a';
main()
{
fstream arduino;
arduino.open("/dev/ttyACM0",ios::in | ios::out);
//Opening device file

if(!arduino)
cout<<"error";
arduino<<2;
arduino.clear();
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";
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);
        } 
    }

i have tried this code in C++ for serial communication with the arduino. i got an error "premature eof". what is the problem here??

Assuming your arduino is actually connected to that port and echoing what it receives, you have to take two things into account: a) Before your arduino code gets control of the serial port, it first tries to load the serial bootloader, so it is possible for the first bytes of communication to never reach your code. b) Even if it does, arduino is probably way slower than your computer and it may not have time to process the answer before you do the check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM