I am creating a single node that is both a producer and a subscriber. The autograder is telling me that I am not subscribed to the /scan subscription, but I am. I have also double checked the name of my node. Could someone give me a tip as to where I am going wrong? I do not wish to expend any more attempts… Code is below. Thanks in advance!
private:
void topic_callback(const sensor_msgs::msg::LaserScan::SharedPtr msg) {
msg_ = *msg;
}
void timer_callback() {
auto toPublish = geometry_msgs::msg::Twist();
auto left = msg_.ranges[0];
for (int i = 0; i < (int)(msg_.ranges.size() / 3); i++) {
if (msg_.ranges[i] < left) {
left = msg_.ranges[i];
}
}
auto forward = msg_.ranges[(int)(msg_.ranges.size() / 3)];
for (int i = (int)(msg_.ranges.size() / 3);
i < 2 * (int)(msg_.ranges.size() / 3); i++) {
if (msg_.ranges[i] < forward) {
forward = msg_.ranges[i];
}
}
auto right = msg_.ranges[msg_.ranges.size() - 1];
for (int i = 2 * (int)(msg_.ranges.size() / 3);
i < (int)(msg_.ranges.size() - 1); i++) {
if (msg_.ranges[i] < right) {
right = msg_.ranges[i];
}
}
printf(“Left: %f\nRight: %f\nForward: %f\n--------------\n”, left, right,
forward);
if (forward > 1) {
toPublish.linear.x = 0.5f;
} else {
toPublish.linear.x = 0.0f;
toPublish.angular.z = 0.5f;
}
if (left < 1) {
toPublish.angular.z = -0.5f;
}
if (right < 1 && toPublish.angular.z == 0.0f) {
toPublish.angular.z = 0.5f;
}
publisher_->publish(toPublish);
}
sensor_msgs::msg::LaserScan msg_;
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr publisher_;
rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr subscription_;
};
int main(int argc, char *argv) {
rclcpp::init(argc, argv);
// Create a loop that will keep the program in execution
rclcpp::spin(std::make_shared());
rclcpp::shutdown();
return 0;
}
I have not changed my code since I started this thread, but upon running it a third time, it works. Now, it is saying that I am not publishing to the /cmd_vel topic, but I believe I am. Upon running the following command, I get the following output which shows that my node is publishing to the /cmd_vel topic. I also checked the output of the /cmd_vel topic, and the data is being written to (and the robot is moving). I am hesitant to use a 4th attempt since I only have 5.