Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <micro_ros_arduino.h>
- #include <stdio.h>
- #include <rcl/rcl.h>
- #include <rcl/error_handling.h>
- #include <rclc/rclc.h>
- #include <rclc/executor.h>
- #include <std_msgs/msg/int32.h>
- rcl_publisher_t publisher;
- std_msgs__msg__Int32 msg;
- rclc_executor_t executor;
- rclc_support_t support;
- rcl_allocator_t allocator;
- rcl_node_t node;
- rcl_timer_t timer;
- #define LED_PIN 13
- #define RCCHECK(fn) { rcl_ret_t temp_rc = fn; if((temp_rc != RCL_RET_OK)){error_loop();}}
- #define RCSOFTCHECK(fn) { rcl_ret_t temp_rc = fn; if((temp_rc != RCL_RET_OK)){}}
- #define trigPin 9
- #define echoPin 10
- long duration;
- int distance;
- void error_loop(){
- while(1){
- digitalWrite(LED_PIN, !digitalRead(LED_PIN));
- delay(100);
- }
- }
- void timer_callback(rcl_timer_t * timer, int64_t last_call_time)
- {
- RCLC_UNUSED(last_call_time);
- if (timer != NULL) {
- RCSOFTCHECK(rcl_publish(&publisher, &msg, NULL));
- msg.data++;
- }
- }
- void setup() {
- set_microros_transports();
- pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
- pinMode(echoPin, INPUT); // Sets the echoPin as an Input
- Serial.begin(9600); // Starts the serial communication
- pinMode(LED_PIN, OUTPUT);
- //digitalWrite(LED_PIN, HIGH);
- delay(2000);
- allocator = rcl_get_default_allocator();
- //create init_options
- RCCHECK(rclc_support_init(&support, 0, NULL, &allocator));
- // create node
- rcl_node_options_t node_ops = rcl_node_get_default_options();
- node_ops.domain_id = 30;
- RCCHECK(rclc_node_init_with_options(&node, "micro_ros_arduino_node", "", &support, &node_ops));
- //RCCHECK(rclc_node_init_default(&node, "micro_ros_arduino_node", "", &support));
- // create publisher
- RCCHECK(rclc_publisher_init_default(
- &publisher,
- &node,
- ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int32),
- "micro_ros_arduino_node_publisher"));
- // create timer,
- const unsigned int timer_timeout = 1000;
- RCCHECK(rclc_timer_init_default(
- &timer,
- &support,
- RCL_MS_TO_NS(timer_timeout),
- timer_callback));
- // create executor
- RCCHECK(rclc_executor_init(&executor, &support.context, 1, &allocator));
- RCCHECK(rclc_executor_add_timer(&executor, &timer));
- msg.data = 0;
- }
- void loop() {
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- // Sets the trigPin on HIGH state for 10 micro seconds
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Reads the echoPin, returns the sound wave travel time in microseconds
- duration = pulseIn(echoPin, HIGH);
- // Calculating the distance
- distance= duration*0.034/2;
- // Prints the distance on the Serial Monitor
- Serial.print("Distance: ");
- Serial.println(distance);
- delay(100);
- RCSOFTCHECK(rclc_executor_spin_some(&executor, RCL_MS_TO_NS(100)));
- }
Advertisement
Add Comment
Please, Sign In to add comment