How to get keyboard input to move robot in Python?
I am working on a simulation with ros and gazebo and I wanted to move a robot with my keystrokes. I had tried to use the keyboard module, but when I ran it with ros run robot_sim move.py
it will return an error saying that I must be root to use this module. Is there any other modules/methods that would allow me to get the keystrokes in real time and publish it to a ROS node?
I fixed this issue by stealing someone else's C++ code to get the keystrokes and I use my Python script to subscribe to it:
#include <termios.h>
#include <ros/ros.h>
#include "std_msgs/Int32.h"
int getch() {
static struct termios oldt, newt;
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON);
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
int ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "keyboard");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Int32>("key_detector", 1000);
ros::Rate loop_rate(10);
while (ros::ok())
{
std_msgs::Int32 c;
c.data = getch();
pub.publish(c);
ros::spinOnce();
loop_rate.sleep();
}
}
Please edit your question to provide a link to the demo/code you downloaded. Most demos support keyboard input control, but you first have to run a "teleop" ros node - the exact name differs for each demo.
You are correct to not use root for this very basic operation. I would be wary of that "keyboard module" you found.
I'd edited my post with the code I am using right now. It appears that it is working fine after testing it yesterday. I am using mavros and px4 firmware. Now I can get my keyboard input, I am just confuse how to translate that into commands. I know there is an area that I can publish called
so do I just publish it to that node and it will just run whatever my keyboard is telling it to run?
Not sue if I understood well, but I believe you have to dig a bit deeper.
/mavros/setpoint_attitude/cmd_vel
is supposed to be the main topic for moving your robot. But when you break it down, you might see some cmd_vel data (x / y / z / angular) related to the keyboard inputs:Example:
or:
So, every time a
cmd_vel
topic is published, it has this data on it, to make the robot move according to its internal programming.This #q331522 can also help. Again: If I understood well your question.