can.py 2.12 KB
Newer Older
Damien George's avatar
Damien George committed
1
2
from pyb import CAN

Henrik Sölver's avatar
Henrik Sölver committed
3
CAN.initfilterbanks(14)
4
5
6
7
can = CAN(1)
print(can)

can.init(CAN.LOOPBACK)
Damien George's avatar
Damien George committed
8
9
print(can)
print(can.any(0))
10

Henrik Sölver's avatar
Henrik Sölver committed
11
12
13
# Catch all filter
can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0))

Damien George's avatar
Damien George committed
14
15
16
can.send('abcd', 123)
print(can.any(0))
print(can.recv(0))
17
18
19
20
21
22
23

can.send('abcd', -1)
print(can.recv(0))

can.send('abcd', 0x7FF + 1)
print(can.recv(0))

Henrik Sölver's avatar
Henrik Sölver committed
24
# Test too long message
25
26
27
28
29
30
31
32
33
try:
    can.send('abcdefghi', 0x7FF)
except ValueError:
    print('passed')
else:
    print('failed')

del can

Henrik Sölver's avatar
Henrik Sölver committed
34
# Testing extended IDs
35
can = CAN(1, CAN.LOOPBACK, extframe = True)
Henrik Sölver's avatar
Henrik Sölver committed
36
37
38
# Catch all filter
can.setfilter(0, CAN.MASK32, 0, (0, 0))

39
40
41
42
43
print(can)

try:
    can.send('abcde', 0x7FF + 1)
except ValueError:
Henrik Sölver's avatar
Henrik Sölver committed
44
    print('failed')
45
46
47
48
49
50
else:
    r = can.recv(0)
    if r[0] == 0x7FF+1 and r[3] == b'abcde':
        print('passed')
    else:
        print('failed, wrong data received')
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

del can

# Test RxCallbacks
can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4))
can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8))
def cb0(bus, reason):
    print('cb0')
    if reason == 0:
        print('pending')
    if reason == 1:
        print('full')
    if reason == 2:
        print('overflow')

def cb1(bus, reason):
    print('cb1')
    if reason == 0:
        print('pending')
    if reason == 1:
        print('full')
    if reason == 2:
        print('overflow')

def cb0a(bus, reason):
    print('cb0a')
    if reason == 0:
        print('pending')
    if reason == 1:
        print('full')
    if reason == 2:
        print('overflow')

def cb1a(bus, reason):
    print('cb1a')
    if reason == 0:
        print('pending')
    if reason == 1:
        print('full')
    if reason == 2:
        print('overflow')


can.rxcallback(0, cb0)
can.rxcallback(1, cb1)

can.send('11111111',1)
can.send('22222222',2)
can.send('33333333',3)
can.rxcallback(0, cb0a)
can.send('44444444',4)

can.send('55555555',5)
can.send('66666666',6)
can.send('77777777',7)
can.rxcallback(1, cb1a)
can.send('88888888',8)

print(can.recv(0))
print(can.recv(0))
print(can.recv(0))
print(can.recv(1))
print(can.recv(1))
print(can.recv(1))

can.send('11111111',1)
can.send('55555555',5)

print(can.recv(0))
print(can.recv(1))