我正在尝试在我的计算机和我的 arduino 之间建立一个串行通信通道。当我查看 ArduinoIDE 时,我收到了从 arduino 发送的完美消息 - 3 个相同的数字。现在,我正在尝试创建一个 c++ 应用程序来在运行 Ubuntu 的计算机上读取该数据,但是我在字符串上得到了很多垃圾。我一直在阅读和搜索,但没有成功。谁能帮我找到问题的根源?
代码:
串行通信.h:
#ifndef SERIALCOMM_HPP
#define SERIALCOMM_HPP
#include <fstream>
#include <string>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitionss
class SerialComm {
public:
SerialComm() noexcept {
}
virtual ~SerialComm() noexcept {
tcsetattr(fd, TCSANOW, &port_settings);
close(fd);
}
void begin(std::string port, speed_t baudrate);
std::string read_data();
private:
int fd;
speed_t _baudrate;
std::string _port;
static constexpr int BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE];
termios port_settings;
};
SerialComm.cpp
#include "SerialComm.hpp"
#include <iostream>
using namespace std;
void SerialComm::begin(string porta, speed_t baudrate) {
_port = porta;
_baudrate = baudrate;
// abre a porta
fd = open(_port.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
printf((string("Unable to open port ") + _port).c_str());
} else {
fcntl(fd, F_SETFL, 0);
printf("port is open.\n");
}
cfsetispeed(&port_settings, _baudrate); // set baud rates
cfsetospeed(&port_settings, _baudrate);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
}
string SerialComm::read_data() {
int state = 1;
while (true) {
state = read(fd, buffer, BUFFER_SIZE);
if (state > 0)
{
return string( buffer );
}
}
}
主文件
int main(int argc, char* argv[])
{
SerialComm serial;
serial.begin("/dev/ttyACM0", B115200);
for(auto i = 0; i < 100; ++i)
{
cout << serial.read_data() << endl;
}
}
序列号:
double sinal = 0;
void setup()
{
Serial.begin( 115200 );
}
void loop()
{
sinal = analogRead( A0 ) * ( 5.0 / 1024.0 );
Serial.print( "$" );
Serial.print( sinal, 5 );
Serial.print( "," );
Serial.print( sinal, 5 );
Serial.print( "," );
Serial.print( sinal, 5 );
Serial.print( "#\n" );
}
Arduino IDE 输出:
$2.24121,2.24121,2.24121#
$2.24609,2.24609,2.24609#
$2.24121,2.24121,2.24121#
$2.24121,2.24121,2.24121#
$2.24609,2.24609,2.24609#
电脑输出:
$2.24609,2.24?�̯m#
$2.
09375#
$2.2412109375,2.2412109937500#
$2.2460937500,2.2460937500,2.2460937500#
375#
$2.2460937500,2.2460937500,2.2460937500#
$2.
375,2.2412109375#
$2.241210937937500#
$2.2460937500,2.2460937500,2.2460937500#
PS:以上是我能得到的最漂亮的输出。