[英]No data sent over serial port in linux c++
TL; DR-我正在嘗試使用我在這里找到的代碼與Arduino進行串行通信,但沒有任何東西被發送出去(Arduino已編程為響應,並且我檢查了它是否與串行監視器兼容)
嗨,我在尋找一種通過C ++通過Linux串行端口將信息發送到Arduino Mega(2560)單元的方法。
我遇到了以下解決方案: 解決方案我正在使用此人的代碼進行寫操作(我能夠從arduino讀取數據)並使用相同的參數(它們起作用了,因為我能夠從Ardunio接收數據) 。 我對Arduino進行編程,以便每當看到至少1位信息時都通過串行發送“ Hi”,然后通過Arduino IDE串行監視器檢查其是否工作。
但是,在運行C ++代碼時,arduino不會響應。 有人知道為什么嗎?
全面披露-我將@ Lunatic999的代碼插入到一個類中,以便我可以根據自己的代碼需要為其創建一個實例。
fd = open(portNameC, O_RDWR | O_NOCTTY | O_SYNC); //open port ("opens file")
串行參數:
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B19200);
cfsetispeed (&tty, (speed_t)B19200);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
編寫 (此代碼已放入我調用的函數中)
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( fd, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
Arduino代碼:
bool dataRecieved = false;
int ledpin = 13;
void setup() {
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(19200);
}
void loop() {
while(!dataRecieved)
{
digitalWrite(ledpin,HIGH);
if (Serial.available() > 0)
{
dataRecieved = true;
}
}
digitalWrite(ledpin,LOW);
delay(1000);
digitalWrite(ledpin,HIGH);
delay(1000);
Serial.println("hi");
}
原來,這一直是一個難題。 我需要應用一些usleep來讓arduino引導加載
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.