赞
踩
本系列教程文章专栏:
本系列课程已上线古月学院,欢迎感兴趣的小伙伴订阅:
开发交流QQ群: 797497206
完整项目代码:
github
teleop_twist_keyboard
项目的源代码,移植到自己程序
同时在ui界面设置每个按钮的shortcut,就能实现键盘控制:
//绑定速度控制按钮
connect(ui.pushButton_i,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_u,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_o,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_j,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_l,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_m,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_back,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
connect(ui.pushButton_backr,SIGNAL(clicked()),this,SLOT(slot_cmd_control()));
槽函数:
//速度控制相关按钮处理槽函数 void MainWindow::slot_cmd_control() { QPushButton* btn=qobject_cast<QPushButton*>(sender()); char key=btn->text().toStdString()[0]; //速度 float liner=ui.horizontalSlider_linear->value()*0.01; float turn=ui.horizontalSlider_raw->value()*0.01; bool is_all=ui.checkBox_use_all->isChecked(); switch (key) { case 'u': qnode.move_base(is_all?'U':'u',liner,turn); break; case 'i': qnode.move_base(is_all?'I':'i',liner,turn); break; case 'o': qnode.move_base(is_all?'O':'o',liner,turn); break; case 'j': qnode.move_base(is_all?'J':'j',liner,turn); break; case 'l': qnode.move_base(is_all?'L':'l',liner,turn); break; case 'm': qnode.move_base(is_all?'M':'m',liner,turn); break; case ',': qnode.move_base(is_all?'<':',',liner,turn); break; case '.': qnode.move_base(is_all?'>':'.',liner,turn); break; } }
创建发布者:
//速度控制话题
cmd_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
qnode.move_base:
//发布机器人速度控制 void QNode::move_base(char k,float speed_linear,float speed_trun) { std::map<char, std::vector<float>> moveBindings { {'i', {1, 0, 0, 0}}, {'o', {1, 0, 0, -1}}, {'j', {0, 0, 0, 1}}, {'l', {0, 0, 0, -1}}, {'u', {1, 0, 0, 1}}, {',', {-1, 0, 0, 0}}, {'.', {-1, 0, 0, 1}}, {'m', {-1, 0, 0, -1}}, {'O', {1, -1, 0, 0}}, {'I', {1, 0, 0, 0}}, {'J', {0, 1, 0, 0}}, {'L', {0, -1, 0, 0}}, {'U', {1, 1, 0, 0}}, {'<', {-1, 0, 0, 0}}, {'>', {-1, -1, 0, 0}}, {'M', {-1, 1, 0, 0}}, {'t', {0, 0, 1, 0}}, {'b', {0, 0, -1, 0}}, {'k', {0, 0, 0, 0}}, {'K', {0, 0, 0, 0}} }; char key=k; //计算是往哪个方向 float x = moveBindings[key][0]; float y = moveBindings[key][1]; float z = moveBindings[key][2]; float th = moveBindings[key][3]; //计算线速度和角速度 float speed = speed_linear; float turn = speed_trun; // Update the Twist message geometry_msgs::Twist twist; twist.linear.x = x * speed; twist.linear.y = y * speed; twist.linear.z = z * speed; twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = th * turn; // Publish it and resolve any remaining callbacks cmd_pub.publish(twist); ros::spinOnce(); }
在我自己学习的过程中目前发现没有相关类似完整开源项目,为了帮助其他人少走弯路,我决定将自己的完整项目开源:
github
创作不易,如果本教程对你有帮助,关注或点个赞吧,或者github标个星哦~~
您的支持就是我最大的动力~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。