2 # -*- coding: iso-8859-15 -*-
8 # http://dangerousprototypes.com/docs/Bitbang
9 # http://dangerousprototypes.com/docs/SPI_(binary)
11 def __init__(self, sDevice):
12 self.pSerial = serial.Serial(sDevice, baudrate=115200, timeout=0.1)
15 def command(self, cmd, num_read):
16 self.pSerial.write(cmd)
17 return self.pSerial.read(num_read)
19 def mode_bit_bang(self):
21 if self.command(chr(0x0), 5) == "BBIO1":
25 def mode_spi(self, mode, speed):
26 if self.command(chr(0x1), 4) != "SPI1":
28 self.spi_set_mode(mode)
29 self.spi_set_speed(speed)
31 def spi_set_mode(self, mode):
32 if mode not in range(0, 4):
33 raise Exception("Unknown mode")
35 self.spi_command(chr(0b10001000))
37 self.spi_command(chr(0b10001010))
39 self.spi_command(chr(0b10001100))
41 self.spi_command(chr(0b10001110))
44 def spi_set_speed(self, speed):
45 lSpeeds = ["30kHz", "125kHz", "250kHz", "1MHz", "2MHz", "2.6MHz", "4MHz", "8MHz"]
46 val = lSpeeds.index(speed)
47 self.spi_command(chr(0b01100000 | val))
49 def command_byte_set(self, bit):
51 state = ord(self.command(chr(0x80 | enable, 1)))
52 if not state & enable:
53 raise Exception("Got 0x%x, expected 0xc0" % state)
55 def power_enable(self):
56 self.command_byte_set(6)
59 s = self.command(chr(0x14), 2)
60 v = struct.unpack(">h", s)
61 return v[0]/1024.0*6.6
63 def spi_command(self, cmd):
64 ret = self.command(cmd, 1)
68 def spi_write(self, data, num_read=0):
70 raise Exception("SPI Data String too long")
71 return self.spi_command(struct.pack(">Bhh%ds" % len(data), 0x04, len(data), num_read, data))