问题
i’m making a very simple c++ program which send an angle to arduino through a serial port and then arduino apply that angle to a servo-motor. I know that Unix see serial ports device like a file, in fact this is the c++ code:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
int angole;
FILE * arduino;
do
{
arduino = fopen("/dev/tty.usbmodem3a21","w");
cout<<"\n\give me the angle\n\n";
cin>>angole;
fprintf(arduino,"%d",angole);
sleep(1);
}while(angole>=0 && angole<=179);
}
and this is arduino’s:
#include <Servo.h>
Servo servo;
const int pinServo = 2;
int angle;
void setup()
{
Serial.begin(9600);
servo.attach(pinServo);
servo.write(0);
}
void loop()
{
if(Serial.available()>0)
{
angle = Serial.read();
servo.write(angle);
}
}
i also checked in the arduino app, in tools>serial port>/div/tty.usbmodem3a21 that it was the right port.
The problem is that the program stops at arduino = fopen("/dev/tty.usbmodem3a21","w"); because it doesn’t even write the message "give me the angle".
for instance , when i write the wrong port in the open function , it writes the message.
回答1:
Indeed, "everything in Linux is a file", but not literally --> the essence is which type of file - in your case you treat the port as plain vanilla file (i.e. something like txt file) while you need treating it as a device file, so no fopen
but :
fd = open("/dev/tty.usbmodem3a21", O_RDWR | O_NOCTTY | O_NDELAY);
The following is a good reference about the file interface of serial ports And this one is even arduino oriented
回答2:
I got connection with this code:
arduino = open("/dev/tty.usbmodemfa131", O_RDWR | O_NOCTTY | O_NDELAY);
来源:https://stackoverflow.com/questions/27515210/xcode-c-serial-port-with-arduino