0
#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??

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For the first problem, try reading whatever may be on the serial port at the beginning of your program, before you send anything. For the second problem, try std::this_thread::sleep_for, and delay your program a bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.