xcode,带有arduino的c ++串口
我正在制作一个非常简单的c ++程序,它通过一个串口向arduino发送一个角度,然后arduino将这个角度应用到伺服电机上。 我知道Unix看到串口设备就像一个文件,实际上这是c ++代码:
#include #include using namespace std; int main() { int angole; FILE * arduino; do { arduino = fopen("/dev/tty.usbmodem3a21","w"); cout<>angole; fprintf(arduino,"%d",angole); sleep(1); }while(angole>=0 && angole<=179); }
这是arduino的:
#include 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); } }
我还检查了arduino应用程序,在工具>串口> /div/tty.usbmodem3a21中,它是正确的端口。
问题是程序停在arduino = fopen(“/ dev / tty.usbmodem3a21”,“w”); 因为它甚至没有写消息“给我角度”。
例如,当我在open函数中写入错误的端口时,它会写入消息。
实际上,“ Linux中的所有内容都是文件 ”,但不是字面意思 – >本质上是哪种类型的文件 – 在您的情况下,您将端口视为普通的文件(即类似txt文件),而您需要将其视为设备文件,所以没有fopen
但是:
fd = open("/dev/tty.usbmodem3a21", O_RDWR | O_NOCTTY | O_NDELAY);
以下是关于串口文件接口的一个很好的参考,这个甚至是面向arduino的
我上传了代码,现在这是Xcode(c ++)代码:
#include #include #include #include #include #include using namespace std; int main() { string angle; int arduino; cout<<" i'm going to connect \n\n"; do { cout<<"\n\n i'm in the loop \n\n"; arduino = open("/dev/tty.usbmodem3a21", O_WRONLY); cout<<"\n\n i'm going to check the connection\n\n"; if(arduino == -1) { cout<<"\n\n error \n\n"; } else { do { cout<<"\n\n write a letter between a and c \n\n"; cin>>angle; write(arduino,&angle,1); }while(angle=="a" || angle=="b" || angle=="c"); } }while(arduino == -1); close(arduino); }
这是arduino的:
#include Servo servo; const int pinServo = 2; char angle; void setup() { Serial.begin(9600); servo.attach(pinServo); servo.write(0); } void loop() { if(Serial.available()>0) { angle = Serial.read(); if(&angle=="a") { servo.write(20); } else if(&angle == "b") { servo.write(90); } else if(&angle == "c") { servo.write(180); } else { servo.write(0); } } }
我仍然有同样的问题,它写道“我要连接”和“我在循环中”然后什么都没有,所以它停在open
函数,我认为代码也可能有更多的问题。
是否有c ++代码可以从arduino中获取某些反馈以及它应该是什么?
我也确定连接不是时间问题,我让它运行了很长时间。
我得到了这段代码的连接:
arduino = open("/dev/tty.usbmodemfa131", O_RDWR | O_NOCTTY | O_NDELAY);