I made a raspberry pi robot that you can control with the keyboard and I want to use my bluetooth keyboard with it. The python program automaticley starts. I used /etc/rc.local to do this.
#!/bin/sh -e
sudo python3 /home/pi/startup/keyboardControl.py &
exit 0
And this is the content of the keyboardControl.py file
from keyboard import is_pressed
import motorControl
motorLeft = motorControl.DCmotor(33, 35, 37)
motorRight = motorControl.DCmotor(36, 40, 38)
speeds = [0, 25, 50, 75]
speed = 0
try:
while 1:
if is_pressed('up'):
if is_pressed('right'):
motorLeft.setSpeed(int(speeds[speed]*1.25))
motorRight.setSpeed(int( speeds[speed]*0.75 ))
elif is_pressed('left'):
motorLeft.setSpeed(int( speeds[speed]*0.75 ))
motorRight.setSpeed(int( speeds[speed]*1.25 ))
else:
motorLeft.setSpeed(speeds[speed])
motorRight.setSpeed(speeds[speed])
elif is_pressed('down'):
if is_pressed('right'):
motorLeft.setSpeed(int( speeds[speed]*-1.25 ))
motorRight.setSpeed(int( speeds[speed]*-0.75 ))
elif is_pressed('left'):
motorLeft.setSpeed(int( speeds[speed]*-0.75 ))
motorRight.setSpeed(int( speeds[speed]*-1.25))
else:
motorLeft.setSpeed(speeds[speed]*-1)
motorRight.setSpeed(speeds[speed]*-1)
elif is_pressed('left'):
motorLeft.setSpeed(int( speeds[speed]*-1.25))
motorRight.setSpeed(int( speeds[speed]*1.25))
elif is_pressed('right'):
motorLeft.setSpeed(int( speeds[speed]*1.25))
motorRight.setSpeed(int( speeds[speed]*-1.25))
else:
motorLeft.setSpeed(0)
motorRight.setSpeed(0)
if is_pressed('1'):
speed = 0
elif is_pressed('2'):
speed = 1
elif is_pressed('3'):
speed = 2
elif is_pressed('4'):
speed = 3
if is_pressed('q'):
raise
except:
motorControl.stopAll()
As you see I used the keyboard library and I also use a library I make myself to control the motors. This works if you use a keyboard via the usb, but if I use a bluetooth keyboard it won't work. I think this is because the code runs before the keyboard is automatically connected. Is there any way to force the bluetooth connection before the program runs?
/etc/rc.local
has limitations due to Compatibility with SysV. We have seen many problems here on this site using it. Following the recommendation of the developers from systemd you should avoid using it.