X code,C ++与Arduino的串口 [英] xcode, c++ serial port with arduino
问题描述
我正在做一个非常简单的C ++程序,它发送一个角度通过串口的Arduino然后Arduino的那个角度适用于伺服电机。我知道,Unix的看到串口设备,如一个文件,其实这是C ++ code:
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);
}
这是Arduino的的:
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);
}
}
我也查了Arduino的应用程序,在工具>串行端口> /div/tty.usbmodem3a21,这是正确的端口。
i also checked in the arduino app, in tools>serial port>/div/tty.usbmodem3a21 that it was the right port.
的问题是,程序停止在阿尔杜伊诺=的fopen(的/ dev / tty.usbmodem3a21,W);因为它甚至不写邮件给我的角度。
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.
推荐答案
事实上,一切Linux是一个文件的,而不是字面 - >本质是哪种类型的文件 - 中你的情况,你把港口作为纯香草文件(即类似txt文件),而你需要把它当作一个设备文件,所以没有的fopen
但是:
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);
借助以下是有关的文件接口一个很好的参考串口
这 之一甚至Arduino的导向
The following is a good reference about the file interface of serial ports And this one is even arduino oriented
这篇关于X code,C ++与Arduino的串口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!