-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitalu_I2C.py
79 lines (70 loc) · 2.45 KB
/
twitalu_I2C.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
import time
import sys
# appends to PYTHONPATH the location of the example codes
sys.path.append(r'/home/pi/git/quick2wire-python-api/')
import quick2wire.i2c as q2w_i2c
import twitalu_globals as globals
# Useful port expander registers
IODIRA = 0x00
IODIRB = 0x01
IPOLA = 0x02
IPOLB = 0x03
GPPUA = 0x0C
GPPUB = 0x0D
GPIOA = 0x12
GPIOB = 0x13
# Each of the following functions require these arguments:
# port_expand_addr = {0x20, 0x21, 0x22} (hex address)
# port = {A, B} (expander port)
# value = {0b00000000} (8-bit data value)
# This function sets the port's pull up resistors
# For pull-up, value = 0b11111111. Port must be set to input.
def set_IO_PULL_UP(port_expand_addr, port, value):
with q2w_i2c.I2CMaster() as bus:
if port == 'A':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPPUA, value))
elif port == 'B':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPPUB, value))
# This function sets the port's logic polarity
# For inverting, value = 0b11111111. For non-inverting, value = 0b00000000
def set_IO_POL(port_expand_addr, port, value):
with q2w_i2c.I2CMaster() as bus:
if port == 'A':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, IPOLA, value))
elif port == 'B':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, IPOLB, value))
# This function sets the direction of a port's GPIO
# For input, value = 0b11111111. For output, value = 0b00000000
def set_IO_DIR(port_expand_addr, port, value):
with q2w_i2c.I2CMaster() as bus:
if port == 'A':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, IODIRA, value))
elif port == 'B':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, IODIRB, value))
# This function writes data to the port expander
def write_data(port_expand_addr, port, value):
with q2w_i2c.I2CMaster() as bus:
if port == 'A':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPIOA, value))
elif port == 'B':
bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPIOB, value))
# This function reads data from the port expander
def read_data(port_expand_addr, port):
with q2w_i2c.I2CMaster() as bus:
if port == 'A':
return bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPIOA),
q2w_i2c.reading(port_expand_addr, 1))[0][0]
elif port == 'B':
return bus.transaction(
q2w_i2c.writing_bytes(port_expand_addr, GPIOB),
q2w_i2c.reading(port_expand_addr, 1))[0][0]