Raspberry Pi Jam "Chaos Car!"
January 22, 2017 [Programming, Python, Raspberry Pi]Raspberry Pi 1
+ battery pack
+ Bluetooth USB dongle
+ i-racer bluetooth car
+ Raspberry Pi camera
+ some Python code
+ loads of sellotape
=
Chaos car!
Here's the code:
#!/usr/bin/env python2 import os import random import bluetooth import sys import time car_name = "DaguCar" def find_car_mac( car_name ): ret = None print "Scanning for a device called %s..." % car_name devices = bluetooth.discover_devices() for addr in devices: dev_name = bluetooth.lookup_name( addr ) if dev_name == car_name: print "Car found! (MAC=%s)" % addr time.sleep( 1 ) return addr else: print "Skipping device named '%s'." % dev_name sys.stderr.write( "Couldn't find a device called %s!\n" % car_name ) sys.exit( 1 ) #car_mac = find_car_mac( car_name ) print "Using hard-coded MAC address" car_mac = "20:13:04:23:05:71" print "Connecting to the car at %s..." % car_mac sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM ) sock.connect( ( car_mac, 1 ) ) class Car: def turn_right(self): print("looking right") sock.send( '\x6A' ) def turn_left(self): print("looking left") sock.send( '\x5A' ) def roll_forward(self): print("watch out in front coming forward") sock.send( '\x1A' ) def roll_backward(self): print("beep beep going backward") sock.send( '\x2A' ) def wait(self): print("waiting") sock.send( '\x00' ) car = Car() instruction = ["turn right", "turn left", "roll forward", "roll backward", "wait"] while True: ci = random.choice(instruction) if ci == "turn right": car.turn_right() elif ci == "turn left": car.turn_left() elif ci == "roll forward": car.roll_forward() elif ci == "roll backward": car.roll_backward() elif ci == "wait": car.wait() time.sleep(0.5)
Improving the code to avoid bumping into walls is left as an exercise for the reader.