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?
35 #Set the default rate.
38 #Array of supported rates.
39 MCPrates=[100,125,250,500,1000];
41 def MCPsetrate(self,rate=125):
42 """Sets the data rate in kHz."""
43 # Now we need to set the timing registers. See chapter 5 of
44 # the MCP2515 datasheet to get some clue as to how this
45 # arithmetic of this works, as my comments here will likely be
46 # rambling, incoherent, and unchanged after I get the infernal
49 # First, we must chose a Time Quanta (QT) which is used to
50 # define the durations of these segments. Section 5.3
51 # suggests setting BRP<5:0> to 0x04 to get a TQ=500ns, as a 20
52 # MHz crystal gives a clock period of 50ns. This way, for 125
53 # kHz communication, the bit time must be 16 TQ.
55 # A bit consists of four parts:
58 # 3: PhaseSeg1 (PS1) 7 TQ
59 # 4: PhaseSeg2 (PS2) 6 TQ
61 # CNF1 with a prescaler of 4 and a SJW of 1 TQ. SJW of 4
62 # might be more stable.
63 #self.poke8(0x2a,0x04);
65 # CNF2 with a BLTMODE of 1, SAM of 0, PS1 of 7TQ, and PRSEG of 2TQ
68 # (6<<3) | # 6+1=7TQ for PHSEG1
69 # (1) # 1+1=2TQ for PRSEG
72 #CNF3 with a PS2 length of 6TQ.
78 #These are the new examples.
81 #125 kHz, 16 TQ, not quite as worked out above.
105 print "WARNING: Because of chip errata, this probably won't work."
107 print "Given unsupported rate of %i kHz." % rate;
108 print "Defaulting to 125kHz.";
112 self.poke8(0x2a,CNF1);
113 self.poke8(0x29,CNF2);
114 self.poke8(0x28,CNF3);
117 """Reset the MCP2515 chip."""
118 self.SPItrans([0xC0]);
119 def MCPcanstat(self):
120 """Get the CAN Status."""
121 return self.peek8(0x0E);
122 def MCPreqstatNormal(self):
123 """Set the CAN state."""
125 self.MCPbitmodify(0x0F,0xE0,(state<<5));
126 def MCPreqstatSleep(self):
127 """Set the CAN state."""
129 self.MCPbitmodify(0x0F,0xE0,(state<<5));
130 def MCPreqstatLoopback(self):
131 """Set the CAN state."""
133 self.MCPbitmodify(0x0F,0xE0,(state<<5));
134 def MCPreqstatListenOnly(self):
135 """Set the CAN state."""
137 self.MCPbitmodify(0x0F,0xE0,(state<<5));
138 def MCPreqstatConfiguration(self):
139 """Set the CAN state."""
141 self.MCPbitmodify(0x0F,0xE0,(state<<5));
143 def MCPcanstatstr(self):
144 """Read the present status as a string."""
145 status=self.MCPcanstat();
146 opmod=(status&0xE0)>>5;
147 return self.MCPMODES[opmod];
148 def MCPrxstatus(self):
149 """Reads the RX Status by the SPI verb of the same name."""
150 data=self.SPItrans([0xB0,0x00]);
153 def MCPreadstatus(self):
154 """Reads the Read Status by the SPI verb of the same name."""
155 #See page 67 of the datasheet for the flag names.
156 data=self.SPItrans([0xA0,0x00]);
159 def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
160 """Requests to send one of the transmit buffers."""
162 if TXB0: flags=flags|1;
163 if TXB1: flags=flags|2;
164 if TXB2: flags=flags|4;
167 print "Warning: Requesting to send no buffer.";
169 self.SPItrans([0x80|flags]);
170 def readrxbuffer(self,packbuf=0):
171 """Reads the RX buffer. Might have old data."""
172 data=self.SPItrans([0x90|(packbuf<<2),
176 0x00, 0x00, 0x00, 0x00,
177 0x00, 0x00, 0x00, 0x00
179 return data[1:len(data)];
180 def writetxbuffer(self,packet,packbuf=0):
181 """Writes the transmit buffer."""
182 self.SPItrans([0x40|(packbuf<<1)]+packet);
185 """Reads the next incoming packet from either buffer.
186 Returns None immediately if no packet is waiting."""
187 status=self.MCPrxstatus()&0xC0;
189 #Buffer 0 has higher priority.
190 return self.readrxbuffer(0);
192 #Buffer 1 has lower priority.
193 return self.readrxbuffer(1);
196 def txpacket(self,packet):
197 """Transmits a packet through one of the outbound buffers.
198 As usual, the packet should begin with SIDH.
199 For now, only TXB0 is supported."""
200 self.writetxbuffer(packet,0);
201 self.MCPrts(TXB0=True);
202 def packet2str(self,packet):
203 """Converts a packet from the internal format to a string."""
206 toprint=toprint+("%02x "%ord(bar))
209 """Read a byte from the given address. Untested."""
210 data=self.SPItrans([0x03,adr&0xFF,00]);
212 def MCPbitmodify(self,adr,mask,data):
213 """Writes a byte with a mask. Doesn't work for many registers."""
214 data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
216 def poke8(self,adr,val):
217 """Poke a value into RAM. Untested"""
218 self.SPItrans([0x02,adr&0xFF,val&0xFF]);