//main body intmain(int argc, char** argv) { ros::init(argc, argv, "serial_port_basic"); //create a nodehandle ros::NodeHandle n; //create a serial class serial::Serial sp; //create the timeout warning serial::Timeout to = serial::Timeout::simpleTimeout(10); //edit the port (for the first serial port the ch340 connected is ttyUSB0) sp.setPort("/dev/ttyUSB0"); //set baudrate sp.setBaudrate(115200); //set seial timeout sp.setTimeout(to);
try{ //open port sp.open(); } catch(serial::IOException& e){ ROS_ERROR_STREAM("Unable to open port."); return-1; }
if(sp.isOpen()){ ROS_INFO_STREAM("serial is opened."); }else{ return-1; }
//control the rate of loop ros::Rate loop_rate(100);
//use for test uint8_t buffer_test[6]={0xAE,0xAA,0x11,0x22,0x22,0XFF}; sp.write(buffer_test, 6);
while(ros::ok()) { //open the subscriber for once ros::spinOnce(); //read from linux buffer size_t n = sp.available(); if(n!=0) { //the lagest buffer place is 64 x hex uint8_t buffer[64]; //put the data into buffer n = sp.read(buffer, n); // printf for test // for(int i=0; i<n; i++){ // printf("the origin buffer is %x",buffer[i]) ; // } // std::cout << std::endl; int err = buffer_read(buffer); //write back for test sp.write(buffer, n); } //wait for the next turn loop_rate.sleep(); } //close the port sp.close(); return0; }
intbuffer_read(uint8_t *buffer){ int max_size=64; int status=0; //the head of the serial port is 0xAE if(buffer[0]==0xAE){ status=1; }else { return0; } //choose the mod of the receiving data switch(buffer[1]){ case0xAA: status=2; break; default: return0; break; } //the fuction that write for an example if(status==2){ if(buffer[5]==0xFF){ printf("roll=%d,yaw=%d,pitch=%d\n",buffer[2],buffer[3],buffer[4]); }else{ return0; } }else{ return0; } //report error return status;