Xcode,C++与Arduino串口的相关问题

3

我正在制作一个非常简单的C++程序,通过串口将一个角度发送到Arduino,然后Arduino将该角度应用于舵机。我知道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);

}

这是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);
    }
}

我还检查了Arduino应用程序中的“工具>串行端口>/div/tty.usbmodem3a21”,确认它是正确的端口。
问题在于程序停在了"arduino = fopen("/dev/tty.usbmodem3a21","w");"这一句,因为它甚至没有写出"give me the angle"这个消息。
例如,当我在打开函数中输入错误的端口时,它会写出该消息。
2个回答

2
实际上,“Linux 中的所有东西都是文件”,但并非字面意义上的 —— 本质是哪种类型的文件 - 在您的情况下,您将端口视为普通的香草文件(即类似于 txt 文件),而您需要将其视为设备文件,因此不能使用fopen,而应该使用:
fd = open("/dev/tty.usbmodem3a21", O_RDWR | O_NOCTTY | O_NDELAY);

以下是有关串口文件接口的良好参考资料。 而这个则更加面向Arduino。

我仍然有一些问题,请看下面的评论。 - Dadda Barba

0

我用这段代码建立了连接:

arduino = open("/dev/tty.usbmodemfa131", O_RDWR | O_NOCTTY | O_NDELAY);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接