[英]xcode, c++ serial port with arduino
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. 我正在制作一个非常简单的c ++程序,它通过一个串口向arduino发送一个角度,然后arduino将这个角度应用到伺服电机上。 I know that Unix see serial ports device like a file, in fact this is the c++ code:
我知道Unix看到串口设备就像一个文件,实际上这是c ++代码:
#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: 这是arduino的:
#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. 我还检查了arduino应用程序,在工具>串口> /div/tty.usbmodem3a21中,它是正确的端口。
The problem is that the program stops at arduino = fopen("/dev/tty.usbmodem3a21","w"); 问题是程序停在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. 例如,当我在open函数中写入错误的端口时,它会写入消息。
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 (ie something like txt file) while you need treating it as a device file, so no fopen
but : 实际上,“ Linux中的所有内容都是文件 ”,但不是字面意思 - >本质上是哪种类型的文件 - 在您的情况下,您将端口视为普通的文件(即类似txt文件),而您需要将其视为设备文件,所以没有
fopen
但是:
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 在下面是关于串口的文件接口一个很好的借鉴和这一个甚至Arduino的导向
我得到了这段代码的连接:
arduino = open("/dev/tty.usbmodemfa131", O_RDWR | O_NOCTTY | O_NDELAY);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.