2 # GoodFET MCP2515 CAN Bus Client
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
7 # Currently being updated by Siege Technology's ENGS89 team
8 # Primary contact: Theodore Sumers <ted.sumers at gmail.com>
10 # 10.4/41.6/83.3 kHz sniffing
12 # debugs on TX and RX packet
13 # int-based state change reqs for preserving state
16 # The MCP2515 is a CAN Bus to SPI adapter from Microchip Technology,
17 # as used in the Goodthopter series of boards. It requires a separate
18 # chip for voltage level conversion, such as the MCP2551.
20 import sys, time, string, cStringIO, struct, glob, os;
22 from GoodFETSPI import GoodFETSPI;
24 class GoodFETMCPCAN(GoodFETSPI):
25 """This class uses the regular SPI app to implement a CAN Bus
26 adapter on the Goodthopter10 hardware."""
27 MCPMODES=["Normal","Sleep","Loopback","Listen-only","Configuration",
28 "UNKNOWN","UNKNOWN","PowerUp"];
31 """Sets up the ports."""
33 self.MCPreset(); #Reset the chip.
34 # We're going to set some registers, so we must be in config
36 self.MCPreqstatConfiguration();
38 # If we don't enable promiscous mode, we'll miss a lot of
39 # packets. It can be manually disabled later.
40 #self.poke8(0x60,0xFF); #TODO Does this have any unpleasant side effects?
41 self.poke8(0x60,0x66); #Wanted FF, but some bits are reserved.
43 #Array of supported rates.
44 MCPrates=[10.4, 41.6, 83.3, 100, 125, 250, 500, 1000];
47 """Reset the MCP2515 chip."""
48 self.SPItrans([0xC0]);
51 ################ SETTING BAUD RATE ################
54 def MCPsetrate(self,rate=125):
55 """Sets the data rate in kHz."""
56 # Now we need to set the timing registers. See chapter 5 of
57 # the MCP2515 datasheet to get some clue as to how this
58 # arithmetic of this works.
61 #STORE the prior status
62 oldstatus=self.MCPcanstatint();
63 print "Setting rate of %i kHz." % rate;
64 #print "Current state is %s." % self.MCPcanstatstr();
65 self.MCPreqstatConfiguration();
66 # print "Switched to %s state." % self.MCPcanstatstr();
69 if rate>41 and rate<42:
70 # NOT CHECKED: based on kvaser website.
71 # Sets baud rate for 41.6 kbps
75 elif rate>10 and rate<11:
76 # NOT CHECKED: based on kvaser website.
77 # Sets baud rate for 10.4 kbps
82 #125 kHz, 16 TQ, not quite as worked out above.
91 elif rate>83 and rate<83.5:
93 # 0.04% error from 83.30
112 print "WARNING: Because of chip errata, this probably won't work."
114 print "Given unsupported rate of %i kHz." % rate;
115 print "Defaulting to 125kHz.";
119 self.poke8(0x2a,CNF1);
120 self.poke8(0x29,CNF2);
121 self.poke8(0x28,CNF3);
123 # and now return to whatever state we were in before
124 self.MCPreqstat(oldstatus);
125 #print "Reverted to %s." % self.MCPcanstatstr();
128 ################# STATE MANAGEMENT ##################
130 def MCPcanstat(self):
131 """Get the CAN Status."""
132 return self.peek8(0x0E);
133 def MCPcanstatstr(self):
134 """Read the present status as a string."""
135 opmod=self.MCPcanstatint();
136 return self.MCPMODES[opmod];
137 def MCPcanstatint(self):
138 """Read present status as an int."""
139 return self.MCPcanstat()>>5;
142 def MCPreqstat(self, state):
143 """Set the CAN state."""
145 self.MCPreqstatNormal();
147 self.MCPreqstatSleep();
149 self.MCPreqstatLoopback();
151 self.MCPreqstatListenOnly();
153 self.MCPreqstatConfiguration();
155 print "Invalid state entered; defaulting to Listen-Only"
156 self.MCPreqstatListenOnly();
157 def MCPreqstatNormal(self):
158 """Set the CAN state."""
160 self.MCPbitmodify(0x0F,0xE0,(state<<5));
161 def MCPreqstatSleep(self):
162 """Set the CAN state."""
164 self.MCPbitmodify(0x0F,0xE0,(state<<5));
165 def MCPreqstatLoopback(self):
166 """Set the CAN state."""
168 self.MCPbitmodify(0x0F,0xE0,(state<<5));
169 def MCPreqstatListenOnly(self):
170 """Set the CAN state."""
172 self.MCPbitmodify(0x0F,0xE0,(state<<5));
173 def MCPreqstatConfiguration(self):
174 """Set the CAN state."""
176 self.MCPbitmodify(0x0F,0xE0,(state<<5));
178 #################### RX MANAGEMENT #####################
180 def MCPrxstatus(self):
181 """Reads the RX Status by the SPI verb of the same name."""
182 data=self.SPItrans([0xB0,0x00]);
185 def MCPreadstatus(self):
186 """Reads the Read Status by the SPI verb of the same name."""
187 #See page 69 of the datasheet for the flag names.
188 data=self.SPItrans([0xA0,0x00]);
191 def readrxbuffer(self,packbuf=0):
192 """Reads the RX buffer. Might have old data."""
193 data=self.SPItrans([0x90|(packbuf<<2),
197 0x00, 0x00, 0x00, 0x00,
198 0x00, 0x00, 0x00, 0x00
201 return data[1:len(data)];
204 """Reads the next incoming packet from either buffer.
205 Returns None immediately if no packet is waiting."""
206 status=self.MCPrxstatus()&0xC0;
208 #Buffer 0 has higher priority.
209 return self.readrxbuffer(0);
211 #Buffer 1 has lower priority.
212 return self.readrxbuffer(1);
216 ################# TX MANAGEMENT ##################
218 def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
219 """Requests to send one of the transmit buffers."""
221 if TXB0: flags=flags|1;
222 if TXB1: flags=flags|2;
223 if TXB2: flags=flags|4;
226 print "Warning: Requesting to send no buffer.";
227 if self.MCPcanstat()>>5!=0:
228 print "Warning: currently in %s mode. NOT in normal mode! May not transmit." %self.MCPcanstatstr();
229 self.SPItrans([0x80|flags]);
231 def writetxbuffer(self,packet,packbuf=0):
232 """Writes the transmit buffer."""
234 self.SPItrans([0x40|(packbuf<<1)]+packet);
235 #READ BACK BUFFER 0 to check what we're about to send out
236 data=self.SPItrans([0x03, 0x31,
240 0x00, 0x00, 0x00, 0x00,
241 0x00, 0x00, 0x00, 0x00
243 print "about to transmit:" + self.packet2str(data[2:len(data)]);
245 def txpacket(self,packet):
246 """Transmits a packet through one of the outbound buffers.
247 As usual, the packet should begin with SIDH.
248 For now, only TXB0 is supported."""
250 self.writetxbuffer(packet,0);
252 #self.SPItrans([0x81]);
253 self.MCPrts(TXB0=True);
256 ############### UTILITY FUNCTIONS #################
258 def packet2str(self,packet):
259 """Converts a packet from the internal format to a string."""
262 toprint=toprint+("%02x "%ord(bar))
265 """Read a byte from the given address. Untested."""
266 data=self.SPItrans([0x03,adr&0xFF,00]);
268 def poke8(self,adr,val):
269 """Poke a value into RAM. Untested"""
270 self.SPItrans([0x02,adr&0xFF,val&0xFF]);
271 newval=self.peek8(adr);
273 print "Failed to poke %02x to %02x. Got %02x." % (adr,val,newval);
274 print "Are you not in idle mode?";
276 def MCPbitmodify(self,adr,mask,data):
277 """Writes a byte with a mask. Doesn't work for many registers."""
278 data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
281 ############### DEBUG UTILITIES: STATUS MESSAGES ##############
283 # def MCPrxstatusmessage(self):
284 # """Returns string indicating status of RX buffers"""
285 # status = self.MCPrxstatus();
288 # print "No RX message";
290 # print "Message in RXB0";
292 # print "Message in RXB1";
294 # print "Messages in both buffers";
300 # CNF3/2/1 = 0x28, 29, 2a