Linux читать, писать Arduino серийный

Я пытаюсь записать в сериал Arduino из программы на C ++. Как установить скорость передачи в программе C ++? Связь, кажется, работает, когда arduino установлен на 9600, но не удается, когда я изменяю его, как и ожидалось. (Поэтому 9600 по умолчанию?) Используя команду, чтобы увидеть выходные данные:
screen / dev / ttyUSBx 115200
Используя пример программы, чтобы отобразить все, на Arduino:

* serial_echo.pde
* -----------------
* Echoes what is sent back through the serial port.
*
* http://spacetinkerer.blogspot.com
*/

int incomingByte = 0;    // for incoming serial data

void setup() {
Serial.begin(115200);    // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) ;
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print((char)incomingByte);
}

и код C ++:

#include <iostream>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

using namespace std;

string comArduino(string outmsg = " hello"){

#define comports_size 3

static int fd_ard;
static bool init = false;
//char buffer[256];

if(!init){
string comports[] = { "/dev/ttyUSB0","/dev/ttyUSB1","/dev/ttyUSB2" };
for(int i = 0; i < comports_size; i++){

fd_ard = open(comports[i].c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (fd_ard != -1) {
cout<<"connected to "<<comports[i]<<endl;
init = true;
break;
}
else{
perror ("open");
}
if(i == (comports_size - 1)){
cout<<"can't connect to arduino [ ER ]\n"<<endl;
return "";
}
}
}
int Er = write(fd_ard,outmsg.c_str(),strlen(outmsg.c_str()));
if(Er < strlen(outmsg.c_str())){
perror ("write ");
init = false;
}
else
cout<<"write ok"<<endl;
return "";
}
int main(){
while(1){
comArduino();
sleep(1);
}
}

Редактировать: необходимо добавить следующие строки после open() правильно настроить сериал:

    struct termios PortConf;
// write port configuration, as ' stty -F /dev/ttyUSB0 -a ' returned after opening the port with the arduino IDE.
tcgetattr(fd_ard, &PortConf);                           // Get the current attributes of the Serial port
PortConf.c_cflag = 0;                                 //set cflag
PortConf.c_cflag |= (CS8 | HUPCL | CREAD | CLOCAL);

PortConf.c_iflag = 0;                                 //set iflag
//PortConf.c_iflag &= ~(ISIG | ICANON | IEXTEN);

PortConf.c_oflag = 0;                                 //set oflag
PortConf.c_oflag |= (ONLCR | CR0 | TAB0 | BS0 | VT0 | FF0); //NR0 is supposed to be set, but won't compile
//PortConf.c_oflag &= ~(OPOST);

PortConf.c_lflag = 0;                                 //set lflag
//PortConf.c_lflag &= ~(ECHO | ECHOE);

PortConf.c_cc[VMIN]  = 0;
PortConf.c_cc[VTIME] = 0;

cfsetispeed(&PortConf,B115200);                       // Set Read  Speed as 115200
cfsetospeed(&PortConf,B115200);                       // Set Write Speed as 115200

if((tcsetattr(fd_ard,TCSANOW,&PortConf)) != 0){       // Set the attributes to the termios structure
printf("Error while setting attributes \n");
return "";
}

-1

Решение

Вам необходимо установить скорость передачи данных любого порта, который вы используете, используя структуру termios.

Используйте «man termios», чтобы получить больше информации о структуре termios

Так что для начала нужно добавить

#include <termios.h>

В начало вашего кода.

позже, когда вы откроете свой порт:

fd_ard = open(comports[i].c_str(), O_RDWR | O_NOCTTY | O_NDELAY);

Вам необходимо получить доступ к структуре termios и изменить ее в соответствии с вашими потребностями.

struct termios SerialPortSettings;  // Create the structure
tcgetattr(fd_ard, &SerialPortSettings); // Get the current attributes of the Serial port

Затем установите скорость

cfsetispeed(&SerialPortSettings,B115200); // Set Read  Speed as 115200
cfsetospeed(&SerialPortSettings,B115200); // Set Write Speed as 115200

Затем внесите изменения

if((tcsetattr(fd_ard,TCSANOW,&SerialPortSettings)) != 0) // Set the attributes to the termios structure
printf("Error while setting attributes \n");

Существует множество других вещей, которые можно настроить для управления потоком, канонического режима и т. Д., Которые могут повлиять на способ отправки и получения данных. Обратитесь к странице руководства или обратитесь к Это описание общего интерфейса терминала

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector