Ingredients: - LG Optimus Dynamic - PC game controller (joystick) - pygame for joystick input - python script runs on PC to translate joystick input to movement commands - SL4A to send movement commands from PC to smartphone over WiFi - smartphone sends movement commands to Arduino via Bluetooth (also SL4A) - Arduino translates commands to movement
First, we taught Bao to listen with Bluetooth
That was using pyserial, connecting directly from PC to Arduino via COM17.
I used that to build a basic instruction set to control movement. E.g.,: !fwd 10 !bwd 5 !left 3 !right 10 !fwdleft 10 5 !bwdright 6 6 !stop
Those instructions are parsed and executed on the Arduino. The numbers tell how much the joystick was deflected.
But it wasn’t very interesting to connect directly from PC to robot via Bluetooth. I wanted to strap my smartphone on to add that extra layer of sensors and computing power. So my scheme was for my PC to talk to my smartphone and for the smartphone to be like the Jewel Wasp, controlling the robot via Bluetooth.
This was the main Python code running on my PC:
#!/usr/bin/env python
import android
import serial
import pygame
import sys
def initAndroid():
# LG dynamic
global g_droid
global g_bao
uuid = "00001101-0000-1000-8000-00805F9B34FB"
mac = "98:D3:31:B0:E9:37" # makeblock mac
g_droid = android.Android(('192.168.1.3', 33333))
g_droid.wakeLockAcquirePartial()
g_droid.bluetoothConnect(uuid, mac)
conns = g_droid.bluetoothActiveConnections()
if not conns.result:
print "Android phone failed to link to robo's Bluetooth"
sys.exit(0)
else:
print "Bluetooth connected"
g_bao = conns.result.keys()[0]
g_droid.bluetoothWrite("!beep\n", g_bao)
g_bao = None
g_droid = None
#g_bao = serial.Serial("COM17", 9600) # laptop bluetooth
initAndroid()
g_joyFwdBwdPos = 0
g_joyLeftRightPos = 0
# allow multiple joysticks
joy = []
def cleanupAndroid():
global g_droid
global g_bao
if g_droid:
g_droid.bluetoothStop(g_bao)
g_droid.wakeLockRelease()
# handle joystick event
def handleJoyEvent(e):
global g_joyFwdBwdPos
global g_joyLeftRightPos
if e.type == pygame.JOYAXISMOTION:
axis = "unknown"
if (e.dict['axis'] == 1):
axis = "X"
if (e.dict['axis'] == 0):
axis = "Y"
if (e.dict['axis'] == 2):
axis = "Throttle"
if (e.dict['axis'] == 3):
axis = "Z"
if (axis != "unknown"):
str = "Axis: %s; Value: %f" % (axis, e.dict['value'])
# uncomment to debug
#output(str, e.dict['joy'])
# Arduino joystick-servo hack
pos = e.dict['value']
zero = 0.5
vector = int(pos * 10)
# update vectors
if axis == "X" or axis == "Z":
if pos < -zero or pos > zero:
g_joyFwdBwdPos = vector
else:
g_joyFwdBwdPos = 0
if axis == "Y" or axis == "Throttle":
if pos < -zero or pos > zero:
g_joyLeftRightPos = vector
else:
g_joyLeftRightPos = 0
# decide move cmd based on vectors
fbmag = abs(g_joyFwdBwdPos)
lrmag = abs(g_joyLeftRightPos)
if g_joyFwdBwdPos < 0:
if g_joyLeftRightPos < 0:
roboCmd("!fwdleft %d %d" % (fbmag, lrmag))
elif g_joyLeftRightPos > 0:
roboCmd("!fwdright %d %d" % (fbmag, lrmag))
else:
roboCmd("!fwd %d" % fbmag)
elif g_joyFwdBwdPos > 0:
if g_joyLeftRightPos < 0:
roboCmd("!bwdleft %d %d" % (fbmag, lrmag))
elif g_joyLeftRightPos > 0:
roboCmd("!bwdright %d %d" % (fbmag, lrmag))
else:
roboCmd("!bwd %d" % fbmag)
elif g_joyLeftRightPos < 0:
roboCmd("!left %d" % lrmag)
elif g_joyLeftRightPos > 0:
roboCmd("!right %d" % lrmag)
else:
roboCmd("!stop")
elif e.type == pygame.JOYBUTTONDOWN:
str = "Button: %d" % (e.dict['button'])
# uncomment to debug
output(str, e.dict['joy'])
button = e.dict['button']
# Button 0 (trigger) to quit
if (button == 0):
print "Bye!\n"
cleanupAndroid()
quit()
elif (button == 1):
roboCmd("!beep")
else:
pass
# print the joystick position
def output(line, stick):
print "Joystick: %d; %s" % (stick, line)
# wait for joystick input
def joystickControl():
while True:
e = pygame.event.wait()
if (e.type == pygame.JOYAXISMOTION or e.type == pygame.JOYBUTTONDOWN):
handleJoyEvent(e)
g_lastRoboCmd = None
def roboCmd(roboCmd):
global g_lastRoboCmd
global g_bao
if "fwd" in roboCmd or "bwd" in roboCmd \
or "left" in roboCmd or "right" in roboCmd \
or "stop" in roboCmd:
# don't send redundant movement commands to save data
if g_lastRoboCmd == roboCmd:
return
g_lastRoboCmd = roboCmd
print roboCmd
if g_droid:
g_droid.bluetoothWrite(roboCmd + "\n", g_bao)
else:
g_bao.write(roboCmd + "\n")
# main method
def main():
# initialize pygame
pygame.joystick.init()
pygame.display.init()
if not pygame.joystick.get_count():
print "\nPlease connect a joystick and run again.\n"
quit()
print "\n%d joystick(s) detected." % pygame.joystick.get_count()
for i in range(pygame.joystick.get_count()):
myjoy = pygame.joystick.Joystick(i)
myjoy.init()
joy.append(myjoy)
print "Joystick %d: " % (i) + joy[i].get_name()
print "Depress trigger (button 0) to quit.\n"
# run joystick listener loop
joystickControl()
# allow use as a module or standalone script
if __name__ == "__main__":
main()
And this was what I had on the Arduino:
` #include #include #include #include #include MeDCMotor MotorL(M1); MeDCMotor MotorR(M2); MeUltrasonicSensor ultrasonic(PORT_3); MeBluetooth bluetooth(PORT_5); const int MAXBUFSZ = 128; char g_lineBuf[MAXBUFSZ]; int g_bufReadIdx = 0; // movement settings const boolean g_debug = true; const int g_stepPeriod = 50; const int g_maxStepsForward = 3000 / g_stepPeriod; const int g_maxTurnSteps = 3000 / g_stepPeriod; const int g_minSpeed = 45; const int g_maxSpeed = 255; const int g_speedFactor = 23; const float g_leftTrim = .97; const float g_rightTrim = 1.; // enums const int LED_PIN = 13; const int EBRAKE_STOP = 2; // full stop const int EBRAKE_WAIT = 1; // wait for "Go" signal const int EBRAKE_GO = 0; // brakes off and GO! const int MODE_ULTRASONIC = 0; const int MODE_REMOTE = 1; const int ULTRASONIC_INIT_SPEED = 200; // robo state machine int g_moveSpeed = ULTRASONIC_INIT_SPEED; int g_numStepsForward = 0; int g_numTurnSteps = 0; boolean g_rightFlag; int g_ebrake = EBRAKE_STOP; long g_timeLastBlocked = 0; uint8_t g_mode = MODE_REMOTE; void setup() { Serial.begin(9600); Serial.println("Software serial on"); bluetooth.begin(9600); Serial.println("Bluetooth on"); g_lineBuf[0] = '\0'; ResetUltrasonic(EBRAKE_STOP); pinMode(LED_PIN, OUTPUT); // "obstructed" LED Serial.println("Bao ready"); } void loop() { char inDat; boolean hasBlue = false; hasBlue = bluetooth.available(); if (hasBlue) { ResetUltrasonic(EBRAKE_GO); inDat = bluetooth.read(); Serial.print(inDat); readIntoLineBuf(inDat); if (cmdLineReady()) { String cmd(g_lineBuf); if (g_debug) Serial.println("COMMAND " + cmd); processCommand(cmd); } } else if (g_mode != MODE_REMOTE && millis() % g_stepPeriod == 0) doUltrasonicCar(); } bool processCommand(String cmd) { if (cmd == "!beep") { buzzerOn(); delay(100); buzzerOff(); } else if (cmd.startsWith("!fwd ")) Forward(getSpeed(cmd, 0)); else if (cmd.startsWith("!bwd ")) Backward(getSpeed(cmd, 0)); else if (cmd.startsWith("!left ")) TurnLeft(getSpeed(cmd, 0)); else if (cmd.startsWith("!right ")) TurnRight(getSpeed(cmd, 0)); else if (cmd.startsWith("!fwdleft")) ForwardAndLeft(getSpeed(cmd, 0), getSpeed(cmd, 1)); else if (cmd.startsWith("!fwdright")) ForwardAndRight(getSpeed(cmd, 0), getSpeed(cmd, 1)); else if (cmd.startsWith("!bwdleft")) BackwardAndTurnLeft(getSpeed(cmd, 0), getSpeed(cmd, 1)); else if (cmd.startsWith("!bwdright")) BackwardAndTurnRight(getSpeed(cmd, 0), getSpeed(cmd, 1)); else Stop(); } int getSpeed(String cmd, int idx) { int mag = getCmdInt(cmd, idx); return g_speedFactor * mag + g_minSpeed; } int getCmdInt(String cmd, int idx) { int spaceIdx = cmd.indexOf(' '); for (int i=0; i < idx; i++) spaceIdx = cmd.indexOf(' ', spaceIdx+1); return cmd.substring(spaceIdx+1).toInt(); } bool cmdLineReady() { if (g_bufReadIdx != 0) return false; // still building line if (g_lineBuf[0] != '!') return false; // not a command line return true; } void readIntoLineBuf(char c) { if (c == '\n' || c == '\r' || c == '\0') { // finish line for processing, set ready for next line g_bufReadIdx = 0; return; } if (g_bufReadIdx >= MAXBUFSZ - 1) { // drop overflow bytes return; } g_lineBuf[g_bufReadIdx] = c; g_lineBuf[g_bufReadIdx+1] = '\0'; g_bufReadIdx++; } void doUltrasonicCar() { int distance = ultrasonic.distanceCm(); boolean isBlocked = (distance > 0 && distance < 60); if (isBlocked) g_timeLastBlocked = millis(); else if (millis() - g_timeLastBlocked < 100) isBlocked = true; if (isBlocked) digitalWrite(LED_PIN, HIGH); else digitalWrite(LED_PIN, LOW); boolean isStuck = (g_numTurnSteps > g_maxTurnSteps || g_numStepsForward > g_maxStepsForward); if (g_ebrake == EBRAKE_STOP && !isBlocked) { // /unstuck, ready for go signal g_ebrake = EBRAKE_WAIT; return; } else if (g_ebrake == EBRAKE_WAIT && isBlocked) { // "Go!" ResetUltrasonic(EBRAKE_GO); return; } else if (g_ebrake == EBRAKE_GO && isStuck) { // stuck -- yank ebrake g_ebrake = EBRAKE_STOP; Stop(); return; } if (g_ebrake != EBRAKE_GO) { // halt until !blocked and receive "Go" signal return; } if (isBlocked) { // evasive maneuvers! randomSeed(analogRead(A4)); int randnum = random(300); if (distance > 30) { if (randnum > 150 && !g_rightFlag) TurnLeft(g_moveSpeed); else TurnRight(g_moveSpeed); } else { if (randnum > 150) BackwardAndTurnLeft(g_moveSpeed, g_moveSpeed); else BackwardAndTurnRight(g_moveSpeed, g_moveSpeed); } } else { // ONWARD! Forward(g_moveSpeed); } } void ResetUltrasonic(int brakePos) { g_rightFlag = false; g_numStepsForward = 0; g_numTurnSteps = 0; g_ebrake = brakePos; if (g_debug && g_mode == MODE_ULTRASONIC) Serial.println("Reset"); } void Stop() { MotorL.stop(); MotorR.stop(); } void Forward(int speed) { g_numStepsForward++; g_numTurnSteps = 0; g_rightFlag = false; MotorL.run(speed * g_leftTrim); MotorR.run(speed * g_rightTrim); if (g_debug) Serial.println("Forward"); } void ForwardAndLeft(int fspeed, int lspeed) { g_numStepsForward++; g_numTurnSteps++; g_rightFlag = false; MotorL.run(fspeed - (lspeed / 2)); MotorR.run(fspeed); if (g_debug) Serial.println("Forward+Left"); } void ForwardAndRight(int fspeed, int rspeed) { g_numStepsForward++; g_numTurnSteps++; g_rightFlag = true; MotorL.run(fspeed); MotorR.run(fspeed - (rspeed / 2)); if (g_debug) Serial.println("Forward+Right"); } void Backward(int speed) { g_rightFlag = false; g_numTurnSteps = 0; MotorL.run(-speed); MotorR.run(-speed); if (g_debug) Serial.println("Backward"); } void TurnLeft(int speed) { g_rightFlag = false; g_numStepsForward = 0; g_numTurnSteps++; MotorL.run(-speed / 2); MotorR.run(speed / 2); if (g_debug) Serial.println("Left"); } void TurnRight(int speed) { g_rightFlag = true; g_numStepsForward = 0; g_numTurnSteps++; MotorL.run(speed / 2); MotorR.run(-speed / 2); if (g_debug) Serial.println("Right"); } void BackwardAndTurnLeft(int bspeed, int lspeed) { g_rightFlag = true; g_numStepsForward = 0; g_numTurnSteps++; MotorL.run(-bspeed + (lspeed / 2)); MotorR.run(-bspeed); if (g_debug) Serial.println("Backward+Left"); } void BackwardAndTurnRight(int bspeed, int rspeed) { g_rightFlag = false; g_numStepsForward = 0; g_numTurnSteps++; MotorL.run(-bspeed); MotorR.run(-bspeed + (rspeed / 2)); if (g_debug) Serial.println("Backward+Right"); } void ChangeSpeed(int spd) { g_moveSpeed = spd; } `
The main changes were to handle commands sent via Bluetooth. Bytes were read one at a time and accumulated into a buffer. The buffer was parsed for commands and the commands were executed. I had to tune the vectors a little to take advantage of the analog joystick input and to smooth out transitions to/from any direction.
I rigged the smartphone onto the robot with Legos. Then I downloaded and streamed the robot’s POV using the “IP Webcam” app because why not?
It’s ALIVE! Robot POV https://www.youtube.com/watch?v=5jLuNrIvPRs
Pilot POV https://www.youtube.com/watch?v=y7jnVtnGvS8
It worked better than I expected. The controller lag was not too bad, even with the inefficient command string processing scheme.
Tee hee
When I was done playing I restored it back to the old IR + Ultrasonic setup. I still haven’t figured out what’s the best next step from IR to Bluetooth for a kid.