最新消息:

ROS与Arduino-Push Button(按钮)

ROS1/一代机器人系统 少儿编程 1451浏览 0评论
ROS与Arduino教程

Push Button(按钮)

说明

  • 这个教程展示观察一个按钮和发布它的状态,按下按钮能点亮LED灯
  • 展示一个简单的常见的硬件按钮如何整合到ROS系统
  • 按钮可作为输入设备控制你的Robot去做不同的任务
  • 或为紧急任务停止运行中的机器

硬件

  • Arduino UNO
  • Push Button

连接图

ROS与Arduino-Push Button(按钮)

对于那些硬件设计的人,你会注意到有没有上拉电阻开关输入。这是因为Arduino已经内置上拉电阻。引脚7被拉高,直到按钮被按下,并连接到地上。

代码

/* 
 * Button Example for Rosserial
 */

#include <ros.h>
#include <std_msgs/Bool.h>


ros::NodeHandle nh;

std_msgs::Bool pushed_msg;
ros::Publisher pub_button("pushed", &pushed_msg);

const int button_pin = 7;
const int led_pin = 13;

bool last_reading;
long last_debounce_time=0;
long debounce_delay=50;
bool published = true;

void setup()
{
  nh.initNode();
  nh.advertise(pub_button);
  
  //initialize an LED output pin 
  //and a input pin for our push button
  pinMode(led_pin, OUTPUT);
  pinMode(button_pin, INPUT);
  
  //Enable the pullup resistor on the button
  digitalWrite(button_pin, HIGH);
  
  //The button is a normally button
  last_reading = ! digitalRead(button_pin);
 
}

void loop()
{
  
  bool reading = ! digitalRead(button_pin);
  
  if (last_reading!= reading){
      last_debounce_time = millis();
      published = false;
  }
  
  //if the button value has not changed during the debounce delay
  // we know it is stable
  if ( !published && (millis() - last_debounce_time)  > debounce_delay) {
    digitalWrite(led_pin, reading);
    pushed_msg.data = reading;
    pub_button.publish(&pushed_msg);
    published = true;
  }

  last_reading = reading;
  
  nh.spinOnce();
}

代码解释

  1. 代码
ros::NodeHandle nh;

std_msgs::Bool pushed_msg;
ros::Publisher pub_button("pushed", &pushed_msg);

解释:

  • 实例化节点处理类,定义发布
  1. 代码

    nh.initNode();
    nh.advertise(pub_button);

解释:

  • Arduino的setup函数,初始化节点处理类,宣告一个发布。
  1. 代码

    pub_button.publish(&pushed_msg);

解释:

  • Arduino的loop函数,发布按钮消息

观察按钮

  • 应该只有按钮被按下或释放才发布消息
  • 观察这个状态改变,就需要记住按钮最后一次的状态和能保持多长时间
  • 一旦状态改变,传感器应该防止按钮反跳,应该等待足够的时间,以便按钮已经稳定而不再震荡。
  • 因为当机械接触和释放时候会有反弹过程,所以输入插脚的电压会反弹。

请输入图片描述

下面的代码定义最后的按钮状态,需要等待的时长及默认定义为已发布

bool last_reading;
long last_debounce_time=0;
long debounce_delay=50;
bool published = true;

在setup函数,我们初始化插脚,IO和上拉电阻。同样初始化稳定的最后的按钮状态

 //initialize an LED output pin 
  //and a input pin for our push button
  pinMode(led_pin, OUTPUT);
  pinMode(button_pin, INPUT);
  
  //Enable the pullup resistor on the button
  digitalWrite(button_pin, HIGH);
  
  //The button is a normally button
  last_reading = ! digitalRead(button_pin);

在Loop函数,代码循环中读取每次值,检查状态值是否改变,是否稳定值,是否已发布。

测试

roscore
rosrun rosserial_python serial_node.py _port:=/dev/ttyUSB0
rostopic echo temperature

您必须 登录 才能发表评论!