xcode, c++ 串口与arduino [英] xcode, c++ serial port with arduino
问题描述
我正在制作一个非常简单的 C++ 程序,它通过串行端口向 arduino 发送一个角度,然后 arduino 将该角度应用于伺服电机.我知道Unix把串口设备看成一个文件,其实这是c++代码:
#include #include 使用命名空间标准;int main(){国际角;文件 * arduino;做{arduino = fopen("/dev/tty.usbmodem3a21","w");cout<<"\n\给我角度\n\n";cin>>angole;fprintf(arduino,"%d",angole);睡眠(1);}while(angole>=0 &&angole<=179);}
这是 arduino 的:
#include 伺服伺服;const int pinServo = 2;内角;无效设置(){Serial.begin(9600);伺服.attach(pinServo);伺服.写(0);}空循环(){if(Serial.available()>0){角度 = Serial.read();伺服.写(角度);}}
我还检查了 arduino 应用程序,在工具>串行端口>/div/tty.usbmodem3a21 中,它是正确的端口.
问题是程序停在arduino = fopen("/dev/tty.usbmodem3a21","w");因为它甚至没有写给我角度"的信息.
例如,当我在 open 函数中写入错误的端口时,它会写入消息.
确实,Linux 中的一切都是文件",但不是字面意思 --> 本质是哪种类型的文件 - 在在您的情况下,您将端口视为普通的 vanilla 文件(即类似 txt 文件的文件),而您需要将其视为 device 文件,因此没有 fopen
而是:
fd = open("/dev/tty.usbmodem3a21", O_RDWR | O_NOCTTY | O_NDELAY);
以下是一个很好的参考串口而这个 one 甚至是面向 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. I know that Unix see serial ports device like a file, in fact this is the c++ code:
#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:
#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.
The problem is that the program stops at 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.
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 (i.e. something like txt file) while you need treating it as a device file, so no fopen
but :
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
这篇关于xcode, c++ 串口与arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!