< >
Home » ROS与Arduino教程 » ROS与Arduino-SRF08 Ultrasonic Ranger(SRF08超声波测距仪)

ROS与Arduino-SRF08 Ultrasonic Ranger(SRF08超声波测距仪)

SRF08 Ultrasonic Ranger(SRF08超声波测距仪)

说明

  • 这个教程展示通过Arduino和SRF08超声波测距仪进行测距。SRF08通过SPI/I2C与Arduino进行通讯。

硬件

连接图

请输入图片描述

  • 额外需增加两个1.8k欧的上拉电阻

代码

/*
 * rosserial SRF08 Ultrasonic Ranger Example
 *
 * This example is calibrated for the SRF08 Ultrasonic Ranger.
 */
#include <Sonar_srf08.h> //SRF08 specific library
#include <WProgram.h>
#include <Wire.h>
#include <ros.h>
#include <std_msgs/Float32.h>


//Set up the ros node and publisher
std_msgs::Float32 sonar_msg;
ros::Publisher pub_sonar("sonar", &sonar_msg);
ros::NodeHandle nh;


Sonar_srf08 MySonar; //create MySonar object

#define CommandRegister 0x00
int New_Address = 248; //0xF8
#define ResultRegister  0x02

float sensorReading =0;

char unit = 'i'; // 'i' for inches , 'c' for centimeters


void setup()
{
  MySonar.connect();
  MySonar.changeAddress(CommandRegister, New_Address);
  New_Address += 4;
  nh.initNode();
  nh.advertise(pub_sonar);

}


long publisher_timer;

void loop()
{

  if (millis() > publisher_timer) {

   // step 1: request reading from sensor
   MySonar.setUnit(CommandRegister, New_Address, unit);

   //pause
  delay(70);

  // set register for reading
  MySonar.setRegister(New_Address, ResultRegister);

  // read data from result register
  sensorReading = MySonar.readData(New_Address, 2);

  sonar_msg.data = sensorReading;
  pub_sonar.publish(&sonar_msg);

  publisher_timer = millis() + 4000; //publish once a second

  }

  nh.spinOnce();
}

测试

  1. 新窗口打开
$ roscore
  1. 新窗口打开,/dev/ttyUSB0为Arduino的设备端口号
rosrun rosserial_python serial_node.py _port:=/dev/ttyUSB0
  1. 新窗口打开
rostopic echo sonar

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ros arduino