Home » BLOG » Control a mobile robot by using keyboard – Python

Control a mobile robot by using keyboard – Python

An example python program for control a mobile robot with keyboard:

  • keyboard control
  • serial communication

[pastacode lang=”python” manual=”%0A%23!%2Fusr%2Fbin%2Fpython%0A%23%20-*-%20coding%3A%20iso-8859-15%20-*-%0A%23%20Author%20%3A%20Mace%20Robotics%20(www.macerobotics.com)%0A%23%20Date%20%3A%2005%2F04%2F2020%0A%23%20Version%20%3A%200.1%0A%23%0Aimport%20serial%0Aimport%20keyboard%0Aimport%20time%0A%0Aprint(%22Control%20borvo%20with%20keyboard%22)%0A%0Aport%20%3D%20serial.Serial(‘COM6’)%0Aprint(port.name)%0A%0Aprint(%22wait..%22)%0Atry%3A%0A%20%20%23%20read%20keyboard%0A%20%20while%201%3A%0A%20%20%20%20if%20keyboard.is_pressed(‘8’)%3A%20%20%23%20if%20key%20’8’%20is%20pressed%20%0A%20%20%20%20%20%20print(‘forward’)%0A%20%20%20%20%20%20port.write(b’FOR!’)%0A%20%20%20%20%20%20time.sleep(0.5)%0A%20%20%20%20if%20keyboard.is_pressed(‘2’)%3A%20%20%23%20if%20key%20’2’%20is%20pressed%20%0A%20%20%20%20%20%20print(‘move%20back’)%0A%20%20%20%20%20%20port.write(b’BAC!’)%0A%20%20%20%20%20%20time.sleep(0.5)%0A%20%20%20%20if%20keyboard.is_pressed(‘4’)%3A%20%0A%20%20%20%20%20%20print(‘turn%20left’)%0A%20%20%20%20%20%20port.write(b’TUL!’)%09%20%0A%20%20%20%20%20%20time.sleep(0.5)%0A%20%20%20%20if%20keyboard.is_pressed(‘6’)%3A%20%20%0A%20%20%20%20%20%20print(‘turn%20right’)%0A%20%20%20%20%20%20port.write(b’TUR!’)%09%20%0A%20%20%20%20%20%20time.sleep(0.5)%0A%20%20%20%20if%20keyboard.is_pressed(‘5’)%3A%20%20%0A%20%20%20%20%20%20print(‘stop’)%0A%20%20%20%20%20%20port.write(b’STP!’)%09%20%0A%20%20%20%20%20%20time.sleep(0.5)%0A%0Aexcept%20KeyboardInterrupt%20as%20exception%3A%0A%20%20print(%22%5CnEnd%5Cn%22)%0A” message=”” highlight=”” provider=”manual”/]