C++中的串行端口,Unix

Serial port in c++ , Unix

本文关键字:Unix 串行端口 C++      更新时间:2023-10-16

我写了一个代码,通过串行端口将mi计算机连接到arduino。

这是arduino的代码:

#include <Servo.h>
Servo servo;
const int pinServo = 2;
unsigned int angle;
void setup()
{
    Serial.begin(9600);
    servo.attach(pinServo);
    servo.write(0);
}
void loop()
{
    if(Serial.available()>0)
    {  
       angle = Serial.read();
       if(angle <= 179)
       {
         servo.write(angle);
       }
    }
}

这是 c++ 的:

#include <iostream>
#include <unistd.h>
#include <fstream>
#include <termios.h>
using namespace std;
int main()
{
    unsigned int angle;
    ofstream arduino;
    struct termios ttable;
    cout<<"nntest1nn";
    arduino.open("/dev/tty.usbmodem3a21");
    cout<<"nntest2nn";
    if(!arduino)
    {
        cout<<"nnERR: could not open portnn";
    }
    else
    {
        if(tcgetattr(arduino,&ttable)<0)
        {
            cout<<"nnERR: could not get terminal optionsnn";
        }
        else
        {
            ttable.c_cflag &= ~PARENB;
            ttable.c_cflag &= ~CSTOPB;
            ttable.c_cflag &= ~CSIZE;
            ttable.c_cflag |= CS8;
            ttable.c_cflag &= ~CRTSCTS;
            ttable.c_cflag |= CREAD | CLOCAL;
            ttable.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
            ttable.c_oflag &= ~OPOST;
            ttable.c_cc[VMIN]  = 0;
            ttable.c_cc[VTIME] = 0;
            cfsetospeed(&ttable,9600);
            if(tcsetattr(arduino,TCSANOW,&ttable)<0)
            {
                cout<<"nnERR: could not set new terminal optionsnn";
            }
            else
            {
                do
                {
                    cout<<"nninsert a number between 0 and 179";
                    cin>>angle;
                    arduino<<angle;
                }while(angle<=179);
                arduino.close();
            }
        }
    }
}

它应该连接到 arduino ,然后问我一个介于 0 和 179 之间的数字,并将该数字发送到 arduino,该数字适合作为伺服电机的角度;但它止步于arduino.open("/dev/tty.usbmodem3a21").我能做什么?

我认为你的问题出现在这些代码行中

if(tcgetattr(arduino,&ttable)<0) {
    // ...
}
else {
    // ...
    if(tcsetattr(arduino,TCSANOW,&ttable)<0) {
        // ...
    }
}

arduino变量的类型是 ofstream ,其中 tcgetattr()tcsetattr() 期望在这一点上通过open()获得文件描述符。

ofstream提供到 bool 的自动转换,从而隐式int。假设

arduino.open("/dev/tty.usbmodem3a21");

正常,您有效地将1传递给tcgetattr()tcsetattr(),这是标准的输入文件描述符。


解决方案不是使用ofstream进行arduino,而是使用普通的文件描述符

int arduino = open("/dev/tty.usbmodem3a21",O_WRONLY);