我正在制作一个非常简单的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");因为它甚至没有写“给我角度”的信息。
例如,当我在打开函数中写入错误的端口时,它会写入消息。
的确, ”Linux 中的一切都是文件”,但不是字面上的 --> 本质是哪种类型的文件 - 在您的情况下,您将端口视为普通文件(即类似 txt 文件的文件),而您需要将其视为device文件,所以没有fopen
but :
fd = open("/dev/tty.usbmodem3a21", O_RDWR | O_NOCTTY | O_NDELAY);
The 下列的 https://www.cmrr.umn.edu/~strupp/serial.html#CONTENTS是关于串口文件接口的一个很好的参考
和这个one https://github.com/todbot/arduino-serial/blob/master/arduino-serial-lib.c甚至是面向arduino的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)