2 # -*- coding: iso-8859-15 -*-
17 # http://dangerousprototypes.com/docs/Bitbang
18 # http://dangerousprototypes.com/docs/SPI_(binary)
20 def __init__(self, sDevice):
21 self.pSerial = serial.Serial(sDevice, baudrate=115200, timeout=0.1)
26 def command(self, cmd, num_read):
27 self.pSerial.write(cmd)
28 return self.pSerial.read(num_read)
30 def mode_bit_bang(self):
32 if self.command(chr(0x0), 5) == "BBIO1":
34 raise Exception("Failed to enter bit bang mode")
36 def mode_spi(self, mode, speed):
37 if self.command(chr(0x1), 4) != "SPI1":
39 self.spi_set_mode(mode)
40 self.spi_set_speed(speed)
42 def spi_set_mode(self, mode):
43 if mode not in range(0, 4):
44 raise Exception("Unknown mode")
46 self.spi_command(chr(0b10001000))
48 self.spi_command(chr(0b10001010))
50 self.spi_command(chr(0b10001100))
52 self.spi_command(chr(0b10001110))
54 def spi_set_speed(self, speed):
55 lSpeeds = ["30kHz", "125kHz", "250kHz", "1MHz", "2MHz", "2.6MHz", "4MHz", "8MHz"]
56 val = lSpeeds.index(speed)
57 self.spi_command(chr(0b01100000 | val))
59 def power_enable(self):
60 self.set_io("POWER", True)
63 s = self.command(chr(0x14), 2)
64 v = struct.unpack(">h", s)
65 return v[0]/1024.0*6.6
67 def spi_command(self, cmd):
68 ret = self.command(cmd, 1)
72 def spi_write(self, data, num_read=0):
74 raise Exception("SPI Data String too long")
75 return self.spi_command(struct.pack(">Bhh%ds" % len(data), 0x04, len(data), num_read, data))
77 def set_io_output(self, pin):
78 if pin not in dPinToBit.keys():
79 raise Exception("Bad output pin")
80 self.io_dir &= ~(1 << dPinToBit[pin])
81 state = 0b01000000 | self.io_dir
82 self.command(chr(state), 1)
84 def set_io_input(self, pin):
85 if pin not in dPinToBit.keys():
86 raise Exception("Bad input pin")
87 self.io_dir |= (1 << dPinToBit[pin])
88 state = 0b01000000 | self.io_dir
89 self.command(chr(state), 1)
91 def set_io(self, pin, val):
92 if pin not in dPinToBit.keys():
93 raise Exception("Bad output pin")
95 self.io_state |= (1 << dPinToBit[pin])
97 self.io_state &= ~(1 << dPinToBit[pin])
98 state = self.update_io()
101 state = self.command(chr(0b10000000 | self.io_state), 1)
104 def get_io(self, pin):
105 if pin not in dPinToBit.keys():
106 raise Exception("Bad I/O pin")
107 state = self.update_io()
108 return state & (1 << dPinToBit[pin])