适用系统 :Linux,Qt for Android
直接上代码
头文件
#ifndef SERIALPORT_H
#define SERIALPORT_H
#include <fcntl.h>
#include <string>
#include <termios.h>
#include <unistd.h>
class SerialPort
{
public:
SerialPort(const std::string& portName);
~SerialPort();
bool open();
void close();
int read(unsigned char *buffer, int bufferSize);
int write(const unsigned char *data, int dataSize);
private:
std::string m_portName;
int m_fd; // 文件描述符
};
#endif // SERIALPORT_H
源码
#include "SerialPort.h"
#include <iostream>
SerialPort::SerialPort(const std::string& portName)
: m_portName(portName), m_fd(-1){}
SerialPort::~SerialPort()
{
close();
}
bool SerialPort::open()
{
m_fd = ::open(m_portName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (m_fd == -1)
{
std::cerr << "Failed to open serial port" << std::endl;
return false;
}
struct termios options;
tcgetattr(m_fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr(m_fd, TCSANOW, &options);
return true;
}
void SerialPort::close()
{
if (m_fd != -1)
{
std::cout<<::close(m_fd)<<std::endl;
m_fd = -1;
}
}
int SerialPort::read(unsigned char* buffer, int bufferSize)
{
int bytesRead = ::read(m_fd, buffer, bufferSize);
return bytesRead;
}
int SerialPort::write(const unsigned char *data, int dataSize)
{
int bytesWritten = ::write(m_fd, data, dataSize);
return bytesWritten;
}
下面提供一些调用实例
#include <Serialport.h>
#include <iostream>
int main()
{
SerialPort *m_serialPort = new SerialPort(portname);// 串口设备名和波特率根据实际情况修改
if (!m_serialPort->open())
{
std::cerr << "Failed to connect to serial port" << std::endl;
}
const unsigned char sendData[] = {"hello,world!"};
m_serialPort->write(sendData, sizeof(sendData));
usleep(1000*500);
unsigned char buffer[256] = {0};
int bytesRead = m_serialPort->read(buffer, sizeof(buffer));
for(int i=0;i<bytesRead,i++)
{
std::cout<<buffer[i];
}
std::cout << std::endl;
m_serialPort.close();
}
运行结果