先使用arduino,做一个串口的重复输入,我手头使用的就是mega版。
在arduino自己的ide中做好配置
这里需要配置好,开发板,处理器还有端口。
程序中先要初始化端口,而后要不断打印“Hello world”
void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.println("Hello world"); delay(1000); }
setup中插入的是初始化的代码,后面的loop中写的是重复执行的指令。
而后就需要编译,并且烧录到板中。我们可以在工具>串口监视器中查看串口输入输出情况
这里需要注意,串口的波特率为9600,校正位 None, 数据位8, 停止位1。
windows下的c++串口读取
在windows下读取USB的做法就是使用 window.h文件。
使用CSerialPort类的 windows.h读取方式。这里附上SerialPort.h
#ifndef SERIALPORT_H_
#define SERIALPORT_H_
#include <Windows.h>
/** 串口通信类
*
* 本类实现了对串口的基本操作
* 例如监听发到指定串口的数据、发送指定数据到串口
*/
class CSerialPort
{
public:
CSerialPort(void);
~CSerialPort(void);
public:
/** 初始化串口函数
*
* @param: UINT portNo 串口编号,默认值为1,即COM1,注意,尽量不要大于9
* @param: UINT baud 波特率,默认为9600
* @param: char parity 是否进行奇偶校验,'Y'表示需要奇偶校验,'N'表示不需要奇偶校验
* @param: UINT databits 数据位的个数,默认值为8个数据位
* @param: UINT stopsbits 停止位使用格式,默认值为1
* @param: DWORD dwCommEvents 默认为EV_RXCHAR,即只要收发任意一个字符,则产生一个事件
* @return: bool 初始化是否成功
* @note: 在使用其他本类提供的函数前,请先调用本函数进行串口的初始化
* /n本函数提供了一些常用的串口参数设置,若需要自行设置详细的DCB参数,可使用重载函数
* /n本串口类析构时会自动关闭串口,无需额外执行关闭串口
* @see:
*/
bool InitPort(UINT portNo = 1, UINT baud = CBR_9600, char parity = 'N', UINT databits = 8, UINT stopsbits = 1, DWORD dwCommEvents = EV_RXCHAR);
/** 串口初始化函数
*
* 本函数提供直接根据DCB参数设置串口参数
* @param: UINT portNo
* @param: const LPDCB & plDCB
* @return: bool 初始化是否成功
* @note: 本函数提供用户自定义地串口初始化参数
* @see:
*/
bool InitPort(UINT portNo, const LPDCB& plDCB);
/** 开启监听线程
*
* 本监听线程完成对串口数据的监听,并将接收到的数据打印到屏幕输出
* @return: bool 操作是否成功
* @note: 当线程已经处于开启状态时,返回flase
* @see:
*/
bool OpenListenThread();
/** 关闭监听线程
*
*
* @return: bool 操作是否成功
* @note: 调用本函数后,监听串口的线程将会被关闭
* @see:
*/
bool CloseListenTread();
/** 向串口写数据
*
* 将缓冲区中的数据写入到串口
* @param: unsigned char * pData 指向需要写入串口的数据缓冲区
* @param: unsigned int length 需要写入的数据长度
* @return: bool 操作是否成功
* @note: length不要大于pData所指向缓冲区的大小
* @see:
*/
bool WriteData(char* pData, unsigned int length);
/** 获取串口缓冲区中的字节数
*
*
* @return: UINT 操作是否成功
* @note: 当串口缓冲区中无数据时,返回0
* @see:
*/
UINT GetBytesInCOM();
/** 读取串口接收缓冲区中一个字节的数据
*
*
* @param: char & cRecved 存放读取数据的字符变量
* @return: bool 读取是否成功
* @note:
* @see:
*/
bool ReadChar(char &cRecved);
private:
/** 打开串口
*
*
* @param: UINT portNo 串口设备号
* @return: bool 打开是否成功
* @note:
* @see:
*/
bool openPort(UINT portNo);
/** 关闭串口
*
*
* @return: void 操作是否成功
* @note:
* @see:
*/
void ClosePort();
/** 串口监听线程
*
* 监听来自串口的数据和信息
* @param: void * pParam 线程参数
* @return: UINT WINAPI 线程返回值
* @note:
* @see:
*/
static UINT WINAPI ListenThread(void* pParam);
private:
/** 串口句柄 */
HANDLE m_hComm;
/** 线程退出标志变量 */
static bool s_bExit;
/** 线程句柄 */
volatile HANDLE m_hListenThread;
/** 同步互斥,临界区保护 */
CRITICAL_SECTION m_csCommunicationSync; //!< 互斥操作串口
};
#endif //SERIALPORT_H_
对应的SerialPort.cpp
#include "StdAfx.h"
#include "SerialPort.h"
#include <process.h>
#include <iostream>
#include <vector>
using namespace std;
/** 线程退出标志 */
bool CSerialPort::s_bExit = false;
/** 当串口无数据时,sleep至下次查询间隔的时间,单位:秒 */
const UINT SLEEP_TIME_INTERVAL = 5;
CSerialPort::CSerialPort(void)
: m_hListenThread(INVALID_HANDLE_VALUE)
{
m_hComm = INVALID_HANDLE_VALUE;
m_hListenThread = INVALID_HANDLE_VALUE;
InitializeCriticalSection(&m_csCommunicationSync);
}
CSerialPort::~CSerialPort(void)
{
CloseListenTread();
ClosePort();
DeleteCriticalSection(&m_csCommunicationSync);
}
bool CSerialPort::InitPort(UINT portNo /*= 1*/, UINT baud /*= CBR_115200*/, char parity /*= 'N'*/,
UINT databits /*= 8*/, UINT stopsbits /*= 1*/, DWORD dwCommEvents /*= EV_RXCHAR*/)
{
/** 临时变量,将制定参数转化为字符串形式,以构造DCB结构 */
char szDCBparam[50];
sprintf_s(szDCBparam, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopsbits);
/** 打开指定串口,该函数内部已经有临界区保护,上面请不要加保护 */
if (!openPort(portNo))
{
return false;
}
/** 进入临界段 */
EnterCriticalSection(&m_csCommunicationSync);
/** 是否有错误发生 */
BOOL bIsSuccess = TRUE;
/** 在此可以设置输入输出的缓冲区大小,如果不设置,则系统会设置默认值.
* 自己设置缓冲区大小时,要注意设置稍大一些,避免缓冲区溢出
*/
/*if (bIsSuccess )
{
bIsSuccess = SetupComm(m_hComm,10,10);
}*/
/** 设置串口的超时时间,均设为0,表示不使用超时限制 */
COMMTIMEOUTS CommTimeouts;
CommTimeouts.ReadIntervalTimeout = 0;
CommTimeouts.ReadTotalTimeoutMultiplier = 0;
CommTimeouts.ReadTotalTimeoutConstant = 0;
CommTimeouts.WriteTotalTimeoutMultiplier = 0;
CommTimeouts.WriteTotalTimeoutConstant = 0;
if (bIsSuccess)
{
bIsSuccess = SetCommTimeouts(m_hComm, &CommTimeouts);
}
DCB dcb;
if (bIsSuccess)
{
// 将ANSI字符串转换为UNICODE字符串
DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, szDCBparam, -1, NULL, 0);
wchar_t *pwText = new wchar_t[dwNum];
if (!MultiByteToWideChar(CP_ACP, 0, szDCBparam, -1, pwText, dwNum))
{
bIsSuccess = TRUE;
}
/** 获取当前串口配置参数,并且构造串口DCB参数 */
bIsSuccess = GetCommState(m_hComm, &dcb) && BuildCommDCB(pwText, &dcb);
/** 开启RTS flow控制 */
dcb.fRtsControl = RTS_CONTROL_ENABLE;
/** 释放内存空间 */
delete[] pwText;
}
if (bIsSuccess)
{
/** 使用DCB参数配置串口状态 */
bIsSuccess = SetCommState(m_hComm, &dcb);
}
/** 清空串口缓冲区 */
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
/** 离开临界段 */
LeaveCriticalSection(&m_csCommunicationSync);
return bIsSuccess == TRUE;
}
bool CSerialPort::InitPort(UINT portNo, const LPDCB& plDCB)
{
/** 打开指定串口,该函数内部已经有临界区保护,上面请不要加保护 */
if (!openPort(portNo))
{
return false;
}
/** 进入临界段 */
EnterCriticalSection(&m_csCommunicationSync);
/** 配置串口参数 */
if (!SetCommState(m_hComm, plDCB))
{
return false;
}
/** 清空串口缓冲区 */
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
/** 离开临界段 */
LeaveCriticalSection(&m_csCommunicationSync);
return true;
}
void CSerialPort::ClosePort()
{
/** 如果有串口被打开,关闭它 */
if (m_hComm != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hComm);
m_hComm = INVALID_HANDLE_VALUE;
}
}
bool CSerialPort::openPort(UINT portNo)
{
/** 进入临界段 */
EnterCriticalSection(&m_csCommunicationSync);
/** 把串口的编号转换为设备名 */
char szPort[50];
sprintf_s(szPort, "COM%d", portNo);
/** 打开指定的串口 */
m_hComm = CreateFileA(szPort, /** 设备名,COM1,COM2等 */
GENERIC_READ | GENERIC_WRITE, /** 访问模式,可同时读写 */
0, /** 共享模式,0表示不共享 */
NULL, /** 安全性设置,一般使用NULL */
OPEN_EXISTING, /** 该参数表示设备必须存在,否则创建失败 */
0,
0);
/** 如果打开失败,释放资源并返回 */
if (m_hComm == INVALID_HANDLE_VALUE)
{
LeaveCriticalSection(&m_csCommunicationSync);
return false;
}
/** 退出临界区 */
LeaveCriticalSection(&m_csCommunicationSync);
return true;
}
bool CSerialPort::OpenListenThread()
{
/** 检测线程是否已经开启了 */
if (m_hListenThread != INVALID_HANDLE_VALUE)
{
/** 线程已经开启 */
return false;
}
s_bExit = false;
/** 线程ID */
UINT threadId;
/** 开启串口数据监听线程 */
m_hListenThread = (HANDLE)_beginthreadex(NULL, 0, ListenThread, this, 0, &threadId);
if (!m_hListenThread)
{
return false;
}
/** 设置线程的优先级,高于普通线程 */
if (!SetThreadPriority(m_hListenThread, THREAD_PRIORITY_ABOVE_NORMAL))
{
return false;
}
return true;
}
bool CSerialPort::CloseListenTread()
{
if (m_hListenThread != INVALID_HANDLE_VALUE)
{
/** 通知线程退出 */
s_bExit = true;
/** 等待线程退出 */
Sleep(10);
/** 置线程句柄无效 */
CloseHandle(m_hListenThread);
m_hListenThread = INVALID_HANDLE_VALUE;
}
return true;
}
UINT CSerialPort::GetBytesInCOM()
{
DWORD dwError = 0; /** 错误码 */
COMSTAT comstat; /** COMSTAT结构体,记录通信设备的状态信息 */
memset(&comstat, 0, sizeof(COMSTAT));
UINT BytesInQue = 0;
/** 在调用ReadFile和WriteFile之前,通过本函数清除以前遗留的错误标志 */
if (ClearCommError(m_hComm, &dwError, &comstat))
{
BytesInQue = comstat.cbInQue; /** 获取在输入缓冲区中的字节数 */
}
return BytesInQue;
}
UINT WINAPI CSerialPort::ListenThread(void* pParam)
{
/** 得到本类的指针 */
CSerialPort *pSerialPort = reinterpret_cast<CSerialPort*>(pParam);
// 线程循环,轮询方式读取串口数据
while (!pSerialPort->s_bExit)
{
UINT BytesInQue = pSerialPort->GetBytesInCOM();
/** 如果串口输入缓冲区中无数据,则休息一会再查询 */
if (BytesInQue == 0)
{
Sleep(SLEEP_TIME_INTERVAL);
continue;
}
/** 读取输入缓冲区中的数据并输出显示 */
char rxByteArray = 0x00;
do
{
rxByteArray = 0x00;
if (pSerialPort->ReadChar(rxByteArray) == true)
{
std::cout << rxByteArray;
}
}while (--BytesInQue);
}
return 0;
}
bool CSerialPort::ReadChar(char &cRecved)
{
BOOL bResult = TRUE;
DWORD BytesRead = 0;
if (m_hComm == INVALID_HANDLE_VALUE)
{
return false;
}
/** 临界区保护 */
EnterCriticalSection(&m_csCommunicationSync);
/** 从缓冲区读取一个字节的数据 */
bResult = ReadFile(m_hComm, &cRecved, 1, &BytesRead, NULL);
if ((!bResult))
{
/** 获取错误码,可以根据该错误码查出错误原因 */
DWORD dwError = GetLastError();
/** 清空串口缓冲区 */
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT);
LeaveCriticalSection(&m_csCommunicationSync);
return false;
}
/** 离开临界区 */
LeaveCriticalSection(&m_csCommunicationSync);
return (BytesRead == 1);
}
bool CSerialPort::WriteData(char* pData, unsigned int length)
{
BOOL bResult = TRUE;
DWORD BytesToSend = 0;
if (m_hComm == INVALID_HANDLE_VALUE)
{
return false;
}
/** 临界区保护 */
EnterCriticalSection(&m_csCommunicationSync);
/** 向缓冲区写入指定量的数据 */
bResult = WriteFile(m_hComm, pData, length, &BytesToSend, NULL);
if (!bResult)
{
DWORD dwError = GetLastError();
/** 清空串口缓冲区 */
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT);
LeaveCriticalSection(&m_csCommunicationSync);
return false;
}
/** 离开临界区 */
LeaveCriticalSection(&m_csCommunicationSync);
return true;
}
最后,我们的main程序。
#include "stdafx.h" #include <windows.h> #include <iostream> #include <string> #include "SerialPort.h" using namespace std; int port; CSerialPort mySerialPort; void PortOpen() { cout << "Please insert your port number : " << endl; cin >> port; if (!mySerialPort.InitPort(port, 9600, 'N', 8, 1, EV_RXCHAR)) { std::cout << "initPort fail !" << std::endl; PortOpen(); } else { std::cout << "initPort success !" << std::endl; } } int main() { PortOpen(); if (!mySerialPort.OpenListenThread()){ std::cout << "OpenListenThread fail !" << std::endl; } else { std::cout << "OpenListenThread success !" << std::endl; } while (1) { UINT BytesInQue = mySerialPort.GetBytesInCOM(); } Sleep(1000); return 0; }
运行结果如下
如果想要以txt文件保存串口数据的话,可以在文件里面加入存储的部分,参考例程如下:
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { ofstream outfile; //终端输入--》内存--》文本 outfile.open("2.txt");//(输入流) (变量)(输出文件流) if(!outfile) cout<<"error"<<endl; string str; int t1; int i=0; while(cin>>t1) //按空格读取,遇到空白符结束 { if(i!=0&&i%3==0) outfile<<"\n"; outfile<<t1<<" "; i++; } outfile.close(); return 0; }
修改的时候,我们可以在SerialPort.h的文件中加入
#include <iostream> #include <fstream> #include <string> #include <vector>
如果要在串口打印的同时,存入txt文件,在SerialPort.cpp的ListenTread函数中改动加入存储功能
UINT WINAPI CSerialPort::ListenThread(void* pParam)
{
ofstream outfile;
outfile.open("data.txt");
if (!outfile) cout << "error" << endl;
/** 得到本类的指针 */
CSerialPort *pSerialPort = reinterpret_cast<CSerialPort*>(pParam);
// 线程循环,轮询方式读取串口数据
while (!pSerialPort->s_bExit)
{
UINT BytesInQue = pSerialPort->GetBytesInCOM();
/** 如果串口输入缓冲区中无数据,则休息一会再查询 */
if (BytesInQue == 0)
{
Sleep(SLEEP_TIME_INTERVAL);
continue;
}
/** 读取输入缓冲区中的数据并输出显示 */
char rxByteArray = 0x00;
do
{
rxByteArray = 0x00;
if (pSerialPort->ReadChar(rxByteArray) == true)
{
int out = rxByteArray;
outfile.put(out);
std::cout << rxByteArray ;
}
}while (--BytesInQue);
}
return 0;
}
这就会在你项目的根目录下产生一个存储数据的txt啦。
ubuntu的串口读取
在ubuntu下使用的读取方式是用的boost库,如果电脑中没有,需要安装。
直接使用 apt-get进行安装
sudo apt-get install libboost-dev
系统中,想要查看串口号的话,terminal中使用
ls -l /dev/tty*
我们使用的是ttyUSB0。因为是配合ros平台使用的,所以引入了ros头文件,并且存储数据成txt,存储位置在workspace根目录下,主程序如下:
#include <string> #include <ros/ros.h> #include "boost/asio.hpp" #include "boost/bind.hpp"
#include <iostream>
#include <fstream>
using namespace std; using namespace boost::asio; unsigned char buf[24]; int main(int argc, char** argv)
{ ros::init(argc, argv, "usb"); ros::NodeHandle n;
std::ofstream out("test.txt");
//ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); io_service iosev; serial_port sp(iosev, "/dev/ttyUSB0"); sp.set_option(serial_port::baud_rate(9600)); sp.set_option(serial_port::flow_control()); sp.set_option(serial_port::parity()); sp.set_option(serial_port::stop_bits()); sp.set_option(serial_port::character_size(8)); while(n.ok()){ char rxData[100]; boost::system::error_code err; //scanf("%s\n",rxData); sp.read_some(buffer(rxData,39),err); if (err) { ROS_INFO("Serial port read_some Error!"); return -1; } //std_msgs::String msg; //std::stringstream ss; ROS_INFO("MPU6050 : %s\n",rxData);
out <<" "<<rxData<<" \n";
loop_rate.sleep();
}
return 0;
}
其中boost部分,主要是
io_service iosev; serial_port sp(iosev, "/dev/ttyUSB0"); sp.set_option(serial_port::baud_rate(9600)); sp.set_option(serial_port::flow_control()); sp.set_option(serial_port::parity()); sp.set_option(serial_port::stop_bits()); sp.set_option(serial_port::character_size(8));
设置端口号,波特率,校正值等等。
boost::system::error_code err; sp.read_some(buffer(rxData,39),err);
上面这两句主要是要读取串口数值,buffer里为传入字符串,39代表传入字符串的长度。编译成功后就可以运行了。
在运行程序前,需要给端口添加权限。
sudo chmod 666 /dev/ttyUSB0