Created
June 28, 2018 22:02
-
-
Save bmidgley/9f8b15beb28a74369c796f19988248f1 to your computer and use it in GitHub Desktop.
bluetooth python car
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# sudo apt-get install bluez python-gobject | |
# hcitool scan | |
# echo 1234 | bluez-simple-agent hci0 00:12:05:09:90:51 | |
# bluez-test-device trusted 00:12:05:09:90:51 yes | |
import socket | |
import time | |
class BluetoothCar: | |
def __init__(self, mac_address): | |
self.speed = 15 | |
self.socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) | |
self.socket.connect((mac_address, 1)) | |
def _write(self, data_byte): | |
self.socket.send(bytearray([data_byte + self.speed])) | |
def set_speed(self, speed): | |
self.speed = min(15, max(0, speed)) | |
def drive(self, command, duration=1.0): | |
self._write(command) | |
time.sleep(duration) | |
self.stop() | |
def forwards(self, duration=1.0): | |
self.drive(0x10, duration) | |
def reverse(self, duration=1.0): | |
self.drive(0x20, duration) | |
def left(self, duration=1.0): | |
self.drive(0x50, duration) | |
def right(self, duration=1.0): | |
self.drive(0x60, duration) | |
def stop(self): | |
self._write(0x00) | |
def __del__(self): | |
self.stop() | |
if __name__ == "__main__": | |
car = BluetoothCar("00:12:05:09:90:51") | |
car.reverse(2) | |
car.set_speed(7) | |
car.forwards() | |
car.left() | |
car.right() | |
car.reverse() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment