code.py
1 # SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import busio 7 import board 8 import pulseio 9 import adafruit_irremote 10 import adafruit_lis3dh 11 12 # Control debug output: it takes time so don't unless you're debugging 13 DEBUG_LOG = False 14 15 # Control codes 16 STOP = 0x01 17 ROTATE_LEFT = 0x02 18 ROTATE_RIGHT = 0x03 19 FORWARD = 0x04 20 FORWARD_LEFT = 0x05 21 FORWARD_RIGHT = 0x06 22 REVERSE = 0x07 23 REVERSE_LEFT = 0x08 24 REVERSE_RIGHT = 0x09 25 26 TRANSMIT_DELAY = 0.1 27 28 # Setup accelerometer 29 i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) 30 sensor = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19) 31 32 # Create a 'pulseio' output, to send infrared signals on the IR transmitter @ 38KHz 33 pulseout = pulseio.PulseOut(board.IR_TX, frequency=38000, duty_cycle=2 ** 15) 34 35 # Create an encoder that will take numbers and turn them into IR pulses 36 encoder = adafruit_irremote.GenericTransmit(header=[9500, 4500], 37 one=[550, 550], 38 zero=[550, 1700], 39 trail=0) 40 41 def log(s): 42 """Optionally output some text. 43 :param string s: test to output 44 """ 45 if DEBUG_LOG: 46 print(s) 47 48 49 while True: 50 x, y, z = sensor.acceleration 51 log("{0: 0.3f} {1: 0.3f} {2: 0.3f}".format(x, y, z)) 52 if z < -5.0 and abs(y) < 3.0: # palm down 53 if x < -5.0: # tipped counterclockwise 54 log("ROTATE_LEFT") 55 encoder.transmit(pulseout, [ROTATE_LEFT] * 4) 56 elif x > 5.0: # tipped clockwise 57 log("ROTATE_RIGHT") 58 encoder.transmit(pulseout, [ROTATE_RIGHT] * 4) 59 else: # level 60 log("STOP") 61 encoder.transmit(pulseout, [STOP] * 4) 62 elif y > 5.0: # palm facing away 63 if x < -5.0: # tipped counterclockwise 64 log("FORWARD_LEFT") 65 encoder.transmit(pulseout, [FORWARD_LEFT] * 4) 66 elif x > 5.0: # tipped clockwise 67 log("FORWARD_RIGHT") 68 encoder.transmit(pulseout, [FORWARD_RIGHT] * 4) 69 else: # straight up 70 log("FORWARD") 71 encoder.transmit(pulseout, [FORWARD] * 4) 72 elif y < -5.0: # palm facing toward (hand down) 73 if x < -5.0: # tipped counterclockwise 74 log("REVERSE_RIGHT") 75 encoder.transmit(pulseout, [REVERSE_RIGHT] * 4) 76 elif x > 5.0: # tipped clockwise 77 log("REVERSE_LEFT") 78 encoder.transmit(pulseout, [REVERSE_LEFT] * 4) 79 else: #straight down 80 log("REVERSE") 81 encoder.transmit(pulseout, [REVERSE] * 4) 82 83 time.sleep(TRANSMIT_DELAY)