Arduino-ROS, example - blink LED and push button

In this example, we can interface the LED and push button to Arduino and control using ROS. When the push button is pressed, the Arduino node sends a True value to a topic called pushed, and at the same time, it switches on the LED which is on the Arduino board. The following shows the circuit for doing this example:

Figure 10 : Interfacing the push button to Arduino
/*  
 * Button Example for Rosserial 
 */ 
 
#include <ros.h> 
#include <std_msgs/Bool.h> 
 
//Nodehandle 
ros::NodeHandle nh; 
 
//Boolean message for Push button 
std_msgs::Bool pushed_msg; 
 
//Defining Publisher in a topic called pushed 
ros::Publisher pub_button("pushed", &pushed_msg); 
 
 
//LED and Push button pin definitions 
const int button_pin = 7; 
const int led_pin = 13; 
 
//Variables to handle debouncing 
//https://www.arduino.cc/en/Tutorial/Debounce 
 
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 for the debounce delay, we know its 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(); 
} 

The preceding code handles the key debouncing and changes the button state only after the button release. The preceding code can upload to Arduino and can interface to ROS using the following command:

  • Start roscore:
    $ roscore 
  • Start serial_node.py:
    $ rosrun roserial_python serial_node.py /dev/ttyACM0

We can see the button press event by echoing the topic pushed:

    $ rostopic echo pushed

We will get following values when a button is pressed:

Figure 11 : Output of Arduino- Push button
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.185.147