2 # GoodFET MCP2515 CAN Bus Client
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
6 # This code is being rewritten and refactored. You've been warned!
9 # The MCP2515 is a CAN Bus to SPI adapter from Microchip Technology,
10 # as used in the Goodthopter series of boards. It requires a separate
11 # chip for voltage level conversion, such as the MCP2551.
13 import sys, time, string, cStringIO, struct, glob, os;
15 from GoodFETSPI import GoodFETSPI;
17 class GoodFETMCPCAN(GoodFETSPI):
18 """This class uses the regular SPI app to implement a CAN Bus
19 adapter on the Goodthopter10 hardware."""
20 MCPMODES=["Normal","Sleep","Loopback","Listen-only","Configuration",
21 "UNKNOWN","UNKNOWN","PowerUp"];
23 """Sets up the ports."""
25 self.MCPreset(); #Reset the chip.
27 # We're going to set some registers, so we must be in config
29 self.MCPreqstatConfiguration();
31 # If we don't enable promiscous mode, we'll miss a lot of
32 # packets. It can be manually disabled later.
33 #self.poke8(0x60,0xFF); #TODO Does this have any unpleasant side effects?
34 self.poke8(0x60,0x66); #Wanted FF, but some bits are reserved.
36 #Set the default rate.
39 #Array of supported rates.
40 MCPrates=[83.3, 100, 125,
43 def MCPsetrate(self,rate=125):
44 """Sets the data rate in kHz."""
45 # Now we need to set the timing registers. See chapter 5 of
46 # the MCP2515 datasheet to get some clue as to how this
47 # arithmetic of this works, as my comments here will likely be
48 # rambling, incoherent, and unchanged after I get the infernal
51 # First, we must chose a Time Quanta (QT) which is used to
52 # define the durations of these segments. Section 5.3
53 # suggests setting BRP<5:0> to 0x04 to get a TQ=500ns, as a 20
54 # MHz crystal gives a clock period of 50ns. This way, for 125
55 # kHz communication, the bit time must be 16 TQ.
57 # A bit consists of four parts:
60 # 3: PhaseSeg1 (PS1) 7 TQ
61 # 4: PhaseSeg2 (PS2) 6 TQ
63 # CNF1 with a prescaler of 4 and a SJW of 1 TQ. SJW of 4
64 # might be more stable.
65 #self.poke8(0x2a,0x04);
67 # CNF2 with a BLTMODE of 1, SAM of 0, PS1 of 7TQ, and PRSEG of 2TQ
70 # (6<<3) | # 6+1=7TQ for PHSEG1
71 # (1) # 1+1=2TQ for PRSEG
74 #CNF3 with a PS2 length of 6TQ.
80 print "Setting rate of %i kHz." % rate;
82 #These are the new examples.
84 #125 kHz, 16 TQ, not quite as worked out above.
93 elif rate>83 and rate<83.5:
95 # 0.04% error from 83.30
114 print "WARNING: Because of chip errata, this probably won't work."
116 print "Given unsupported rate of %i kHz." % rate;
117 print "Defaulting to 125kHz.";
121 self.poke8(0x2a,CNF1);
122 self.poke8(0x29,CNF2);
123 self.poke8(0x28,CNF3);
126 """Reset the MCP2515 chip."""
127 self.SPItrans([0xC0]);
128 def MCPcanstat(self):
129 """Get the CAN Status."""
130 return self.peek8(0x0E);
131 def MCPreqstatNormal(self):
132 """Set the CAN state."""
134 self.MCPbitmodify(0x0F,0xE0,(state<<5));
135 def MCPreqstatSleep(self):
136 """Set the CAN state."""
138 self.MCPbitmodify(0x0F,0xE0,(state<<5));
139 def MCPreqstatLoopback(self):
140 """Set the CAN state."""
142 self.MCPbitmodify(0x0F,0xE0,(state<<5));
143 def MCPreqstatListenOnly(self):
144 """Set the CAN state."""
146 self.MCPbitmodify(0x0F,0xE0,(state<<5));
147 def MCPreqstatConfiguration(self):
148 """Set the CAN state."""
150 self.MCPbitmodify(0x0F,0xE0,(state<<5));
152 def MCPcanstatstr(self):
153 """Read the present status as a string."""
154 status=self.MCPcanstat();
155 opmod=(status&0xE0)>>5;
156 return self.MCPMODES[opmod];
157 def MCPrxstatus(self):
158 """Reads the RX Status by the SPI verb of the same name."""
159 data=self.SPItrans([0xB0,0x00]);
162 def MCPreadstatus(self):
163 """Reads the Read Status by the SPI verb of the same name."""
164 #See page 67 of the datasheet for the flag names.
165 data=self.SPItrans([0xA0,0x00]);
168 def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
169 """Requests to send one of the transmit buffers."""
171 if TXB0: flags=flags|1;
172 if TXB1: flags=flags|2;
173 if TXB2: flags=flags|4;
176 print "Warning: Requesting to send no buffer.";
178 self.SPItrans([0x80|flags]);
179 def readrxbuffer(self,packbuf=0):
180 """Reads the RX buffer. Might have old data."""
181 data=self.SPItrans([0x90|(packbuf<<2),
185 0x00, 0x00, 0x00, 0x00,
186 0x00, 0x00, 0x00, 0x00
188 return data[1:len(data)];
189 def writetxbuffer(self,packet,packbuf=0):
190 """Writes the transmit buffer."""
191 self.SPItrans([0x40|(packbuf<<1)]+packet);
194 """Reads the next incoming packet from either buffer.
195 Returns None immediately if no packet is waiting."""
196 status=self.MCPrxstatus()&0xC0;
198 #Buffer 0 has higher priority.
199 return self.readrxbuffer(0);
201 #Buffer 1 has lower priority.
202 return self.readrxbuffer(1);
205 def txpacket(self,packet):
206 """Transmits a packet through one of the outbound buffers.
207 As usual, the packet should begin with SIDH.
208 For now, only TXB0 is supported."""
209 self.writetxbuffer(packet,0);
210 self.MCPrts(TXB0=True);
211 def packet2str(self,packet):
212 """Converts a packet from the internal format to a string."""
215 toprint=toprint+("%02x "%ord(bar))
218 """Read a byte from the given address. Untested."""
219 data=self.SPItrans([0x03,adr&0xFF,00]);
221 def MCPbitmodify(self,adr,mask,data):
222 """Writes a byte with a mask. Doesn't work for many registers."""
223 data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
225 def poke8(self,adr,val):
226 """Poke a value into RAM. Untested"""
227 self.SPItrans([0x02,adr&0xFF,val&0xFF]);
228 newval=self.peek8(adr);
230 print "Failed to poke %02x to %02x. Got %02x." % (adr,val,newval);
231 print "Are you not in idle mode?";