python-socket-examples / bluetooth_car.py

import socket
import time

class RawBluetoothSocket:
    def __init__(self, mac_address="00:12:05:09:98:36"):
        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(bytes([data_byte]))


class BluetoothCar:
    
    def __init__(self):
        self.bluetooth_connection = RawBluetoothSocket()

    def drive(self, command, duration=None):
        self.bluetooth_connection.write(command)
        if duration is not None:
            time.sleep(duration)
            self.stop()

    def forwards(self, duration=1.0):
        self.drive(0x16, duration)

    def reverse(self, duration=1.0):
        self.drive(0x26, duration)

    def left(self, duration=1.0):
        self.drive(0x57, duration)

    def right(self, duration=1.0):
        self.drive(0x67, duration)

    def stop(self):
        self.bluetooth_connection.write(0x00)

    def __del__(self):
        self.stop()

if __name__ == "__main__":
    car = BluetoothCar()
    while True:
        car.forwards(0.05)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.