r/AskRobotics • • 1d ago

Debugging My camera subscriber node error does not make sense

0 Upvotes

Hello i am currently trying to make a camera subscriber node in ros2 jazzy with opencv and cv bridge in c++ from scratch.when i checked to code it seems fine but when i build it.It gives this error that does not make sense the code is below.I hope someone can help me:

```

// this is a node to subscribe camera images as ros2 msgs with opencv version 4.6 currently
#include "rclcpp/rclcpp.hpp" // c++ client library
#include <vector>



#include <functional>
#include <memory>
#include <sensor_msgs/msg/image.hpp>
#include <cv_bridge/cv_bridge.hpp> // needed to make a .hpp file  for this current version of opencv
#include <opencv2/opencv.hpp> // for opencv format


// creating namespaces


using std::placeholders::_1;
class Camera_subscribernode : public rclcpp::Node {


public:
Camera_subscribernode() : Node("camera_subs1")
{


// creating subscriber// error is below
camera_subs_  = this->create_subscription<sensor_msgs::msg::Image>("camera/image", 10,std::bind(&Camera_subscribernode::callback_cam, this,_1)); 
// creating timer        
camera_timer_ = this->create_wall_timer(std::chrono::milliseconds(30),std::bind(&Camera_subscribernode::camera_processing,this));


     RCLCPP_INFO(this->get_logger(), "Starting camera_subscriber application in cpp...");
    }


    private:


    bool cam_is_;
    cv::Mat frame; // creating camer objects
sensor_msgs::msg::Image::SharedPtr camera_subs_ ;
rclcpp::TimerBase::SharedPtr camera_timer_;


void callback_cam(const sensor_msgs::msg::Image::SharedPtr msg) {
frame = cv_bridge::toCvCopy(msg,"bgr8")->image;
cam_is_ = true;
}
void camera_processing() {



    if(cam_is_) {


        cv::imshow("view_camera",frame);
        cv::waitKey(1);
    }
}};



int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    auto node = std::make_shared<Camera_subscribernode>();
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}

r/AskRobotics • • Jun 19 '26

Debugging Help needed getting stepper motor to move.

1 Upvotes

Hello, I am currently working on robotics project and I was wiring my electrical and testing a few software related things but I hit a roadblock when trying to get my stepper motor to move.

In the first picture you can see the layout of my electrics. I have 24V 10A power supply than then goes of to the two blue jumper strips, both of which provide 24V to 3 stepper motor drivers and their expansion boards. After that another line takes it from the jumper strips to a buck step down converter on both sides. One converter drops the 24V to 5V for the esp32, and the other drops the 24V to 20V so the fans can run a tad bit quieter.

In the second, third and fourth images I have provided an images of my wiring connecting my esp32 to the drv8825 expansion boards. On the expansion board I have connected the EN signal pin to ground. I have then taken the column of drive pins including the signal, V, and ground pins (orange , white, and brown) and connected that to the d19 column on the esp32 expansion boards, lastly I connected the step signal pin to the d18 signal pin on the esp32(yellow).

In the next two pictures are the stepper motor wiring to the driver board and also the specifications of the motors, which I got from stepper online if that could help in the debugging process. I connected A+(Black) to 1A and A-(blue) to 2A, and B+(Green) to 1B and B-(red) to 2B. I also made sure to tune the current limit using the potentiometer on the drv8825 boards following the formula Vref= Imax/2 which in my case was 1.5/2 =0.75.

Lastly is the code that I uploaded to the esp32 to try and get the stepper motor spinning which is where I hit my roadblock.

Any suggestions and advice on how to debug/ fix this issue is much appreciated, also please let me know if you want to know more specifics regarding component models etc.

Also I am new to Reddit and now that I have gotten to the end of writing my message I can’t figure out how to attach images to this post if anyone could help me with that as well that would be great.

r/AskRobotics • • 6d ago

Debugging ROSHub 0.1.0-alpha: manage, run and diagnose ROS 2 projects from one local dashboard

Thumbnail
1 Upvotes

ROSHUB: A tool to focus more on development, rather than solving bugs, or keeping a notepad for commands.

But it is still in early-stage, so feedback and contributions are welcome

r/AskRobotics • • Sep 19 '26

Debugging QTR-8RC line follower: PID works perfectly, but adding turning conditions breaks the line following

1 Upvotes

I'm building a line-following robot for a robotics competition using an Arduino Nano and QTR-8RC sensor array.

I'm still learning the coding side, so I used Al assistance while developing the code.

My current setup:

Arduino Nano

QTR-8RC 8-channel reflectance sensor

TB6612FNG motor driver

N20 motors

PID control

QTRSensors library

The interesting problem is that my basic PID test code works properly. The robot follows normal lines and even S-curves quite well.

However, when I add additional turning conditions for things like sharp/90° turns, the robot stops following the line properly.

I suspect the problem is with how I'm combining the turning conditions with the PID loop, but I'm not sure what the main mistake is.

For example, I'm currently using sensor patterns/conditions to detect a sharp turn and then forcing the motors to turn. After adding this logic, the robot becomes unstable or loses the line even though the original PID code worked correctly.

Since I'm using a QTR-8RC, should I switch from the QTR library/digital-style sensor handling to direct analogRead() values and use the actual sensor intensity values for PID and turn detection?

Would analog sensor values make sharp-turn detection more reliable than simply checking whether each sensor is HIGH/LOW?

r/AskRobotics • • Sep 17 '26

Debugging cannot get mujoco to load a xml file in cmake c++ executable

1 Upvotes

hello i am trying to learn to use mujoco in c++ instead of python because i like c++.After a long time i could get it to build in cmake.but when i execute the code to load the model and simulate the error:

WARNING: Model missing header ID. i tried what i could but i do not know what i did wrong. The c++ code looks like this :

#include <mujoco/mujoco.h>
#include "stdio.h"


char error[1000];
mjModel* m ;
mjData* d;


int main() {
  // load model from file and check for errors

  m = mj_loadModel("/home/d22/mujoco_ws/cpp/model/sleep/humanoid.xml", NULL);
  if (!m) {
    printf("%s\n", error);
    return 0;
  }


  // make data corresponding to model
  d = mj_makeData(m);


  // run simulation for 10 seconds
  while (d->time < 10)
    mj_step(m, d);


  // free model and data
  mj_deleteData(d);
  mj_deleteModel(m);


  return 0;
}                                                                                  

I hope someone can help me.thats all.

r/AskRobotics • • Aug 04 '26

Debugging Help with my robotic gripper

1 Upvotes

Hello, I am currently working on my master’s project and I cannot figure out how to solve this issue.
I am developing a robotic gripper that measures the clamping force and stops when the desired force is reached. Everything works correctly at first, and the gripper stops at the set force. However, after a short time, it loses some gripping force and then increases it again. Because of this, the measured force keeps fluctuating.
I suspect that the problem may be caused by the servos’ built-in torque or overload protection, which temporarily reduces the torque to prevent damage.
Do you have any ideas about what I could change or improve to keep the gripping force stable?

r/AskRobotics • • Aug 06 '26

Debugging How to deal with EKF Variance?

2 Upvotes

Hey everyone I work on my thesis and is about a rover that uses cube purple, here3 and a lidar and I have to make it drive autonomously a mission that I planned. Unfortunately there is a problem. When the rover is in auto mode it moves for a few seconds and then stops changing to hold. I checked the log file and found out that when the rover changes state from auto to hold the messages EKF failsafe and EKF variance pop. I looked at some graphs and the only solution I found is to calibrate the here3 compass. I tried to calibrate the compass, nothing changed so I guess either I did it wrong or it is not the problem. I attached the link that contains my log file, so please if you can help me I will very much appreciate it. Please feel free to ask me whatever you need to know in order to help me!

Log File

r/AskRobotics • • Jul 10 '26

Debugging Aide traitement de données de ma RPLIDAR C1 à partir de ma Rasberry pi 3

2 Upvotes

Salut tout le monde,

WARNING tunnel mais franchement si des personnes peuvent m'aider svp !!
J'aimerai pouvoir traiter les données reçu par mon capteur RLIDAR C1. L'objectif est d'envoyer en ADS les data traitées de mon lidar. J'ai réussi avec ma Rasberry de récupérer les données (code python avec pygame et Split&Merge) et de les afficher avec un visualizer (autre algo python). Cela fonctionnait très bien et cela ressemblait à ce qu'on peut voir avec Robostudio (logiciel de visualisation de SLAMTEC).

Maintenant je souhaite pouvoir les traiter et reconnaître les murs et d'autres objets en reliant les nuages de points par des lignes ou des courbes. L'objectif final étant de reconnaître une paroi de conteneur qui ressemble, en le nuage de point, à une sinusoïde (un algo de reconnaissance de sinusoïde en nuage de points sera fait plus tard). J'ai ainsi coder un programme qui récupére les données du Lidar, un programme qui traitent les données en reliant les points en objets mathématiques : courbes et lignes (l'idée de reconnaître des rectangles, des triangles, des ronds est écartée car trop compliquée et pas forcèment pertinente) et un programme qui visualise les données traitées avec une interface graphique. J'ai aussi fait un programme de mémorisation pour assouplir le prog de traitement afin qu'il soit plus stable, plus précis et plus rapide. Je ne sais pas si cette idée est pertinente. 4 prog en python au final. Pas de ROS utilisé, je connais rien à ROS et c'est pas l'objectif de faire ça avec ROS.

Le problème est que le traitement des data du lidar n'est pas concluant. Sur mon visualizer, le nuage de points est correctement traitées avec des lignes et courbes qui relient les points mais cela dure que quelques secondes puis mon visualizer n'affiche plus rien. Est ce que mon visuliazer n'arrive pas à suivre la cadence ou mon data_treatement qui est mauvais ? N'hésitez pas à me poser des questions ou me faire des sugestions sur ma façon de faire.

Je peux vous partager certains codes ou des images de mon visualizer (mais apparemment on peut pas partager d'images....bizarre ?)

Merci déjà d'avoir porter de l'attention à mon message !

r/AskRobotics • • Jun 28 '26

Debugging Curious how people are debugging robots in production these days.

Thumbnail
1 Upvotes

r/AskRobotics • • Jun 14 '26

Debugging Help with Inverse Kinematics!

1 Upvotes

So I recently managed to get my spider quadruped working and I did manage to get a working (maybe) inverse kinematics code but the problem is that, it does not seem to function very well, the leg moves very weirdly despite it. Would appreciate it if anyone could give any pointers or help out!

r/AskRobotics • • May 02 '26

Debugging Microros timer problem on ESP32

1 Upvotes

Hello. Im working on a differential robot, and for controlling it im using an ESP32, running microros, using the library for arduino code for ease for now. The esp basically does 2 things: 1) Gets cmd_vel to move 2) Sends back ticks to read odometry and correct them. The problem is, while the cmd_vel works great, it recieves fast and instantly, the part of the ticks, no matter what timer i adjust, it wont go below publishing each second the ticks, which for odometry is too slow for corrections. Any idea why is it failing? Any help is welcome, thanks.

#include <micro_ros_arduino.h>
#include <stdio.h>
#include <rcl/rcl.h>
#include <rclc/rclc.h>
#include <rclc/executor.h>
#include <std_msgs/msg/int32.h>
#include <geometry_msgs/msg/twist.h>
#include <Adafruit_NeoPixel.h>
#include <WiFi.h>
#include <std_msgs/msg/int32_multi_array.h>
#define LEFT_FWD 1
#define LEFT_BWD 2
#define RIGHT_FWD 11
#define RIGHT_BWD 12
#define WHEEL_BASE 0.20
#define ENC_LEFT_A 4
#define ENC_LEFT_B 5
volatile long ticks_left = 0;
Adafruit_NeoPixel debug(1, 48, NEO_GRB + NEO_KHZ800);
char ssid[] = "Aruba";
char password[] = "-";
char IPAddress[] ="192.168.50.229"; //ROCKCHIP
size_t agent_port = 8888;
#define MAX_SPEED 1.0
#define MAX_PWM   255
rcl_publisher_t publisher;
rcl_subscription_t subscriber;
rcl_timer_t timer;
rclc_executor_t executor;
rclc_support_t support;
rcl_allocator_t allocator;
rcl_node_t node;
geometry_msgs__msg__Twist cmd_msg;
std_msgs__msg__Int32MultiArray msg_pub;
int32_t somecounter = 0;
unsigned long last_cmd_time = 0;
void IRAM_ATTR encoder_left_isr(){if (digitalRead(ENC_LEFT_B) == HIGH) {ticks_left++;} 
                                  else {ticks_left--;}}//ATRIB-RAM SPECIFIED ENCODE
long get_left_ticks() {
  long value;
  noInterrupts();
  value = ticks_left;
  interrupts();
  return value;
}
void stop_motors() {
  analogWrite(LEFT_FWD, 0);analogWrite(LEFT_BWD, 0);
  analogWrite(RIGHT_FWD, 0);analogWrite(RIGHT_BWD, 0);
}
void set_motor(float left, float right) {
  float left_norm  = left  / MAX_SPEED;
  float right_norm = right / MAX_SPEED;
  left_norm  = constrain(left_norm,  -1.0, 1.0);
  right_norm = constrain(right_norm, -1.0, 1.0);
  int left_pwm  = abs(left_norm)  * MAX_PWM;
  int right_pwm = abs(right_norm) * MAX_PWM;
  if (left_norm > 0) {analogWrite(LEFT_FWD, left_pwm);analogWrite(LEFT_BWD, 0);} 
  else if (left_norm < 0) {analogWrite(LEFT_FWD, 0);analogWrite(LEFT_BWD, left_pwm);} 
  else {analogWrite(LEFT_FWD, 0);analogWrite(LEFT_BWD, 0);}
  if (right_norm > 0) {analogWrite(RIGHT_FWD, right_pwm);analogWrite(RIGHT_BWD, 0);} 
  else if (right_norm < 0) {analogWrite(RIGHT_FWD, 0);analogWrite(RIGHT_BWD, right_pwm);} 
  else {analogWrite(RIGHT_FWD, 0);analogWrite(RIGHT_BWD, 0);}
}
void cmd_vel_callback(const void * msgin) {
  const geometry_msgs__msg__Twist * msg = (const geometry_msgs__msg__Twist *)msgin;
  float linear = msg->linear.x;
  float angular = msg->angular.z;
  float left  = linear - (angular * WHEEL_BASE / 2.0);
  float right = linear + (angular * WHEEL_BASE / 2.0);
  set_motor(left, right);
  last_cmd_time = millis();
  debug.setPixelColor(0, debug.Color(0, 0, 255));
  debug.show();
}


void timer_callback(rcl_timer_t * timer, int64_t last_call_time)
{
  (void) last_call_time;


  if (timer != NULL) {
    msg_pub.data.data[0] = get_left_ticks();   //BYPASS_02
    msg_pub.data.data[1] = 0;            //WAITER (RUEDA2)


    rcl_publish(&publisher, &msg_pub, NULL);
  }
}


void setup() {
  debug.begin();
  debug.clear();
  debug.setPixelColor(0, debug.Color(255, 0, 0));
  debug.show();
  pinMode(ENC_LEFT_A, INPUT_PULLUP);
  pinMode(ENC_LEFT_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENC_LEFT_A), encoder_left_isr, RISING);
  msg_pub.data.data = (int32_t*) malloc(2 * sizeof(int32_t));
  msg_pub.data.size = 2;
  msg_pub.data.capacity = 2;
  //WiFi.begin(ssid, password);
  //while (WiFi.status() != WL_CONNECTED) {delay(500); debug.setPixelColor(0, debug.Color(196, 0, 255));debug.show();}
  //set_microros_wifi_transports(ssid, password, IPAddress, agent_port); //WIFI
  set_microros_transports(); //USB-UART (TX/RX00)
  delay(2000);
  allocator = rcl_get_default_allocator();
  rclc_support_init(&support, 0, NULL, &allocator);
  rclc_node_init_default(&node, "ESP32S3MAIN", "", &support);
  rclc_publisher_init_default(
    &publisher,
    &node,
    ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int32MultiArray),
    "encoder"
  );
  rclc_subscription_init_default(
    &subscriber,
    &node,
    ROSIDL_GET_MSG_TYPE_SUPPORT(geometry_msgs, msg, Twist),
    "cmd_vel"
  );
  rclc_timer_init_default(
    &timer,
    &support,
    RCL_MS_TO_NS(50),
    timer_callback
  );
  rclc_executor_init(&executor, &support.context, 2, &allocator);
  rclc_executor_add_subscription(
    &executor,
    &subscriber,
    &cmd_msg,
    &cmd_vel_callback,
    ON_NEW_DATA
  );
  rclc_executor_add_timer(&executor, &timer);
}


void loop() {rclc_executor_spin_some(&executor, RCL_MS_TO_NS(1));
  if (millis() - last_cmd_time > 500) {
    stop_motors();
    debug.setPixelColor(0, debug.Color(255, 255, 0));
    debug.show();
  }delay(10);}

r/AskRobotics • • May 29 '26

Debugging Position controller not loading in ROS 2 lyrical

Thumbnail
1 Upvotes

r/AskRobotics • • Apr 22 '26

Debugging Dh parameters verification help

2 Upvotes

Can someone please take a look at my dh parameters as I can’t tell if it’s my code or my parameters and I can’t get any simulation tool to work properly

r/AskRobotics • • Feb 15 '26

Debugging Teensy 4.1 and stepper motor not working as I want.

1 Upvotes

Hi everyone! I am new to using a teensy 4.1, I am familiar to the arduino and esp32. I am building a 6dof robotic arm and using normal stepper motors and limit switches.

I am using sn74hct245n level shifter for the signals and it is working fine. But I am having trouble to get the robot to home. When the motor hits the limit switch it does not stop but rather slow down and just go through the limit switch and then go go to normal speed. 
I wired the limit as NC, I took the COM pin and wired it to the GND of the teensy and the NC pin I wired it to the teensy pin to track the state. When I tested the limit switch by hand, it worked fine. And for the signals I wired the +5v pins all to the power supply +5v and took the -signal pins to the teensy.

 I am using plateformIO and arduino framework for the teensy, and using fastAccelStepper Library to control the stepper.

r/AskRobotics • • Apr 05 '26

Debugging Can you help me identify what this connector is?

1 Upvotes

Hello everyone, I recently purchase a second hand Hesai Pandar 128 E3X LiDAR sensor with one of these strange connectors. I was wondering if anyone a, know why my sensor (despite clearly being marked as Hesai Pandar 128 E3X etched into metal, this was dirt cheap and marked as broken, there is no reason the seller would lie) is a different color and has this strange connector. B, can anyone please identify what connector this is so I can buy the corresponding female jack, or at the very least help me tell which one of these prongs does what, data1, data2, power, ground, etc. I don't think the manufacturer will help me even though I did send them an email.

https://imgur.com/a/iFMye6x

r/AskRobotics • • May 12 '26

Debugging Software has QA. Robots don't.

0 Upvotes

I've been talking to a lot of robotics teams lately. The ones with paying customers, running robots in real environments every day.

The conversation always ends up in the same place. Not data, not models: those are hard problems but people are working on them. The quiet one is what happens after the run. Robot does something unexpected, and now you're digging through logs and video manually trying to figure out why. Policy issue? Controller? Hardware glitch? Bad data? You make a call, patch something, run it again. No systematic way to know if the same failure is happening across hundreds of runs, no way to catch a pattern until someone stumbles on it.

Teams are slow not because they can't train or deploy: it's because the feedback loop between what the robot does and what you learn from it is almost entirely manual. That's the bottleneck nobody talks about.

I've been building something to close that loop. Point it at your episodes: LeRobot, MCAP, rosbag, whatever format you're using and it runs sensor analysis, action diffs, and multi-camera VLM annotation, then puts everything in a queryable KB. Root cause attribution: policy, controller, hardware, perception. Something your agent can query directly instead of you digging through files.

Looking for 2-3 teams to try it on real data. Free, I help with setup and the first runs, you shape the roadmap.

DM or comment if this sounds familiar.

robolens.to/manifesto for more context.

r/AskRobotics • • Apr 27 '26

Debugging Trouble with PCA9685 servo driver

1 Upvotes

I’m currently trying to build a robot dog with Arduino Uno. It’s my first robotics project, but I’ve run into issues with the servo driver. I have 10 MSg90 servos connected to the driver but have been moving them one at a time so far.

When I try to move one of the legs, the servo connected to it shakes violently until I hold it steady to stop it. The servos were working for about a day, but when I tried again today, only the first programmed movements worked. After that, they stopped responding completely.

I had to switch to a new servo driver to get them working again, but the legs were still shaking. After testing, I think it may be a power issue. I’m not sure if it’s too much power or too little. I know servo shaking can happen from low power, but I also think too much power may have damaged the first driver.

My current setup: • Servo driver power port connected to a 6V 2000mAh Ni-CD battery • From the driver pins, I have GND, 5V, and analog pins connected

I also tried using a 5V 5A DC adapter, but nothing happened when using that. I don’t think the issue is wiring, so I’m not sure what to do next. Any ideas?

r/AskRobotics • • Apr 10 '26

Debugging FS-i6 not binding w/ malenki nano

1 Upvotes

I’ve been working on an antweight combat bot for awhile now and everything‘s been going fine with the connection until now. Idiot just says "RXBinding" while the malenki blinks blue. I haven’t changed anything with the wiring at all since it lasy worked. Plz help!

r/AskRobotics • • Apr 10 '26

Debugging What is wrong with my line follower bot's code? (Except the PID constants and speed, that I can change later on) The bot's wheels are not working properly and moving in random directions. Components- Arduino Nano, L298N motor driver, N20 motors, IR array, IC7805

1 Upvotes
#define IR0 A0
#define IR1 A1
#define IR2 A2
#define IR3 A3
#define IR4 A4
#define IR5 A5
#define IR6 2
#define IR7 4


// Motor pins (L298N)
const int ENA = 9;   // left motor PWM
const int IN1 = 7;
const int IN2 = 8;


const int ENB = 10;  // right motor PWM
const int IN3 = 11;
const int IN4 = 12;


struct Paths 
{
  bool L;
  bool S;
  bool R;
};


int ir[8];
int weights[8] = {-3,-2,-1,0,0,1,2,3};


float Kp = 30;
float Kd = 8;


int last_error = 0;
int baseSpeed = 80;


void setup() 
{
  Serial.begin(115200);
  Serial.println();
  pinMode(IR0, INPUT);
  pinMode(IR1, INPUT);
  pinMode(IR2, INPUT);
  pinMode(IR3, INPUT);
  pinMode(IR4, INPUT);
  pinMode(IR5, INPUT);
  pinMode(IR6, INPUT);
  pinMode(IR7, INPUT);


  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
}


char path[100];
int i = 0;
char shorten(char a, char b, char c)
{
  if (a == 'L' && b == 'B' && c == 'L')
    return 'S';
  if (a == 'R' && b == 'B' && c == 'R')
    return 'S';
  if (a == 'S' && b == 'B' && c == 'S')
    return 'B';
  if (a == 'L' && b == 'B' && c == 'R')
    return 'B';
  if (a == 'R' && b == 'B' && c == 'L')
    return 'B';
  if (a == 'L' && b == 'B' && c == 'S')
    return 'R';
  if (a == 'S' && b == 'B' && c == 'L')
    return 'R';
  if (a == 'R' && b == 'B' && c == 'S')
    return 'L';
  if (a == 'S' && b == 'B' && c == 'R')
    return 'L';
  return 'B';
}


void storePath(char move)
{
  path[i] = move;
  i++;
  while (i >= 3 && path[i-2] == 'B')
  {
    path[i-3] = shorten(path[i-3], path[i-2], path[i-1]);
    i = i - 2;
  }
}


void loop() 
{
  if (finish())
  {
    setMotor(0,0);
    while(1);
  }
  readSensors();
  for (int j=0; j<8; j++)
  {
    Serial.print(ir[j]);
    Serial.print(" ");
  }


  if (lineLost()) 
  {
    searchLine();
  }
  else if (isNode()) 
  {
    Paths p = detectPaths();
    char move = decideMove(p);
    storePath(move);
    executeTurn(move);
    while (isNode()) 
    {
        readSensors();
        setMotor(baseSpeed, baseSpeed);
  }
  }
  else 
  {
    followLinePID();
  }
} 
bool finish()
{
  if (allHigh())
  {
    setMotor(baseSpeed,baseSpeed);
    delay(400);
    readSensors();
    if (allHigh())
    {
      return true;
    }
  }
  return false;
}
bool allHigh()
{
  int count = 0;
  for (int k=0; k<8; k++)
  {
    count += ir[k];
  }
  return count == 8;
}
void readSensors() {
  ir[0] = !digitalRead(IR0);
  ir[1] = !digitalRead(IR1);
  ir[2] = !digitalRead(IR2);
  ir[3] = !digitalRead(IR3);
  ir[4] = !digitalRead(IR4);
  ir[5] = !digitalRead(IR5);
  ir[6] = !digitalRead(IR6);
  ir[7] = !digitalRead(IR7);
}


int getPosition() {
  int numerator = 0;
  int denominator = 0;
  for (int i = 0; i < 8; i++) {
    if (ir[i]) 
    {
      numerator += weights[i];
      denominator++;
    }
  }
  if (denominator == 0) return 0;
  return numerator / denominator;
}


void followLinePID() {
  int position = getPosition();
  int correction = computePID(position);
  int leftSpeed  = baseSpeed + correction;
  int rightSpeed = baseSpeed - correction;
  setMotor(leftSpeed, rightSpeed);
}


int computePID(int position) {
  int error = position;
  int derivative = error - last_error;
  int correction = (Kp * error) + (Kd * derivative);
  last_error = error;
  return correction;
}


Paths detectPaths() {
  Paths p;
  p.L = ir[0] || ir[1] || ir[2];
  p.S = ir[3] || ir[4];
  p.R = ir[5] || ir[6] || ir[7];
  return p;
}


bool isNode() 
{
  bool centerActive = ir[3] || ir[4];
  bool leftActive   = ir[0] || ir[1] || ir[2];
  bool rightActive  = ir[5] || ir[6] || ir[7];
  return centerActive && (leftActive || rightActive);
}


char decideMove(Paths p) 
{
  if (p.L) return 'L';
  if (p.S) return 'S';
  if (p.R) return 'R';
  return 'B';
}


void executeTurn(char move) {
  if (move == 'L') {
    turnLeft90();
  } 
  else if (move == 'R') {
    turnRight90();
  } 
  else if (move == 'B') {
    uTurn();
  } 
  else {
    setMotor(baseSpeed, baseSpeed);
    delay(50);
  }
}


bool lineLost() {
  for (int i = 0; i < 8; i++) {
    if (ir[i]) return false;
  }
  return true;
}


void searchLine() 
{
  setMotor(120, -120);
}


void turnLeft90() 
{
  setMotor(-150, 150);
  delay(200);
  setMotor(0, 0);
}


void turnRight90() {
  setMotor(150, -150);
  delay(200);
  setMotor(0, 0);
}


void uTurn() {
  setMotor(150, -150);
  delay(400);
  setMotor(0, 0);
}


void setMotor(int leftSpeed, int rightSpeed) 
{
  leftSpeed = constrain(leftSpeed, -255, 255);
  rightSpeed = constrain(rightSpeed, -255, 255);


  if (leftSpeed >= 0) 
  {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    analogWrite(ENA, leftSpeed);
  } else 
  {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    analogWrite(ENA, -leftSpeed);
  }


  if (rightSpeed >= 0) 
  {
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);
    analogWrite(ENB, rightSpeed);
  } else 
  {
    digitalWrite(IN3, LOW);
    digitalWrite(IN4, HIGH);
    analogWrite(ENB, -rightSpeed);
  }
}

r/AskRobotics • • Apr 02 '26

Debugging BARN Challenge Doubt

1 Upvotes

For my college course, I need to implement a navigation model for the BARN Challenge. To approach this, I’ve been studying the methods used by previous top-performing teams and working with an existing GitHub repository as a baseline. [Github Repo]
I’ve successfully set up and run the code using the Gazebo simulation environment along with ROS (rospy). However, I’m encountering a major inconsistency that I’m unable to debug:

The robot is able to reach the goal according to my navigation logic, but in Gazebo (which should represent the ground truth), the robot’s actual position appears to be significantly different from what my code estimates.

This suggests that there is a discrepancy between the robot’s perceived pose (likely from the odometry) and its true pose in the simulation.

Now I tried hard fixing by making the target slightly further then the actual target so that any wheel slip is accounted but doesn't work.

From what I understand, the robot currently does not have an accurate estimate of its global position. I want to explore the idea of building a local map using LiDAR data to improve localization, but this approach hasn’t worked well so far. [current moment]

Any help would be appreciated or any link to a post regarding this would also help.

r/AskRobotics • • Mar 18 '26

Debugging why doesnt my code work?

1 Upvotes

#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver servo = Adafruit_PWMServoDriver(0x40);

void setServo(int n_servo, int angulo);

void setup() {

Serial.begin(9600);

servo.begin();

servo.setPWMFreq(50);

setServo(0, 100);

}

void loop() {

for (int i = 0; i<=180; i = i+5){

setServo(0, i);

delay(100);

}

}

void setServo(int n_servo, int angulo){

int duty;

duty = map(angulo,0, 180, 102, 512);

servo.setPWM(n_servo, 0, duty);

}

help me please ive been trying to learn to code a single servo on my PCA9685 so i can learn to code the rest of servos but all the tutorials either dont work or theyre outdated, help me

r/AskRobotics • • Dec 04 '25

Debugging Need some help with encoders

1 Upvotes

I'm trying to do a reading in some encoders to get the RPM from the motor, I am starting in the use of the encoder and developted this code with some assist from AI, because that's probably the only teacher I have to help me, can someone help me understand why it's giving low RPM values like around 30RPM?

Code: https://github.com/Jhuan-Medeiros/Movimentacao-Robo-Omnidirecional/blob/main/src/main.cpp
Motor with encoder and datasheets: search for JGA25-370 DC in AliExpress and look for one that has a blue wheel. My version of motor it's the 6V 280RPM.

Notes: I'm not advertising nothing, my code in Github can be used by anyone and sorry for the comments being in Portuguese, wasn't thinking in showcasing it to anyone.

r/AskRobotics • • Jan 26 '26

Debugging Error [controller_manager]: Switch controller timed out after 5 seconds! and [spawner_joint_state_broadcaster]: Failed to activate controller : joint_state_broadcaster when trying to add ros2_control plugins github repo

Thumbnail
1 Upvotes

r/AskRobotics • • Jan 08 '26

Debugging triggered publisher with ros2 gazebo not working

1 Upvotes

can someone help me with ros2 gazebo? i tried to bridge ros2 topic with gazebo topic to publish std_msgs/Int32 msg to a gz.msgs.Int32 topic with joystick button presses to make the cmd_vel output respond so that the robot included in gazebo world respond so that robot moves in a certain direction. the gazebo topic viewer can see my ros2 topic but the triggered publisher does not respond. the code and sdf file and the cmake file is here below:

# this is a launch file to learn to publish a gazebo world with gazebo and publish ros2 joystick msgs to gazebo
# so the comments can  be messy
import os
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution, Command, TextSubstitution
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch_ros.substitutions import FindPackageShare


def generate_launch_description():


    pkg_ros_gz_sim = get_package_share_directory('ros_gz_sim')
    gazebo_basics_pkg = get_package_share_directory('gz_train1')
    default_rviz_config_path = PathJoinSubstitution([gazebo_basics_pkg, 'rviz', 'urdf.rviz'])


    # Show joint state publisher GUI for joints
    gui_arg = DeclareLaunchArgument(name='gui', default_value='true', choices=['true', 'false'],
                                    description='Flag to enable joint_state_publisher_gui')

    # RViz config file path
    rviz_arg = DeclareLaunchArgument(name='rvizconfig', default_value=default_rviz_config_path,
                                    description='Absolute path to rviz config file')


    # URDF model path to spawn urdf file in gazebo
    model_arg = DeclareLaunchArgument(
        'model', default_value=os.path.join(gazebo_basics_pkg,'urdf','07-physics.urdf'),
        description='Name of the URDF description to load'
    )


    # Use built-in ROS2 URDF launch package with our own arguments
    urdf_rviz = IncludeLaunchDescription(
        PathJoinSubstitution([FindPackageShare('urdf_launch'), 'launch', 'display.launch.py']),
        launch_arguments={
            'urdf_package': 'gz_train1',
            'urdf_package_path': PathJoinSubstitution([gazebo_basics_pkg,'urdf', '08-macroed.urdf.xacro']),
            'rviz_config': LaunchConfiguration('rvizconfig'),
            'jsp_gui': LaunchConfiguration('gui')}.items()
    )



    # Define the path to your URDF or Xacro file
    urdf_file_path = PathJoinSubstitution([os.path.join(
        gazebo_basics_pkg,  # Replace with your package name
        "urdf","07-physics.urdf")
    ])




    gazebo_launch = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(pkg_ros_gz_sim, 'launch', 'gz_sim.launch.py'),
        ),
        launch_arguments={'gz_args': [PathJoinSubstitution([
            gazebo_basics_pkg,
            'worlds',
            'camjoylidar.sdf'
        ]),
        #TextSubstitution(text=' -r -v -v1 --render-engine ogre')],
        TextSubstitution(text=' -r -v -v4')],
        'on_exit_shutdown': 'false'}.items()
    )


    joy = Node(package='gz_train1',
                    namespace='joy_bridge'
                    ,executable='joy1',
                   remappings=[('/joy1', '/joy')],
                    name='pub3',
                     output='screen')


    # node that supposed to send  ros2 msgs to the sdf world
    bridge = Node(
    package='ros_gz_bridge',
    executable='parameter_bridge',
    name="joy_bridge",
    namespace='joy_trigger',
    arguments=['/joy1@std_msgs/msg/Int32@gz.msgs.Int32'],
    remappings=[('/joy1', '/joy')],
    output='screen'
   ,
        parameters=[
            {'use_sim_time': True},
        ]
)

    launchDescriptionObject = LaunchDescription()
    launchDescriptionObject.add_action(gazebo_launch)

    launchDescriptionObject.add_action(bridge)
    launchDescriptionObject.add_action(joy)



    launchDescriptionObject.add_action(gui_arg)

    launchDescriptionObject.add_action(rviz_arg)
    #launchDescriptionObject.add_action(model_arg)
    #launchDescriptionObject.add_action(urdf_rviz)

    #launchDescriptionObject.add_action(robot_state_publisher_node)
    #launchDescriptionObject.add_action(joint_state_publisher_gui_node)
    return launchDescriptionObject

// This is a node to publish msgs with joystick button presses (this pkg is only used with the xbox one controller)


// Below are the standard headers
#include <chrono>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <iostream>


// Below are the standard headers for ros2
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/int32.hpp"


// Below is the header to get joystick input from bluetooth communication.
#include <linux/joystick.h>
// Below are the standard namespaces to shorten the code.
using namespace std;
using namespace std::chrono_literals;


 // node msg is created.
 // below is the struct for the joystick values create
 // This node only uses the button values for this node but you can use more if you want to
 //but i recommend to  look for this repo as a example: https://github.com/t-kiyozumi/joystick_on_linux.git
typedef struct
{
  uint16_t X;
  uint16_t Y;
  uint16_t A;
  uint16_t B;
  uint16_t LB;
  uint16_t LT;
  uint16_t RB;
  uint16_t RT;
  uint16_t start;
  uint16_t back;
  int16_t axes1_x;
  int16_t axes1_y;
  int16_t axes0_x;
  int16_t axes0_y;
} controler_state;


void write_controler_state(controler_state *controler, js_event event) // this fuction writes the controller state and publish the node
{

  switch (event.type)
  {
  case JS_EVENT_BUTTON:


  auto node = rclcpp::Node::make_shared("topic");
  auto publisher = node->create_publisher<std_msgs::msg::Int32>("joy1", 10);
  // below are the button commands to publish the message data.
  rclcpp::executors::SingleThreadedExecutor executor;
  executor.add_node(node);
    auto message = std_msgs::msg::Int32();


            message.data = 0;
         publisher->publish(message);
          RCLCPP_INFO(node->get_logger(), "Publishing joystick button b:'%i'", message.data);



    if (event.number == 1)
    {
      controler->B = event.value;



         message.data = 20;
         publisher->publish(message);
          RCLCPP_INFO(node->get_logger(), "Publishing joystick button b:'%i'", message.data);
    }
    if (event.number == 0)
    {
      controler->A = event.value;


         message.data = 10;
         publisher->publish(message);
         RCLCPP_INFO(node->get_logger(), "Publishing joystick button a: x'%i'", message.data);
    }
    if (event.number == 3)
    {
      controler->X = event.value;


          message.data = 30;
           publisher->publish(message);
         RCLCPP_INFO(node->get_logger(), "Publishing joystick button a: y'%i'", message.data);
    }
    if (event.number == 4)
    {
      controler->Y = event.value;

       message.data = 40;
        publisher->publish(message);
         RCLCPP_INFO(node->get_logger(), "Publishing joystick button y:'%i'", message.data);

    }
         if (event.number == 6)
    {
      controler->LB = event.value;

       message.data = 0;
        publisher->publish(message);
         RCLCPP_INFO(node->get_logger(), "Publishing joystick value:'%i'", message.data);
    }
    if (event.number == 7)
    {
      controler->RB = event.value;

       message.data = 7;
        publisher->publish(message);
         RCLCPP_INFO(node->get_logger(), "Publishing joystick button rb:'%i'", message.data);
          rclcpp::shutdown();
    }

  }
  }






int main(int argc, char * argv[])
{    rclcpp::init(argc, argv); // Initialise rclcpp

  int fd = open("/dev/input/js0", O_RDONLY); 
  struct js_event event;
  controler_state *controler;
  controler = (controler_state *)malloc(sizeof(controler_state));



  while (1) // now the code publish msgs created by a button presses in a loop.
  {
    read(fd, &event, sizeof(event));
    write_controler_state(controler, event);



     usleep(1000);



  }





  return 0;


}

<!--
this is a world were you can drive a diffrential driver
with telop plugin,gz.msgs.Int32(maybe ros2 topic in the future)
-->
<sdf version="1.10">
  <world name="visualize_lidar_world">
    <physics name="1ms" type="ignored">
      <max_step_size>0.001</max_step_size>
      <real_time_factor>1.0</real_time_factor>
    </physics>
    <plugin
      filename="gz-sim-physics-system"
      name="gz::sim::systems::Physics">
    </plugin>
    <plugin
      filename="gz-sim-sensors-system"
      name="gz::sim::systems::Sensors">
      <render_engine>ogre2</render_engine>
    </plugin>
    <plugin
      filename="gz-sim-scene-broadcaster-system"
      name="gz::sim::systems::SceneBroadcaster">
    </plugin>

    <gui fullscreen="0">

      <!-- 3D scene -->
      <plugin filename="MinimalScene" name="3D View">
        <gz-gui>
          <title>3D View</title>
          <property type="bool" key="showTitleBar">false</property>
          <property type="string" key="state">docked</property>
        </gz-gui>

        <engine>ogre2</engine>
        <scene>scene</scene>
        <ambient_light>0.4 0.4 0.4</ambient_light>
        <background_color>0.8 0.8 0.8</background_color>
        <camera_pose>-6 0 6 0 0.5 0</camera_pose>
      </plugin>

      <!-- Plugins that add functionality to the scene -->
      <plugin filename="EntityContextMenuPlugin" name="Entity context menu">
        <gz-gui>
          <property key="state" type="string">floating</property>
          <property key="width" type="double">5</property>
          <property key="height" type="double">5</property>
          <property key="showTitleBar" type="bool">false</property>
        </gz-gui>
      </plugin>
      <plugin filename="GzSceneManager" name="Scene Manager">
        <gz-gui>
          <property key="resizable" type="bool">false</property>
          <property key="width" type="double">5</property>
          <property key="height" type="double">5</property>
          <property key="state" type="string">floating</property>
          <property key="showTitleBar" type="bool">false</property>
        </gz-gui>
      </plugin>
      <plugin filename="InteractiveViewControl" name="Interactive view control">
        <gz-gui>
          <property key="resizable" type="bool">false</property>
          <property key="width" type="double">5</property>
          <property key="height" type="double">5</property>
          <property key="state" type="string">floating</property>
          <property key="showTitleBar" type="bool">false</property>
        </gz-gui>
      </plugin>
      <plugin filename="CameraTracking" name="Camera Tracking">
        <gz-gui>
          <property key="resizable" type="bool">false</property>
          <property key="width" type="double">5</property>
          <property key="height" type="double">5</property>
          <property key="state" type="string">floating</property>
          <property key="showTitleBar" type="bool">false</property>
        </gz-gui>
      </plugin>
      <!-- World control -->
      <plugin filename="WorldControl" name="World control">
        <gz-gui>
          <title>World control</title>
          <property type="bool" key="showTitleBar">false</property>
          <property type="bool" key="resizable">false</property>
          <property type="double" key="height">72</property>
          <property type="double" key="z">1</property>

          <property type="string" key="state">floating</property>
          <anchors target="3D View">
            <line own="left" target="left"/>
            <line own="bottom" target="bottom"/>
          </anchors>
        </gz-gui>

        <play_pause>true</play_pause>
        <step>true</step>
        <start_paused>true</start_paused>
        <use_event>true</use_event>

      </plugin>

      <!-- World statistics -->
      <plugin filename="WorldStats" name="World stats">
        <gz-gui>
          <title>World stats</title>
          <property type="bool" key="showTitleBar">false</property>
          <property type="bool" key="resizable">false</property>
          <property type="double" key="height">110</property>
          <property type="double" key="width">290</property>
          <property type="double" key="z">1</property>

          <property type="string" key="state">floating</property>
          <anchors target="3D View">
            <line own="right" target="right"/>
            <line own="bottom" target="bottom"/>
          </anchors>
        </gz-gui>

        <sim_time>true</sim_time>
        <real_time>true</real_time>
        <real_time_factor>true</real_time_factor>
        <iterations>true</iterations>
      </plugin>

      <plugin filename="VisualizeLidar" name="Visualize Lidar">
      </plugin>

      <!-- Inspector -->
      <plugin filename="ComponentInspector" name="Component inspector">
        <gz-gui>
          <property type="string" key="state">docked</property>
        </gz-gui>
      </plugin>

      <!-- Entity tree -->
      <plugin filename="EntityTree" name="Entity tree">
        <gz-gui>
          <property type="string" key="state">docked</property>
        </gz-gui>
      </plugin>
    </gui>

    <light type="directional" name="sun">
      <cast_shadows>true</cast_shadows>
      <pose>0 0 10 0 0 0</pose>
      <diffuse>0.8 0.8 0.8 1</diffuse>
      <specular>0.2 0.2 0.2 1</specular>
      <attenuation>
        <range>1000</range>
        <constant>0.9</constant>
        <linear>0.01</linear>
        <quadratic>0.001</quadratic>
      </attenuation>
      <direction>-0.5 0.1 -0.9</direction>
    </light>

    <model name="ground_plane">
      <static>true</static>
      <link name="link">
        <collision name="collision">
          <geometry>
            <box>
              <size>20 20 0.1</size>
            </box>
          </geometry>
        </collision>
        <visual name="visual">
          <geometry>
            <box>
              <size>20 20 0.1</size>
            </box>
          </geometry>
          <material>
            <ambient>0.8 0.8 0.8 1</ambient>
            <diffuse>0.8 0.8 0.8 1</diffuse>
            <specular>0.8 0.8 0.8 1</specular>
          </material>
        </visual>
      </link>
    </model>

    <model name="box">
      <pose>0 -1 0.5 0 0 0</pose>
      <link name="box_link">
        <inertial>
          <inertia>
            <ixx>1</ixx>
            <ixy>0</ixy>
            <ixz>0</ixz>
            <iyy>1</iyy>
            <iyz>0</iyz>
            <izz>1</izz>
          </inertia>
          <mass>1.0</mass>
        </inertial>
        <collision name="box_collision">
          <geometry>
            <box>
              <size>1 1 1</size>
            </box>
          </geometry>
        </collision>

        <visual name="box_visual">
          <geometry>
            <box>
              <size>1 1 1</size>
            </box>
          </geometry>
          <material>
            <ambient>1 0 0 1</ambient>
            <diffuse>1 0 0 1</diffuse>
            <specular>1 0 0 1</specular>
          </material>
        </visual>
      </link>
    </model>

    <model name="model_with_lidar">
      <pose>4 0 0.5 0 0.0 3.14</pose>
      <link name="link">
        <pose>0.05 0.05 0.05 0 0 0</pose>
        <inertial>
          <mass>0.1</mass>
          <inertia>
            <ixx>0.000166667</ixx>
            <iyy>0.000166667</iyy>
            <izz>0.000166667</izz>
          </inertia>
        </inertial>
        <collision name="collision">
          <geometry>
            <box>
              <size>0.1 0.1 0.1</size>
            </box>
          </geometry>
        </collision>
        <visual name="visual">
          <geometry>
            <box>
              <size>0.1 0.1 0.1</size>
            </box>
          </geometry>
        </visual>

        <sensor name='gpu_lidar' type='gpu_lidar'>
        <pose relative_to='lidar_sensor_joint' > 4 0 0.5 0 0.0 3.14</pose>
          <topic>lidar</topic>
          <update_rate>10</update_rate>
          <lidar>
            <scan>
              <horizontal>
                <samples>640</samples>
                <resolution>1</resolution>
                <min_angle>-1.396263</min_angle>
                <max_angle>1.396263</max_angle>
              </horizontal>
              <vertical>
                <samples>16</samples>
                <resolution>1</resolution>
                <min_angle>-0.261799</min_angle>
                <max_angle>0.261799</max_angle>
              </vertical>
            </scan>
            <range>
              <min>0.08</min>
              <max>10.0</max>
              <resolution>0.01</resolution>
            </range>
          </lidar>
          <visualize>true</visualize>
        </sensor>
      </link>
      <static>true</static>
    </model>

    <model name='vehicle_blue'>
      <pose>-4 0 0.325 0 0 0.0</pose>
      <link name='chassis'>
        <pose>-0.151427 -0 0.175 0 -0 0</pose>
        <inertial>
          <mass>1.14395</mass>
          <inertia>
            <ixx>0.126164</ixx>
            <ixy>0</ixy>
            <ixz>0</ixz>
            <iyy>0.416519</iyy>
            <iyz>0</iyz>
            <izz>0.481014</izz>
          </inertia>
        </inertial>
        <visual name='visual'>
          <geometry>
            <box>
              <size>2.01142 1 0.568726</size>
            </box>
          </geometry>
          <material>
            <ambient>0.5 0.5 1.0 1</ambient>
            <diffuse>0.5 0.5 1.0 1</diffuse>
            <specular>0.0 0.0 1.0 1</specular>
          </material>
        </visual>
        <collision name='collision'>
          <geometry>
            <box>
              <size>2.01142 1 0.568726</size>
            </box>
          </geometry>
        </collision>
      </link>

      <link name="lidar_link">
        <pose>0 0 0.5 0 0 0</pose>
        <inertial>
          <mass>0.1</mass>
          <inertia>
            <ixx>0.000166667</ixx>
            <iyy>0.000166667</iyy>
            <izz>0.000166667</izz>
          </inertia>
        </inertial>
        <collision name="collision">
          <geometry>
            <box>
              <size>0.1 0.1 0.1</size>
            </box>
          </geometry>
        </collision>
        <visual name="visual">
          <geometry>
            <box>
              <size>0.1 0.1 0.1</size>
            </box>
          </geometry>
        </visual>
          <sensor name="boundingbox_camera" type="boundingbox_camera">
         <topic>img</topic>
         <pose relative_to='lidar_link' > 0 0 0.5 0 0.0 0 </pose>
         <camera>
           <box_type>2d</box_type>
           <horizontal_fov>1.047</horizontal_fov>
           <image>
             <width>800</width>
             <height>600</height>
           </image>
           <clip>
             <near>0.1</near>
             <far>10</far>
           </clip>
         </camera>
         <always_on>1</always_on>
         <update_rate>30</update_rate>
         <visualize>true</visualize>
       </sensor>
      </link>

      <link name='left_wheel'>
        <pose>0.554283 0.625029 -0.025 -1.5707 0 0</pose>
        <inertial>
          <mass>2</mass>
          <inertia>
            <ixx>0.145833</ixx>
            <ixy>0</ixy>
            <ixz>0</ixz>
            <iyy>0.145833</iyy>
            <iyz>0</iyz>
            <izz>0.125</izz>
          </inertia>
        </inertial>
        <visual name='visual'>
          <geometry>
            <sphere>
              <radius>0.3</radius>
            </sphere>
          </geometry>
          <material>
            <ambient>0.2 0.2 0.2 1</ambient>
            <diffuse>0.2 0.2 0.2 1</diffuse>
            <specular>0.2 0.2 0.2 1</specular>
          </material>
        </visual>
        <collision name='collision'>
          <geometry>
            <sphere>
              <radius>0.3</radius>
            </sphere>
          </geometry>
        </collision>
      </link>

      <link name='right_wheel'>
        <pose>0.554282 -0.625029 -0.025 -1.5707 0 0</pose>
        <inertial>
          <mass>2</mass>
          <inertia>
            <ixx>0.145833</ixx>
            <ixy>0</ixy>
            <ixz>0</ixz>
            <iyy>0.145833</iyy>
            <iyz>0</iyz>
            <izz>0.125</izz>
          </inertia>
        </inertial>
        <visual name='visual'>
          <geometry>
            <sphere>
              <radius>0.3</radius>
            </sphere>
          </geometry>
          <material>
            <ambient>0.2 0.2 0.2 1</ambient>
            <diffuse>0.2 0.2 0.2 1</diffuse>
            <specular>0.2 0.2 0.2 1</specular>
          </material>
        </visual>
        <collision name='collision'>
          <geometry>
            <sphere>
              <radius>0.3</radius>
            </sphere>
          </geometry>
        </collision>
      </link>

      <link name='caster'>
        <pose>-0.957138 -0 -0.125 0 -0 0</pose>
        <inertial>
          <mass>1</mass>
          <inertia>
            <ixx>0.1</ixx>
            <ixy>0</ixy>
            <ixz>0</ixz>
            <iyy>0.1</iyy>
            <iyz>0</iyz>
            <izz>0.1</izz>
          </inertia>
        </inertial>
        <visual name='visual'>
          <geometry>
            <sphere>
              <radius>0.2</radius>
            </sphere>
          </geometry>
          <material>
            <ambient>0.2 0.2 0.2 1</ambient>
            <diffuse>0.2 0.2 0.2 1</diffuse>
            <specular>0.2 0.2 0.2 1</specular>
          </material>
        </visual>
        <collision name='collision'>
          <geometry>
            <sphere>
              <radius>0.2</radius>
            </sphere>
          </geometry>
        </collision>
      </link>

      <joint name='lidar_sensor_joint' type='fixed'>
        <parent>chassis</parent>
        <child>lidar_link</child>
      </joint>

      <joint name='left_wheel_joint' type='revolute'>
        <parent>chassis</parent>
        <child>left_wheel</child>
        <axis>
          <xyz>0 0 1</xyz>
          <limit>
            <lower>-1.79769e+308</lower>
            <upper>1.79769e+308</upper>
          </limit>
        </axis>
      </joint>

      <joint name='right_wheel_joint' type='revolute'>
        <parent>chassis</parent>
        <child>right_wheel</child>
        <axis>
          <xyz>0 0 1</xyz>
          <limit>
            <lower>-1.79769e+308</lower>
            <upper>1.79769e+308</upper>
          </limit>
        </axis>
      </joint>

      <joint name='caster_wheel' type='ball'>
        <parent>chassis</parent>
        <child>caster</child>
      </joint>

      <plugin
        filename="gz-sim-diff-drive-system"
        name="gz::sim::systems::DiffDrive">
        <left_joint>left_wheel_joint</left_joint>
        <right_joint>right_wheel_joint</right_joint>
        <wheel_separation>1.25</wheel_separation>
        <wheel_radius>0.3</wheel_radius>
        <odom_publish_frequency>1</odom_publish_frequency>
        <topic>cmd_vel</topic>
      </plugin>
    </model>

<!-- Moving Forward-->

<plugin filename="gz-sim-triggered-publisher-system"

name="gz::sim::systems::TriggeredPublisher">

<input type="gz.msgs.Int32" topic="/joy">

<match field="data">40</match>

</input>

<output type="gz.msgs.Twist" topic="/cmd_vel">

linear: {x: 0.5}, angular: {z: 0.0}

</output>

</plugin>

<!-- Moving Backward-->

<plugin filename="gz-sim-triggered-publisher-system"

name="gz::sim::systems::TriggeredPublisher">

<input type="gz.msgs.Int32" topic="/joy">

<match field="data">30</match>

</input>

<output type="gz.msgs.Twist" topic="/cmd_vel">

linear: {x: -0.5}, angular: {z: 0.0}

</output>

</plugin>

<!-- Moving leftward-->

<plugin filename="gz-sim-triggered-publisher-system"

name="gz::sim::systems::TriggeredPublisher">

<input type="gz.msgs.Int32" topic="/joy">

<match field="data">20</match>

</input>

<output type="gz.msgs.Twist" topic="/cmd_vel">

linear: {x: 0.0}, angular: {z: 0.5}

</output>

</plugin>

<!-- Moving rightwards-->

<plugin filename="gz-sim-triggered-publisher-system"

name="gz::sim::systems::TriggeredPublisher">

<input type="gz.msgs.Int32" topic="/joy">

<match field="data">10</match>

</input>

<output type="gz.msgs.Twist" topic="/cmd_vel">

linear: {x: 0.0}, angular: {z: -0.5}

</output>

</plugin>

<!-- stop moving-->

<plugin filename="gz-sim-triggered-publisher-system"

name="gz::sim::systems::TriggeredPublisher">

<input type="gz.msgs.Int32" topic="/joy">

<match field="data">50</match>

</input>

<output type="gz.msgs.Twist" topic="/cmd_vel">

linear: {x: 0.0}, angular: {z: 0.0}

</output>

</plugin>

</world>

</sdf>

#here is the cmake list
cmake_minimum_required(VERSION 3.8)
project(gz_train1)


if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()


# find dependencies
find_package(ament_cmake REQUIRED)
find_package(ament_cmake_python REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(diagnostic_msgs REQUIRED)
find_package(diagnostic_updater REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(rclpy REQUIRED)
find_package(tf2 REQUIRED)
find_package(tf2_ros REQUIRED)
include_directories(include)
add_executable(gz_sub src/gz_sub.cpp)
add_executable(joy1  src/joytest.cpp)
add_executable(slpub src/gz_pub_sleep.cpp)
add_executable(joy2 src/joytest2.cpp)
add_executable(tf2_broad src/tf2_staticbroad_test1.cpp)



ament_python_install_package(scripts)


ament_python_install_package(gz_train1)




ament_target_dependencies(
 slpub
 geometry_msgs
  std_msgs
  rclcpp
)



ament_target_dependencies(
 tf2_broad
 geometry_msgs
   rclcpp
   tf2
   tf2_ros
)



ament_target_dependencies(
  gz_sub
  std_msgs
  rclcpp

)


ament_target_dependencies(
  joy1 
  std_msgs
  rclcpp

)


ament_target_dependencies(
  joy2
  std_msgs
  rclcpp

)
install(TARGETS  
slpub
joy1
joy2
gz_sub
tf2_broad
  DESTINATION lib/${PROJECT_NAME})


install(DIRECTORY
launch urdf worlds rviz  scripts gz_train1
DESTINATION share/${PROJECT_NAME})



# Install Python executables in the ros2_ws
install(PROGRAMS
scripts/test_pub.py



DESTINATION lib/${PROJECT_NAME}
)


ament_package()

r/AskRobotics • • Jan 02 '26

Debugging Trying to to make a camera tracking robot that follows a color or a face

1 Upvotes

I am currently building a raspberry pi camera tracking robot.I started with a 2 servos(The mg996r servos) using but i had more success with 1.I got it to move but when it moves only in 1 direction and not turn back.So i wanna ask if someone can help me fix that i have a link to a youtube shorts that show the problem:https://youtube.com/shorts/ySms8Wri9yQ?si=m3_-5zswMOAshUTR .And the repo of the code that i am using: https://github.com/Dawsatek22/orp-raspberrypi-camera_trackrobot/blob/main/tracking_red_1servo.py