WiringPi C ++串行函数随机停止工作

时间:2018-12-21 21:38:59

标签: c++ raspberry-pi wiringpi

启动GPS Ros节点时,大部分时间都可以从Raspberry串行端口读取数据,但有时在重新启动后,它无法正确读取数据,并一次又一次地溢出相同的字符(总是“?”)。仅在重新编译或重新启动节点后,它才能再次开始工作。

int main(int argc, char **argv)
{
int fd;

ros::init(argc, argv, "talker");

ros::NodeHandle n;

gps_node::gps_raw gps_data;

ros::Publisher chatter_pub = n.advertise<gps_node::gps_raw>("gps_raw", 100);

ros::Rate loop_rate(1000);


if ((fd = serialOpen ("/dev/ttyAMA0", 115200)) < 0)
{
 fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
}

if (wiringPiSetup () == -1)
{
  fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
}
char input = 0;
while (ros::ok())
{
  while (serialDataAvail (fd))
  {
    input = serialGetchar (fd);
    ROS_INFO_STREAM(input);
        NazaDecoder.decode(input);
      gps_data.gps_sats = round(NazaDecoder.getNumSat());
    gps_data.lat = NazaDecoder.getLat();
    gps_data.lon = NazaDecoder.getLon();
    gps_data.heading = round(NazaDecoder.getHeadingNc());
    gps_data.alt = NazaDecoder.getGpsAlt();
    chatter_pub.publish(gps_data);
    ros::spinOnce();
    loop_rate.sleep();
  }
}
return 0;
}

1 个答案:

答案 0 :(得分:0)

通过失败重新打开串行端口,我找到了可行的解决方案。

if (wiringPiSetup () == -1)
  {
    fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
  }
  REINIT:if ((fd = serialOpen ("/dev/ttyAMA0", 115200)) < 0)
  {
   fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
  }

  int input = 0;
  while (ros::ok())
  {
    while (serialDataAvail (fd))
    {
      input = serialGetchar (fd);
        NazaDecoder.decode(input);
        gps_data.gps_sats = round(NazaDecoder.getNumSat());
      gps_data.lat = NazaDecoder.getLat();
      gps_data.lon = NazaDecoder.getLon();
      gps_data.heading = round(NazaDecoder.getHeadingNc());
      gps_data.alt = NazaDecoder.getGpsAlt();
      chatter_pub.publish(gps_data);
      ros::spinOnce();
      loop_rate.sleep();
      if(input==-1){
        goto REINIT;
      }
    }
  }
  return 0;