-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface_spi.py
56 lines (52 loc) · 2.18 KB
/
interface_spi.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
import os, sys
from my_exceptions import SetupException, SendingException
from str_bit_helper import *
wiringpi_path = os.path.abspath('WiringPi-Python')
sys.path.append( wiringpi_path )
import wiringpi2 as wiringpi
class InterfaceSPI():
# constants used in constructor
CE_0 = 0
CE_1 = 1
SPEED_0_5MHZ = 500000
SPEED_1_0MHZ = 2 * SPEED_0_5MHZ
SPEED_2_0MHZ = 2 * SPEED_1_0MHZ
SPEED_4_0MHZ = 2 * SPEED_2_0MHZ
SPEED_8_0MHZ = 2 * SPEED_4_0MHZ
SPEED_16_0MHZ = 2 * SPEED_8_0MHZ
SPEED_32_0MHZ = 2 * SPEED_16_0MHZ
def __init__(self, ce_channel, speed):
self.ce_channel = ce_channel
os.system('gpio load spi')
wiringpi.wiringPiSetup()
error = wiringpi.wiringPiSPISetup(ce_channel,speed)
if (error == -1):
raise SetupException('Error while SPI setup')
print('InterfaceSPI initalized (CE_%d, speed:%.1fMHz)' % (ce_channel, speed * 0.000001))
# read_write - True = read; False = write
# address_char - address to read / write
# string_data - string which char values will be overwritten on read or written on write
def send(self, read_write, address_char, string_data):
if (read_write):
address_bin = fill_bits_to_byte(str2bits(address_char))
address_char = bits2str('1' + address_bin[1:])
string_data_cpy = address_char + string_data[:]
error = wiringpi.wiringPiSPIDataRW(self.ce_channel, string_data_cpy)
if (error == -1):
# couldn't make SendingEcteption take more than one argument in contructor...
#error_msg = SendingException.get_msg(read_write, address_char, string_data)
error_msg = (
'Error while SPI %s address:%s data:%s' % (
'read' if read_write else 'write',
str2bits(address_char),
'(not important)' if read_write else str2bits(string_data)
)
)
raise SendingException(error_msg)
return string_data_cpy[1:] if read_write else None
def __unicode__(self):
return self.__str__()
def __repr__(self):
return self.__str__()
def __str__(self):
return 'InterfaceSPI'