]> defiant.homedns.org Git - pyshared.git/blob - bus_pirate.py
added initial bus pirate class
[pyshared.git] / bus_pirate.py
1 #!/usr/bin/env python
2 # -*- coding: iso-8859-15 -*-
3
4 import serial
5 import struct
6
7
8 # http://dangerousprototypes.com/docs/Bitbang
9 # http://dangerousprototypes.com/docs/SPI_(binary)
10 class BP:
11         def __init__(self, sDevice):
12                 self.pSerial = serial.Serial(sDevice, baudrate=115200, timeout=0.1)
13                 self.mode_bit_bang()
14
15         def command(self, cmd, num_read):
16                 self.pSerial.write(cmd)
17                 return self.pSerial.read(num_read)
18
19         def mode_bit_bang(self):
20                 for i in range(20):
21                         if self.command(chr(0x0), 5) == "BBIO1":
22                                 return
23                 raise Exception()
24
25         def mode_spi(self, mode, speed):
26                 if self.command(chr(0x1), 4) != "SPI1":
27                         raise Exception()
28                 self.spi_set_mode(mode)
29                 self.spi_set_speed(speed)
30
31         def spi_set_mode(self, mode):
32                 if mode not in range(0, 4):
33                         raise Exception("Unknown mode")
34                 if mode == 0:
35                         self.spi_command(chr(0b10001000))
36                 elif mode == 1:
37                         self.spi_command(chr(0b10001010))
38                 elif mode == 2:
39                         self.spi_command(chr(0b10001100))
40                 elif mode == 3:
41                         self.spi_command(chr(0b10001110))
42
43
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))
48
49         def command_byte_set(self, bit):
50                 enable = 1<<bit
51                 state = ord(self.command(chr(0x80 | enable, 1)))
52                 if not state & enable:
53                         raise Exception("Got 0x%x, expected 0xc0" % state)
54
55         def power_enable(self):
56                 self.command_byte_set(6)
57         
58         def get_adc(self):
59                 s = self.command(chr(0x14), 2)
60                 v = struct.unpack(">h", s)
61                 return v[0]/1024.0*6.6
62
63         def spi_command(self, cmd):
64                 ret = self.command(cmd, 1)
65                 if ord(ret) != 0x1:
66                         raise Exception()
67         
68         def spi_write(self, data, num_read=0):
69                 if len(data) > 4096:
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))