在頭文件中,進行串口頭文件的包含
#include < serial/serial.h >
在類的定義中,什么一個 serial 類的實例
serial::Serial Stm32_Serial; //聲明串口對象
并且在類的定義中,聲明兩個結構體,用來存儲接收和要發(fā)送的數(shù)據(jù)
RECEIVE_DATA Receive_Data; //The serial port receives the data structure //串口接收數(shù)據(jù)結構體
SEND_DATA Send_Data; //The serial port sends the data structure //串口發(fā)送數(shù)據(jù)結構體
在類的構造函數(shù)中,配置這個串口對象的參數(shù)
private_nh.param< std::string >("usart_port_name", usart_port_name, "/dev/stm32_controller"); //Fixed serial port number //固定串口號
private_nh.param< int > ("serial_baud_rate", serial_baud_rate, 115200); //Communicate baud rate 115200 to the lower machine //和下位機通信波特率115200
這兩個參數(shù)是在launch文件中設置的,代碼里進行參數(shù)的讀取。
usart_port_name 設置的USB設備別名
serial_baud_rate 串口通信的波特率要和stm32設置的一致
try
{
//Attempts to initialize and open the serial port //嘗試初始化與開啟串口
Stm32_Serial.setPort(usart_port_name); //Select the serial port number to enable //選擇要開啟的串口號
Stm32_Serial.setBaudrate(serial_baud_rate); //Set the baud rate //設置波特率
serial::Timeout _time = serial::Timeout::simpleTimeout(2000); //Timeout //超時等待
Stm32_Serial.setTimeout(_time);
Stm32_Serial.open(); //Open the serial port //開啟串口
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("car_robot can not open serial port,Please check the serial port cable! "); //If opening the serial port fails, an error message is printed //如果開啟串口失敗,打印錯誤信息
}
初始化串口配置,并開啟串口
設置的參數(shù)包括:
- 要開啟的串口號
- 設置波特率
- 超時等待
判斷串口是否被打開,打開輸出終端打印信息
if(Stm32_Serial.isOpen())
{
ROS_INFO_STREAM("car_robot serial port opened"); //Serial port opened successfully //串口開啟成功提示
}
ROS主控讀取stm32發(fā)送的數(shù)據(jù)
之后便可以通過
Stm32_Serial.read(Receive_Data_Pr,sizeof(Receive_Data_Pr));
read函數(shù)讀取串口接收到的字節(jié),之后通過定義的通信協(xié)議再進行和校驗與數(shù)據(jù)解析即可stm32向ROS主控發(fā)送數(shù)據(jù)。
ROS主控向stm32發(fā)送數(shù)據(jù)
ROS主控向stm32發(fā)送數(shù)據(jù)的代碼如下:
將之前定義的發(fā)送數(shù)據(jù)的結構體 Send_Data的tx 中填入要發(fā)送的字節(jié)
Send_Data.tx[0]=FRAME_HEADER; //frame head 0x7B //幀頭0X7B
Send_Data.tx[1] = 0; //set aside //預留位
Send_Data.tx[2] = 0; //set aside //預留位
填好字節(jié)后,直接通過下面代碼發(fā)送即可
try
{
Stm32_Serial.write(Send_Data.tx,sizeof (Send_Data.tx)); //Sends data to the downloader via serial port //通過串口向下位機發(fā)送數(shù)據(jù)
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("Unable to send data through serial port"); //If sending data fails, an error message is printed //如果發(fā)送數(shù)據(jù)失敗,打印錯誤信息
}
-
控制器
+關注
關注
114文章
17096瀏覽量
184166 -
STM32
+關注
關注
2293文章
11031瀏覽量
364658 -
智能車
+關注
關注
21文章
409瀏覽量
77552 -
ROS
+關注
關注
1文章
288瀏覽量
17734
發(fā)布評論請先 登錄
STM32串口通信數(shù)據(jù)亂碼的相關問題

評論