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