2

我写了一个代码来连接,通过一个串口,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<<"\n\ntest1\n\n";

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

    cout<<"\n\ntest2\n\n";

    if(!arduino)
    {
        cout<<"\n\nERR: could not open port\n\n";
    }
    else
    {
        if(tcgetattr(arduino,&ttable)<0)
        {
            cout<<"\n\nERR: could not get terminal options\n\n";
        }
        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<<"\n\nERR: could not set new terminal options\n\n";
            }
            else
            {
                do
                {
                    cout<<"\n\ninsert a number between 0 and 179";
                    cin>>angle;
                    arduino<<angle;
                }while(angle<=179);

                arduino.close();
            }
        }
    }

}

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

4

1 回答 1

2

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

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");

一切顺利,您有效地传递1tcgetattr()and tcsetattr(),这是标准输入文件描述符。


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

int arduino = open("/dev/tty.usbmodem3a21",O_WRONLY);
于 2014-12-28T12:50:33.723 回答