Skip to content

Instantly share code, notes, and snippets.

@cyrus007
Last active June 4, 2019 17:15
Show Gist options
  • Save cyrus007/9f00afd40caa1614dac932768a005dd4 to your computer and use it in GitHub Desktop.
Save cyrus007/9f00afd40caa1614dac932768a005dd4 to your computer and use it in GitHub Desktop.
Relay uBit data via BLE to RPi connected to rctoy
"""
© 2017 [email protected]
This program reads the Accelerometer:x,y,z values
coming from uBit via BLE and sends it to the network
"""
import signal
import socket
import sys
import time
from bluezero import microbit
ubit = microbit.Microbit(adapter_addr='##:##:##:##:##:##', device_addr='##:##:##:##:##:##')
def signal_handler(signal, frame):
print('You pressed Ctrl+C exiting!')
sock.close()
ubit.disconnect()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port on the server given by the caller
server_address = (sys.argv[1], 23)
print('connecting to %s port %s' % server_address, file=sys.stderr)
sock.connect(server_address)
# Now connect to uBit
move = False
try:
message = 'Starting...'
print('sending {}'.format(message), file=sys.stderr)
sock.sendall(message)
ubit.connect()
while True:
if ubit.button_a > 0:
move = True
ubit.pixels = [0b01110,
0b11000,
0b01111,
0b00011,
0b01110]
time.sleep(0.25)
elif ubit.button_b > 0:
move = False
ubit.pixels = [0b11111,
0b00100,
0b00100,
0b00100,
0b00100]
time.sleep(0.25)
else:
x, y, z = ubit.accelerometer
print('X = {}, Y = {}, Z = {}'.format(x,y,z))
if move:
if x > 0.4:
""" move right """
message = 'right:' + repr(x)
if x < -0.4:
""" move left """
message = 'left:' + repr(x)
if y > 0.4:
""" move backward """
message += ',backward:' + repr(y)
if y < -0.4:
""" move forward """
message = ',forward:' + repr(y)
print('Movement: {}'.format(message), file=sys.stderr)
message = '< 10| 200| 100| 600|1000>\n'
print('Sending {}'.format(message), file=sys.stderr)
sock.sendall(message)
time.sleep(0.01)
finally:
sock.close()
ubit.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment