[英]Open a serial port with arduino using c++ with Xcode on mac
我用 C++ 編寫了一個簡單的程序,它通過串行端口向 Arduino 發送一個角度值; Arduino 然后使用該值來控制伺服電機。
這是 C++ 代碼
#include <iostream>
#include <unistd.h>
#include <fstream>
using namespace std;
int main()
{
unsigned int angle;
fstream arduino;
cout<<"check-1";
arduino.open("/dev/tty.usbmodem3a21");
cout<<"check-2";
if(arduino)
{
do
{
cout<<"\n\ninsert a number between 0 and 179";
cin>>angle;
arduino<<angle;
}while(angle <= 179);
arduino.close();
}
else
{
cout<<"\n\nERROR!!\n\n";
}
}
這是 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);
}
}
}
問題是它停在arduino.open(...)
。 盡管我在工具 > 串行端口中檢查了 Arduino 應用程序中選擇的端口是否正確,但它甚至沒有打印出“check-1”。
為了添加更多有用的信息,我測試了使用iOS::binary
參數打開端口,因此打開命令變為arduino.open("/dev/tty.usbmodem3a21",iOS::binary)
; 結果,這會打印出“check-1”、“check-2”和“ERROR!!”。 如果輸入錯誤的串行端口名稱,我會得到相同的結果。
為什么會發生這種情況,我該如何解決?
arduino 顯示為串行設備。 您應該考慮使用open()
和close()
函數。 我已經在 Linux 上完成了這項工作,但我很確定這在 Mac 上的工作方式類似。 這是一個示例代碼片段。 第一個片段打開並設置文件描述符。
int fd; // File descriptor
// Open port
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1){
printf("Device cannot be opened.\n");
exit(-1); // If the device is not open, return -1
}
struct termios options;
fcntl(fd, F_SETFL, FNDELAY); // Open the device in nonblocking mode
// Set parameters
tcgetattr(fd, &options); // Get the current options of the port
bzero(&options, sizeof(options)); // Clear all the options
speed_t Speed;
switch (baudRate) // Set the speed (baudRate)
{
case 110 : Speed=B110; break;
case 300 : Speed=B300; break;
case 600 : Speed=B600; break;
case 1200 : Speed=B1200; break;
case 2400 : Speed=B2400; break;
case 4800 : Speed=B4800; break;
case 9600 : Speed=B9600; break;
case 19200 : Speed=B19200; break;
case 38400 : Speed=B38400; break;
case 57600 : Speed=B57600; break;
case 115200 : Speed=B115200; break;
default : exit(-4);
}
cfsetispeed(&options, Speed); // Set the baud rate at 115200 bauds
cfsetospeed(&options, Speed);
options.c_cflag |= ( CLOCAL | CREAD | CS8); // Configure the device : 8 bits, no parity, no control
options.c_iflag |= ( IGNPAR | IGNBRK );
options.c_cc[VTIME]=0; // Timer unused
options.c_cc[VMIN]=0; // At least on character before satisfy reading
tcsetattr(fd, TCSANOW, &options); // Activate the settings
這只是關閉它:
close(fd);
從實際的文件描述符中讀取:
ioctl(fd, FIONREAD, &t1);
if(t1 > 0) {
// If the number of bytes read is equal to the number of bytes retrieved
if(read(fd,pByte, t1) == t1) {
for(int i =0; i < t1; i++) {
if(pByte[i] != '\r'){ // Just makes sure you're not scanning new lines
// TODO: Do what you want with this character
}
}
}
}
在用c++程序發送命令之前你應該做的第一件事是正確配置串口,你只需讓串口閉環,你發送的所有東西都應該收到,如果你沒有收到任何東西你有串口配置問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.