WPILibC++ 2024.3.2
SPI.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <stdint.h>
8
9#include <memory>
10#include <span>
11
12#include <hal/SPITypes.h>
13#include <units/time.h>
14
15namespace frc {
16
17class DigitalSource;
18
19/**
20 * SPI bus interface class.
21 *
22 * This class is intended to be used by sensor (and other SPI device) drivers.
23 * It probably should not be used directly.
24 *
25 */
26class SPI {
27 public:
28 /**
29 * SPI port.
30 */
31 enum Port {
32 /// Onboard SPI bus port CS0.
34 /// Onboard SPI bus port CS1.
36 /// Onboard SPI bus port CS2.
38 /// Onboard SPI bus port CS3.
40 /// MXP (roboRIO MXP) SPI bus port.
41 kMXP
42 };
43
44 /**
45 * SPI mode.
46 */
47 enum Mode {
48 /// Clock idle low, data sampled on rising edge.
50 /// Clock idle low, data sampled on falling edge.
52 /// Clock idle high, data sampled on falling edge.
54 /// Clock idle high, data sampled on rising edge.
56 };
57
58 /**
59 * Constructor
60 *
61 * @param port the physical SPI port
62 */
63 explicit SPI(Port port);
64
65 virtual ~SPI();
66
67 SPI(SPI&&) = default;
68 SPI& operator=(SPI&&) = default;
69
70 /**
71 * Returns the SPI port.
72 *
73 * @return The SPI port.
74 */
75 Port GetPort() const;
76
77 /**
78 * Configure the rate of the generated clock signal.
79 *
80 * The default value is 500,000Hz.
81 * The maximum value is 4,000,000Hz.
82 *
83 * @param hz The clock rate in Hertz.
84 */
85 void SetClockRate(int hz);
86
87 /**
88 * Sets the mode for the SPI device.
89 *
90 * <p>Mode 0 is Clock idle low, data sampled on rising edge
91 *
92 * <p>Mode 1 is Clock idle low, data sampled on falling edge
93 *
94 * <p>Mode 2 is Clock idle high, data sampled on falling edge
95 *
96 * <p>Mode 3 is Clock idle high, data sampled on rising edge
97 *
98 * @param mode The mode to set.
99 */
100 void SetMode(Mode mode);
101
102 /**
103 * Configure the chip select line to be active high.
104 */
106
107 /**
108 * Configure the chip select line to be active low.
109 */
111
112 /**
113 * Write data to the peripheral device. Blocks until there is space in the
114 * output FIFO.
115 *
116 * If not running in output only mode, also saves the data received
117 * on the CIPO input during the transfer into the receive FIFO.
118 */
119 virtual int Write(uint8_t* data, int size);
120
121 /**
122 * Read a word from the receive FIFO.
123 *
124 * Waits for the current transfer to complete if the receive FIFO is empty.
125 *
126 * If the receive FIFO is empty, there is no active transfer, and initiate
127 * is false, errors.
128 *
129 * @param initiate If true, this function pushes "0" into the transmit
130 * buffer and initiates a transfer. If false, this
131 * function assumes that data is already in the receive
132 * FIFO from a previous write.
133 * @param dataReceived Buffer to receive data from the device
134 * @param size The length of the transaction, in bytes
135 */
136 virtual int Read(bool initiate, uint8_t* dataReceived, int size);
137
138 /**
139 * Perform a simultaneous read/write transaction with the device
140 *
141 * @param dataToSend The data to be written out to the device
142 * @param dataReceived Buffer to receive data from the device
143 * @param size The length of the transaction, in bytes
144 */
145 virtual int Transaction(uint8_t* dataToSend, uint8_t* dataReceived, int size);
146
147 /**
148 * Initialize automatic SPI transfer engine.
149 *
150 * Only a single engine is available, and use of it blocks use of all other
151 * chip select usage on the same physical SPI port while it is running.
152 *
153 * @param bufferSize buffer size in bytes
154 */
155 void InitAuto(int bufferSize);
156
157 /**
158 * Frees the automatic SPI transfer engine.
159 */
160 void FreeAuto();
161
162 /**
163 * Set the data to be transmitted by the engine.
164 *
165 * Up to 16 bytes are configurable, and may be followed by up to 127 zero
166 * bytes.
167 *
168 * @param dataToSend data to send (maximum 16 bytes)
169 * @param zeroSize number of zeros to send after the data
170 */
171 void SetAutoTransmitData(std::span<const uint8_t> dataToSend, int zeroSize);
172
173 /**
174 * Start running the automatic SPI transfer engine at a periodic rate.
175 *
176 * InitAuto() and SetAutoTransmitData() must be called before calling this
177 * function.
178 *
179 * @param period period between transfers (us resolution)
180 */
181 void StartAutoRate(units::second_t period);
182
183 /**
184 * Start running the automatic SPI transfer engine when a trigger occurs.
185 *
186 * InitAuto() and SetAutoTransmitData() must be called before calling this
187 * function.
188 *
189 * @param source digital source for the trigger (may be an analog trigger)
190 * @param rising trigger on the rising edge
191 * @param falling trigger on the falling edge
192 */
193 void StartAutoTrigger(DigitalSource& source, bool rising, bool falling);
194
195 /**
196 * Stop running the automatic SPI transfer engine.
197 */
198 void StopAuto();
199
200 /**
201 * Force the engine to make a single transfer.
202 */
204
205 /**
206 * Read data that has been transferred by the automatic SPI transfer engine.
207 *
208 * Transfers may be made a byte at a time, so it's necessary for the caller
209 * to handle cases where an entire transfer has not been completed.
210 *
211 * Each received data sequence consists of a timestamp followed by the
212 * received data bytes, one byte per word (in the least significant byte).
213 * The length of each received data sequence is the same as the combined
214 * size of the data and zeroSize set in SetAutoTransmitData().
215 *
216 * Blocks until numToRead words have been read or timeout expires.
217 * May be called with numToRead=0 to retrieve how many words are available.
218 *
219 * @param buffer buffer where read words are stored
220 * @param numToRead number of words to read
221 * @param timeout timeout (ms resolution)
222 * @return Number of words remaining to be read
223 */
224 int ReadAutoReceivedData(uint32_t* buffer, int numToRead,
225 units::second_t timeout);
226
227 /**
228 * Get the number of bytes dropped by the automatic SPI transfer engine due
229 * to the receive buffer being full.
230 *
231 * @return Number of bytes dropped
232 */
234
235 /**
236 * Configure the Auto SPI Stall time between reads.
237 *
238 * @param port The number of the port to use. 0-3 for Onboard CS0-CS2, 4 for
239 * MXP.
240 * @param csToSclkTicks the number of ticks to wait before asserting the cs
241 * pin
242 * @param stallTicks the number of ticks to stall for
243 * @param pow2BytesPerRead the number of bytes to read before stalling
244 */
245 void ConfigureAutoStall(HAL_SPIPort port, int csToSclkTicks, int stallTicks,
246 int pow2BytesPerRead);
247
248 /**
249 * Initialize the accumulator.
250 *
251 * @param period Time between reads
252 * @param cmd SPI command to send to request data
253 * @param xferSize SPI transfer size, in bytes
254 * @param validMask Mask to apply to received data for validity checking
255 * @param validValue After valid_mask is applied, required matching value for
256 * validity checking
257 * @param dataShift Bit shift to apply to received data to get actual data
258 * value
259 * @param dataSize Size (in bits) of data field
260 * @param isSigned Is data field signed?
261 * @param bigEndian Is device big endian?
262 */
263 void InitAccumulator(units::second_t period, int cmd, int xferSize,
264 int validMask, int validValue, int dataShift,
265 int dataSize, bool isSigned, bool bigEndian);
266
267 /**
268 * Frees the accumulator.
269 */
271
272 /**
273 * Resets the accumulator to zero.
274 */
276
277 /**
278 * Set the center value of the accumulator.
279 *
280 * The center value is subtracted from each value before it is added to the
281 * accumulator. This is used for the center value of devices like gyros and
282 * accelerometers to make integration work and to take the device offset into
283 * account when integrating.
284 */
285 void SetAccumulatorCenter(int center);
286
287 /**
288 * Set the accumulator's deadband.
289 */
290 void SetAccumulatorDeadband(int deadband);
291
292 /**
293 * Read the last value read by the accumulator engine.
294 */
296
297 /**
298 * Read the accumulated value.
299 *
300 * @return The 64-bit value accumulated since the last Reset().
301 */
302 int64_t GetAccumulatorValue() const;
303
304 /**
305 * Read the number of accumulated values.
306 *
307 * Read the count of the accumulated values since the accumulator was last
308 * Reset().
309 *
310 * @return The number of times samples from the channel were accumulated.
311 */
312 int64_t GetAccumulatorCount() const;
313
314 /**
315 * Read the average of the accumulated value.
316 *
317 * @return The accumulated average value (value / count).
318 */
319 double GetAccumulatorAverage() const;
320
321 /**
322 * Read the accumulated value and the number of accumulated values atomically.
323 *
324 * This function reads the value and count atomically.
325 * This can be used for averaging.
326 *
327 * @param value Pointer to the 64-bit accumulated output.
328 * @param count Pointer to the number of accumulation cycles.
329 */
330 void GetAccumulatorOutput(int64_t& value, int64_t& count) const;
331
332 /**
333 * Set the center value of the accumulator integrator.
334 *
335 * The center value is subtracted from each value*dt before it is added to the
336 * integrated value. This is used for the center value of devices like gyros
337 * and accelerometers to take the device offset into account when integrating.
338 */
340
341 /**
342 * Read the integrated value. This is the sum of (each value * time between
343 * values).
344 *
345 * @return The integrated value accumulated since the last Reset().
346 */
348
349 /**
350 * Read the average of the integrated value. This is the sum of (each value
351 * times the time between values), divided by the count.
352 *
353 * @return The average of the integrated value accumulated since the last
354 * Reset().
355 */
357
358 protected:
361
362 private:
363 void Init();
364
365 class Accumulator;
366 std::unique_ptr<Accumulator> m_accum;
367};
368
369} // namespace frc
and restrictions which apply to each piece of software is included later in this file and or inside of the individual applicable source files The disclaimer of warranty in the WPILib license above applies to all code in and nothing in any of the other licenses gives permission to use the names of FIRST nor the names of the WPILib contributors to endorse or promote products derived from this software The following pieces of software have additional or alternate and or Google Inc All rights reserved Redistribution and use in source and binary with or without are permitted provided that the following conditions are this list of conditions and the following disclaimer *Redistributions in binary form must reproduce the above copyright this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution *Neither the name of Google Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED BUT NOT LIMITED THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY OR CONSEQUENTIAL WHETHER IN STRICT OR EVEN IF ADVISED OF THE POSSIBILITY OF SUCH January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation source
Definition: ThirdPartyNotices.txt:111
DigitalSource Interface.
Definition: DigitalSource.h:22
SPI bus interface class.
Definition: SPI.h:26
void SetAccumulatorIntegratedCenter(double center)
Set the center value of the accumulator integrator.
void SetChipSelectActiveLow()
Configure the chip select line to be active low.
double GetAccumulatorIntegratedAverage() const
Read the average of the integrated value.
void StopAuto()
Stop running the automatic SPI transfer engine.
virtual int Read(bool initiate, uint8_t *dataReceived, int size)
Read a word from the receive FIFO.
void ForceAutoRead()
Force the engine to make a single transfer.
void FreeAccumulator()
Frees the accumulator.
SPI(Port port)
Constructor.
void SetAccumulatorDeadband(int deadband)
Set the accumulator's deadband.
void ResetAccumulator()
Resets the accumulator to zero.
double GetAccumulatorAverage() const
Read the average of the accumulated value.
virtual ~SPI()
Port GetPort() const
Returns the SPI port.
void FreeAuto()
Frees the automatic SPI transfer engine.
void SetMode(Mode mode)
Sets the mode for the SPI device.
void SetAutoTransmitData(std::span< const uint8_t > dataToSend, int zeroSize)
Set the data to be transmitted by the engine.
void StartAutoRate(units::second_t period)
Start running the automatic SPI transfer engine at a periodic rate.
virtual int Transaction(uint8_t *dataToSend, uint8_t *dataReceived, int size)
Perform a simultaneous read/write transaction with the device.
void SetChipSelectActiveHigh()
Configure the chip select line to be active high.
int64_t GetAccumulatorCount() const
Read the number of accumulated values.
SPI(SPI &&)=default
int GetAccumulatorLastValue() const
Read the last value read by the accumulator engine.
double GetAccumulatorIntegratedValue() const
Read the integrated value.
hal::SPIPort m_port
Definition: SPI.h:359
SPI & operator=(SPI &&)=default
void SetAccumulatorCenter(int center)
Set the center value of the accumulator.
virtual int Write(uint8_t *data, int size)
Write data to the peripheral device.
Port
SPI port.
Definition: SPI.h:31
@ kOnboardCS2
Onboard SPI bus port CS2.
Definition: SPI.h:37
@ kOnboardCS1
Onboard SPI bus port CS1.
Definition: SPI.h:35
@ kOnboardCS0
Onboard SPI bus port CS0.
Definition: SPI.h:33
@ kOnboardCS3
Onboard SPI bus port CS3.
Definition: SPI.h:39
@ kMXP
MXP (roboRIO MXP) SPI bus port.
Definition: SPI.h:41
int64_t GetAccumulatorValue() const
Read the accumulated value.
Mode
SPI mode.
Definition: SPI.h:47
@ kMode2
Clock idle high, data sampled on falling edge.
Definition: SPI.h:53
@ kMode1
Clock idle low, data sampled on falling edge.
Definition: SPI.h:51
@ kMode3
Clock idle high, data sampled on rising edge.
Definition: SPI.h:55
@ kMode0
Clock idle low, data sampled on rising edge.
Definition: SPI.h:49
void InitAuto(int bufferSize)
Initialize automatic SPI transfer engine.
int ReadAutoReceivedData(uint32_t *buffer, int numToRead, units::second_t timeout)
Read data that has been transferred by the automatic SPI transfer engine.
void StartAutoTrigger(DigitalSource &source, bool rising, bool falling)
Start running the automatic SPI transfer engine when a trigger occurs.
HAL_SPIMode m_mode
Definition: SPI.h:360
int GetAutoDroppedCount()
Get the number of bytes dropped by the automatic SPI transfer engine due to the receive buffer being ...
void GetAccumulatorOutput(int64_t &value, int64_t &count) const
Read the accumulated value and the number of accumulated values atomically.
void InitAccumulator(units::second_t period, int cmd, int xferSize, int validMask, int validValue, int dataShift, int dataSize, bool isSigned, bool bigEndian)
Initialize the accumulator.
void SetClockRate(int hz)
Configure the rate of the generated clock signal.
void ConfigureAutoStall(HAL_SPIPort port, int csToSclkTicks, int stallTicks, int pow2BytesPerRead)
Configure the Auto SPI Stall time between reads.
A move-only C++ wrapper around a HAL handle.
Definition: Types.h:96
HAL_SPIMode
Definition: SPITypes.h:26
HAL_SPIPort
Definition: SPITypes.h:17
@ HAL_SPI_kMode0
Definition: SPITypes.h:27
@ HAL_SPI_kMode1
Definition: SPITypes.h:28
@ HAL_SPI_kMode2
Definition: SPITypes.h:29
@ HAL_SPI_kMode3
Definition: SPITypes.h:30
constexpr auto count() -> size_t
Definition: core.h:1203
Definition: AprilTagPoseEstimator.h:15