micro-ROS / micro_ros_msgs

Collection of ROS 2 message definitions used throughout the implementation of micro-ROS, both in the agent and client endpoints.
Apache License 2.0
6 stars 13 forks source link

Trying to subscribe to a FloatArray #3

Closed MarcBoudreau007 closed 10 months ago

MarcBoudreau007 commented 1 year ago

Ubuntu 22.02 ROS2 humble micro-ros humble Teensy 4.1

#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/float32_multi_array.h>

rcl_subscription_t subscriber;
std_msgs__msg__Float32MultiArray msg//[]={0.0,1.1,2.2};
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)){}}

void error_loop(){
  while(1){
    digitalWrite(LED_PIN, !digitalRead(LED_PIN));
    delay(100);
  }
}

void subscription_callback(const void * msgin)
{  
  const std_msgs__msg__Float32MultiArray * msg = (const std_msgs__msg__Float32MultiArray *)msgin;

}

void setup() {
  //Serial.begin(9600);
  set_microros_transports();

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);  

  delay(2000);

  allocator = rcl_get_default_allocator();

  //create init_options
  RCCHECK(rclc_support_init(&support, 0, NULL, &allocator));

  // create node
  RCCHECK(rclc_node_init_default(&node, "micro_ros_arduino_node", "", &support));

  // create subscriber
  RCCHECK(rclc_subscription_init_default(
    &subscriber,
    &node,
    ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Float32MultiArray),
    "micro_ros_arduino_subscriber"));
  //Serial.write("msg");
  //Serial.println(msg.data);
  // create executor
  RCCHECK(rclc_executor_init(&executor, &support.context, 1, &allocator));
  RCCHECK(rclc_executor_add_subscription(&executor, &subscriber, &msg, &subscription_callback, ON_NEW_DATA));

}

void loop() {
  delay(100);
  RCCHECK(rclc_executor_spin_some(&executor, RCL_MS_TO_NS(100)));
  if (msg.data=={5.0, 6.0, 4.0})
  {
    digitalWrite(LED_PIN, HIGH);  
  }

  if (msg.data[1]==2.0)
  {
    digitalWrite(LED_PIN, LOW);  
  }

}
pablogs9 commented 1 year ago

Hello, @MarcBoudreau007 you need to initialize the memory in std_msgs__msg__Float32MultiArray message.

You have more information about handling this here: https://micro.ros.org/docs/tutorials/advanced/handling_type_memory/