Debian Codegraph @

libraries/Wire/src/Wire.cpp

raw
1 /*
2 TwoWire.cpp - TWI/I2C library for Wiring & Arduino
3 Copyright (c) 2006 Nicholas Zambetti. All right reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 Modified 2012 by Todd Krein ([email protected]) to implement repeated starts
20 Modified 2017 by Chuck Todd ([email protected]) to correct Unconfigured Slave Mode reboot
21 Modified 2020 by Greyson Christoforo ([email protected]) to implement timeouts
22 */
23
24 extern "C" {
25 #include <stdlib.h>
26 #include <string.h>
27 #include <inttypes.h>
28 #include "utility/twi.h"
29 }
30
31 #include "Wire.h"
32
33 // Initialize Class Variables //////////////////////////////////////////////////
34
35 uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
36 uint8_t TwoWire::rxBufferIndex = 0;
37 uint8_t TwoWire::rxBufferLength = 0;
38
39 uint8_t TwoWire::txAddress = 0;
40 uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
41 uint8_t TwoWire::txBufferIndex = 0;
42 uint8_t TwoWire::txBufferLength = 0;
43
44 uint8_t TwoWire::transmitting = 0;
45 void (*TwoWire::user_onRequest)(void);
46 void (*TwoWire::user_onReceive)(int);
47
48 // Constructors ////////////////////////////////////////////////////////////////
49
50 TwoWire::TwoWire()
51 {
52 }
53
54 // Public Methods //////////////////////////////////////////////////////////////
55
56 void TwoWire::begin(void)
57 {
58 rxBufferIndex = 0;
59 rxBufferLength = 0;
60
61 txBufferIndex = 0;
62 txBufferLength = 0;
63
64 twi_init();
65 twi_attachSlaveTxEvent(onRequestService); // default callback must exist
66 twi_attachSlaveRxEvent(onReceiveService); // default callback must exist
67 }
68
69 void TwoWire::begin(uint8_t address)
70 {
71 begin();
72 twi_setAddress(address);
73 }
74
75 void TwoWire::begin(int address)
76 {
77 begin((uint8_t)address);
78 }
79
80 void TwoWire::end(void)
81 {
82 twi_disable();
83 }
84
85 void TwoWire::setClock(uint32_t clock)
86 {
87 twi_setFrequency(clock);
88 }
89
90 /***
91 * Sets the TWI timeout.
92 *
93 * This limits the maximum time to wait for the TWI hardware. If more time passes, the bus is assumed
94 * to have locked up (e.g. due to noise-induced glitches or faulty slaves) and the transaction is aborted.
95 * Optionally, the TWI hardware is also reset, which can be required to allow subsequent transactions to
96 * succeed in some cases (in particular when noise has made the TWI hardware think there is a second
97 * master that has claimed the bus).
98 *
99 * When a timeout is triggered, a flag is set that can be queried with `getWireTimeoutFlag()` and is cleared
100 * when `clearWireTimeoutFlag()` or `setWireTimeoutUs()` is called.
101 *
102 * Note that this timeout can also trigger while waiting for clock stretching or waiting for a second master
103 * to complete its transaction. So make sure to adapt the timeout to accommodate for those cases if needed.
104 * A typical timeout would be 25ms (which is the maximum clock stretching allowed by the SMBus protocol),
105 * but (much) shorter values will usually also work.
106 *
107 * In the future, a timeout will be enabled by default, so if you require the timeout to be disabled, it is
108 * recommended you disable it by default using `setWireTimeoutUs(0)`, even though that is currently
109 * the default.
110 *
111 * @param timeout a timeout value in microseconds, if zero then timeout checking is disabled
112 * @param reset_with_timeout if true then TWI interface will be automatically reset on timeout
113 * if false then TWI interface will not be reset on timeout
114
115 */
116 void TwoWire::setWireTimeout(uint32_t timeout, bool reset_with_timeout){
117 twi_setTimeoutInMicros(timeout, reset_with_timeout);
118 }
119
120 /***
121 * Returns the TWI timeout flag.
122 *
123 * @return true if timeout has occurred since the flag was last cleared.
124 */
125 bool TwoWire::getWireTimeoutFlag(void){
126 return(twi_manageTimeoutFlag(false));
127 }
128
129 /***
130 * Clears the TWI timeout flag.
131 */
132 void TwoWire::clearWireTimeoutFlag(void){
133 twi_manageTimeoutFlag(true);
134 }
135
136 uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint32_t iaddress, uint8_t isize, uint8_t sendStop)
137 {
138 if (isize > 0) {
139 // send internal address; this mode allows sending a repeated start to access
140 // some devices' internal registers. This function is executed by the hardware
141 // TWI module on other processors (for example Due's TWI_IADR and TWI_MMR registers)
142
143 beginTransmission(address);
144
145 // the maximum size of internal address is 3 bytes
146 if (isize > 3){
147 isize = 3;
148 }
149
150 // write internal register address - most significant byte first
151 while (isize-- > 0)
152 write((uint8_t)(iaddress >> (isize*8)));
153 endTransmission(false);
154 }
155
156 // clamp to buffer length
157 if(quantity > BUFFER_LENGTH){
158 quantity = BUFFER_LENGTH;
159 }
160 // perform blocking read into buffer
161 uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop);
162 // set rx buffer iterator vars
163 rxBufferIndex = 0;
164 rxBufferLength = read;
165
166 return read;
167 }
168
169 uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) {
170 return requestFrom((uint8_t)address, (uint8_t)quantity, (uint32_t)0, (uint8_t)0, (uint8_t)sendStop);
171 }
172
173 uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
174 {
175 return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
176 }
177
178 uint8_t TwoWire::requestFrom(int address, int quantity)
179 {
180 return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
181 }
182
183 uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
184 {
185 return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop);
186 }
187
188 void TwoWire::beginTransmission(uint8_t address)
189 {
190 // indicate that we are transmitting
191 transmitting = 1;
192 // set address of targeted slave
193 txAddress = address;
194 // reset tx buffer iterator vars
195 txBufferIndex = 0;
196 txBufferLength = 0;
197 }
198
199 void TwoWire::beginTransmission(int address)
200 {
201 beginTransmission((uint8_t)address);
202 }
203
204 //
205 // Originally, 'endTransmission' was an f(void) function.
206 // It has been modified to take one parameter indicating
207 // whether or not a STOP should be performed on the bus.
208 // Calling endTransmission(false) allows a sketch to
209 // perform a repeated start.
210 //
211 // WARNING: Nothing in the library keeps track of whether
212 // the bus tenure has been properly ended with a STOP. It
213 // is very possible to leave the bus in a hung state if
214 // no call to endTransmission(true) is made. Some I2C
215 // devices will behave oddly if they do not see a STOP.
216 //
217 uint8_t TwoWire::endTransmission(uint8_t sendStop)
218 {
219 // transmit buffer (blocking)
220 uint8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop);
221 // reset tx buffer iterator vars
222 txBufferIndex = 0;
223 txBufferLength = 0;
224 // indicate that we are done transmitting
225 transmitting = 0;
226 return ret;
227 }
228
229 // This provides backwards compatibility with the original
230 // definition, and expected behaviour, of endTransmission
231 //
232 uint8_t TwoWire::endTransmission(void)
233 {
234 return endTransmission(true);
235 }
236
237 // must be called in:
238 // slave tx event callback
239 // or after beginTransmission(address)
240 size_t TwoWire::write(uint8_t data)
241 {
242 if(transmitting){
243 // in master transmitter mode
244 // don't bother if buffer is full
245 if(txBufferLength >= BUFFER_LENGTH){
246 setWriteError();
247 return 0;
248 }
249 // put byte in tx buffer
250 txBuffer[txBufferIndex] = data;
251 ++txBufferIndex;
252 // update amount in buffer
253 txBufferLength = txBufferIndex;
254 }else{
255 // in slave send mode
256 // reply to master
257 twi_transmit(&data, 1);
258 }
259 return 1;
260 }
261
262 // must be called in:
263 // slave tx event callback
264 // or after beginTransmission(address)
265 size_t TwoWire::write(const uint8_t *data, size_t quantity)
266 {
267 if(transmitting){
268 // in master transmitter mode
269 for(size_t i = 0; i < quantity; ++i){
270 write(data[i]);
271 }
272 }else{
273 // in slave send mode
274 // reply to master
275 twi_transmit(data, quantity);
276 }
277 return quantity;
278 }
279
280 // must be called in:
281 // slave rx event callback
282 // or after requestFrom(address, numBytes)
283 int TwoWire::available(void)
284 {
285 return rxBufferLength - rxBufferIndex;
286 }
287
288 // must be called in:
289 // slave rx event callback
290 // or after requestFrom(address, numBytes)
291 int TwoWire::read(void)
292 {
293 int value = -1;
294
295 // get each successive byte on each call
296 if(rxBufferIndex < rxBufferLength){
297 value = rxBuffer[rxBufferIndex];
298 ++rxBufferIndex;
299 }
300
301 return value;
302 }
303
304 // must be called in:
305 // slave rx event callback
306 // or after requestFrom(address, numBytes)
307 int TwoWire::peek(void)
308 {
309 int value = -1;
310
311 if(rxBufferIndex < rxBufferLength){
312 value = rxBuffer[rxBufferIndex];
313 }
314
315 return value;
316 }
317
318 void TwoWire::flush(void)
319 {
320 // XXX: to be implemented.
321 }
322
323 // behind the scenes function that is called when data is received
324 void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
325 {
326 // don't bother if user hasn't registered a callback
327 if(!user_onReceive){
328 return;
329 }
330 // don't bother if rx buffer is in use by a master requestFrom() op
331 // i know this drops data, but it allows for slight stupidity
332 // meaning, they may not have read all the master requestFrom() data yet
333 if(rxBufferIndex < rxBufferLength){
334 return;
335 }
336 // copy twi rx buffer into local read buffer
337 // this enables new reads to happen in parallel
338 for(uint8_t i = 0; i < numBytes; ++i){
339 rxBuffer[i] = inBytes[i];
340 }
341 // set rx iterator vars
342 rxBufferIndex = 0;
343 rxBufferLength = numBytes;
344 // alert user program
345 user_onReceive(numBytes);
346 }
347
348 // behind the scenes function that is called when data is requested
349 void TwoWire::onRequestService(void)
350 {
351 // don't bother if user hasn't registered a callback
352 if(!user_onRequest){
353 return;
354 }
355 // reset tx buffer iterator vars
356 // !!! this will kill any pending pre-master sendTo() activity
357 txBufferIndex = 0;
358 txBufferLength = 0;
359 // alert user program
360 user_onRequest();
361 }
362
363 // sets function called on slave write
364 void TwoWire::onReceive( void (*function)(int) )
365 {
366 user_onReceive = function;
367 }
368
369 // sets function called on slave read
370 void TwoWire::onRequest( void (*function)(void) )
371 {
372 user_onRequest = function;
373 }
374
375 // Preinstantiate Objects //////////////////////////////////////////////////////
376
377 TwoWire Wire = TwoWire();
378