|
| 1 | +#include <micro_ros_arduino.h> |
| 2 | + |
| 3 | +#include <stdio.h> |
| 4 | +#include <rcl/rcl.h> |
| 5 | +#include <rcl/error_handling.h> |
| 6 | +#include <rclc/rclc.h> |
| 7 | +#include <rclc/executor.h> |
| 8 | + |
| 9 | +#include <geometry_msgs/msg/twist.h> |
| 10 | + |
| 11 | +rcl_subscription_t subscriber; |
| 12 | +geometry_msgs__msg__Twist msg; |
| 13 | +rclc_executor_t executor; |
| 14 | +rcl_allocator_t allocator; |
| 15 | +rclc_support_t support; |
| 16 | +rcl_node_t node; |
| 17 | + |
| 18 | + |
| 19 | +#define LED_PIN 13 |
| 20 | + |
| 21 | +#define RCCHECK(fn) { rcl_ret_t temp_rc = fn; if((temp_rc != RCL_RET_OK)){error_loop();}} |
| 22 | +#define RCSOFTCHECK(fn) { rcl_ret_t temp_rc = fn; if((temp_rc != RCL_RET_OK)){error_loop();}} |
| 23 | + |
| 24 | +void error_loop(){ |
| 25 | + while(1){ |
| 26 | + digitalWrite(LED_PIN, !digitalRead(LED_PIN)); |
| 27 | + delay(100); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +//twist message cb |
| 32 | +void subscription_callback(const void *msgin) { |
| 33 | + const geometry_msgs__msg__Twist * msg = (const geometry_msgs__msg__Twist *)msgin; |
| 34 | + // if velocity in x direction is 0 turn off LED, if 1 turn on LED |
| 35 | + digitalWrite(LED_PIN, (msg->linear.x == 0) ? LOW : HIGH); |
| 36 | +} |
| 37 | + |
| 38 | +void setup() { |
| 39 | + pinMode(LED_PIN, OUTPUT); |
| 40 | + digitalWrite(LED_PIN, HIGH); |
| 41 | + |
| 42 | + delay(2000); |
| 43 | + |
| 44 | + allocator = rcl_get_default_allocator(); |
| 45 | + |
| 46 | + //create init_options |
| 47 | + RCCHECK(rclc_support_init(&support, 0, NULL, &allocator)); |
| 48 | + |
| 49 | + // create node |
| 50 | + node = rcl_get_zero_initialized_node(); |
| 51 | + RCCHECK(rclc_node_init_default(&node, "micro_ros_arduino_node", "", &support)); |
| 52 | + |
| 53 | + // create subscriber |
| 54 | + RCCHECK(rclc_subscription_init_default( |
| 55 | + &subscriber, |
| 56 | + &node, |
| 57 | + ROSIDL_GET_MSG_TYPE_SUPPORT(geometry_msgs, msg, Twist), |
| 58 | + "micro_ros_arduino_twist_subscriber")); |
| 59 | + |
| 60 | + // create executor |
| 61 | + executor = rclc_executor_get_zero_initialized_executor(); |
| 62 | + RCCHECK(rclc_executor_init(&executor, &support.context, 1, &allocator)); |
| 63 | + |
| 64 | + unsigned int rcl_wait_timeout = 1000; // in ms |
| 65 | + RCCHECK(rclc_executor_set_timeout(&executor, RCL_MS_TO_NS(rcl_wait_timeout))); |
| 66 | + RCCHECK(rclc_executor_add_subscription(&executor, &subscriber, &msg, &subscription_callback, ON_NEW_DATA)); |
| 67 | + |
| 68 | +} |
| 69 | + |
| 70 | +void loop() { |
| 71 | + delay(100); |
| 72 | + RCCHECK(rclc_executor_spin_some(&executor, RCL_MS_TO_NS(100))); |
| 73 | +} |
0 commit comments