Arduino не читает отправленный через порт текст, но видит \n
Т.Е. при использовании кода под Linux строка с ардуино получается вроде правильно, а вот передача как-то неправильно работает. Arduino подключается через USB, и в ОС виден как usbtty. При попытке отправить строку, он должен отправить её обратно, если получает \n, но он ничего не отправляет обратно, хотя \n правильно считывается, и ардуино пытается отправить принятое обратно. При попытке просто отправить любую строку при получении \n то всё работает правильно. Кроме того, при попытке отправить одну и ту же строку периодически количество принятых байт меняется, хотя текст не менялся. Из Arduino IDE всё нормально работает. P.S. простите за возможные глупые ошибки, нас с паскаля сразу на ассемблер кинули без C++, пришлось самоучиваться :) Код ардуино:
void setup()
{
Serial.begin(9600);
}
String inString = "";
void loop()
{
while (Serial.available() > 0)
{
int inChar = Serial.read();
if (inChar == '\n')
{
Serial.println(inString);
inString = "";
}
else inString += (char)inChar;
}
}
Код C++ для Linux:
// C library headers
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
// Linux headers
#include <fcntl.h> // Contains file controls like O_RDWR
#include <errno.h> // Error integer and strerror() function
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()
int main()
{
// Open the serial port. Change device path as needed (currently set to an standard FTDI USB-UART cable type device)
int serial_port = open("/dev/ttyUSB0", O_RDWR);
// Create new termios struc, we call it 'tty' for convention
struct termios tty;
memset(&tty, 0, sizeof tty);
// Read in existing settings, and handle any error
if(tcgetattr(serial_port, &tty) != 0)
{
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
}
/// /// /// /// /// ///
tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag |= CS8; // 8 bits per byte (most common)
tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
// tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX)
// tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX)
tty.c_cc[VTIME] = 10; // Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
tty.c_cc[VMIN] = 0;
/// /// /// /// /// ///
// Set in/out baud rate to be 9600
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
// Save tty settings, also checking for error
if (tcsetattr(serial_port, TCSANOW, &tty) != 0)
{
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
}
L1:
// Allocate memory for read buffer, set size according to your needs
char read_buf [256];
memset(&read_buf, '\0', sizeof(read_buf));
// Read bytes. The behaviour of read() (e.g. does it block?,
// how long does it block for?) depends on the configuration
// settings above, specifically VMIN and VTIME
int num_bytes = read(serial_port, &read_buf, sizeof(read_buf));
// n is the number of bytes read. n may be 0 if no bytes were received, and can also be -1 to signal an error.
if (num_bytes < 0)
{
printf("Error reading: %s", strerror(errno));
}
// Here we assume we received ASCII data, but you might be sending raw bytes (in that case, don't try and
// print it to the screen like this!)
printf("Read %i bytes. Received message: %s", num_bytes, read_buf);
tcflush(serial_port, TCIFLUSH);
printf("Enter command: ");
std::string str;
std::cin >> str;
str += "\n";
const char * msg;
msg = str.c_str();
//msg += '\n';
// Write to serial port
//unsigned char msg[] = { 'h', 'e', 'l', 'p', '\n'};
write(serial_port, msg, sizeof(msg));
goto L1;
if (getchar() == '\n')
{
close(serial_port);
return 0;
}
else
{
goto L1;
}
}
Ответы (2 шт):
- для начала попробуйте уменьшить скорость до 9600-38400. это железо, на кабель между устройствами могут быть наводки, напр., wifi.
- приём на линуксе с консоли можно организовать через
cat </dev/ttyUSB0и менять параметры данного терминала через stty - после получения устойчивого обмена, просмотрите полученные параметры stty и скопируйте в ваш c-код.
- пересмотрите готовые примеры arduino-проектов.
- могу ошибаться, если вы не применяете RTS/CTS (соответствующие контакты на разьёмах, 5 проводов в кабеле), то следует использовать XON/XOFF, где используются только 3 провода.
Наверное всё-таки не так
write(serial_port, msg, sizeof(msg));
а вот так
write(serial_port, msg, strlen(msg));