WPILibC++ 2024.1.1-beta-4
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:
29 enum Mode {
30 kMode0 = HAL_SPI_kMode0, /*!< Clock idle low, data sampled on rising edge */
31 kMode1 =
32 HAL_SPI_kMode1, /*!< Clock idle low, data sampled on falling edge */
33 kMode2 =
34 HAL_SPI_kMode2, /*!< Clock idle high, data sampled on falling edge */
35 kMode3 = HAL_SPI_kMode3 /*!< Clock idle high, data sampled on rising edge */
36 };
37
38 /**
39 * Constructor
40 *
41 * @param port the physical SPI port
42 */
43 explicit SPI(Port port);
44
45 virtual ~SPI();
46
47 SPI(SPI&&) = default;
48 SPI& operator=(SPI&&) = default;
49
50 Port GetPort() const;
51
52 /**
53 * Configure the rate of the generated clock signal.
54 *
55 * The default value is 500,000Hz.
56 * The maximum value is 4,000,000Hz.
57 *
58 * @param hz The clock rate in Hertz.
59 */
60 void SetClockRate(int hz);
61
62 /**
63 * Sets the mode for the SPI device.
64 *
65 * <p>Mode 0 is Clock idle low, data sampled on rising edge
66 *
67 * <p>Mode 1 is Clock idle low, data sampled on falling edge
68 *
69 * <p>Mode 2 is Clock idle high, data sampled on falling edge
70 *
71 * <p>Mode 3 is Clock idle high, data sampled on rising edge
72 *
73 * @param mode The mode to set.
74 */
75 void SetMode(Mode mode);
76
77 /**
78 * Configure the chip select line to be active high.
79 */
81
82 /**
83 * Configure the chip select line to be active low.
84 */
86
87 /**
88 * Write data to the peripheral device. Blocks until there is space in the
89 * output FIFO.
90 *
91 * If not running in output only mode, also saves the data received
92 * on the CIPO input during the transfer into the receive FIFO.
93 */
94 virtual int Write(uint8_t* data, int size);
95
96 /**
97 * Read a word from the receive FIFO.
98 *
99 * Waits for the current transfer to complete if the receive FIFO is empty.
100 *
101 * If the receive FIFO is empty, there is no active transfer, and initiate
102 * is false, errors.
103 *
104 * @param initiate If true, this function pushes "0" into the transmit
105 * buffer and initiates a transfer. If false, this
106 * function assumes that data is already in the receive
107 * FIFO from a previous write.
108 * @param dataReceived Buffer to receive data from the device
109 * @param size The length of the transaction, in bytes
110 */
111 virtual int Read(bool initiate, uint8_t* dataReceived, int size);
112
113 /**
114 * Perform a simultaneous read/write transaction with the device
115 *
116 * @param dataToSend The data to be written out to the device
117 * @param dataReceived Buffer to receive data from the device
118 * @param size The length of the transaction, in bytes
119 */
120 virtual int Transaction(uint8_t* dataToSend, uint8_t* dataReceived, int size);
121
122 /**
123 * Initialize automatic SPI transfer engine.
124 *
125 * Only a single engine is available, and use of it blocks use of all other
126 * chip select usage on the same physical SPI port while it is running.
127 *
128 * @param bufferSize buffer size in bytes
129 */
130 void InitAuto(int bufferSize);
131
132 /**
133 * Frees the automatic SPI transfer engine.
134 */
135 void FreeAuto();
136
137 /**
138 * Set the data to be transmitted by the engine.
139 *
140 * Up to 16 bytes are configurable, and may be followed by up to 127 zero
141 * bytes.
142 *
143 * @param dataToSend data to send (maximum 16 bytes)
144 * @param zeroSize number of zeros to send after the data
145 */
146 void SetAutoTransmitData(std::span<const uint8_t> dataToSend, int zeroSize);
147
148 /**
149 * Start running the automatic SPI transfer engine at a periodic rate.
150 *
151 * InitAuto() and SetAutoTransmitData() must be called before calling this
152 * function.
153 *
154 * @param period period between transfers (us resolution)
155 */
156 void StartAutoRate(units::second_t period);
157
158 /**
159 * Start running the automatic SPI transfer engine when a trigger occurs.
160 *
161 * InitAuto() and SetAutoTransmitData() must be called before calling this
162 * function.
163 *
164 * @param source digital source for the trigger (may be an analog trigger)
165 * @param rising trigger on the rising edge
166 * @param falling trigger on the falling edge
167 */
168 void StartAutoTrigger(DigitalSource& source, bool rising, bool falling);
169
170 /**
171 * Stop running the automatic SPI transfer engine.
172 */
173 void StopAuto();
174
175 /**
176 * Force the engine to make a single transfer.
177 */
179
180 /**
181 * Read data that has been transferred by the automatic SPI transfer engine.
182 *
183 * Transfers may be made a byte at a time, so it's necessary for the caller
184 * to handle cases where an entire transfer has not been completed.
185 *
186 * Each received data sequence consists of a timestamp followed by the
187 * received data bytes, one byte per word (in the least significant byte).
188 * The length of each received data sequence is the same as the combined
189 * size of the data and zeroSize set in SetAutoTransmitData().
190 *
191 * Blocks until numToRead words have been read or timeout expires.
192 * May be called with numToRead=0 to retrieve how many words are available.
193 *
194 * @param buffer buffer where read words are stored
195 * @param numToRead number of words to read
196 * @param timeout timeout (ms resolution)
197 * @return Number of words remaining to be read
198 */
199 int ReadAutoReceivedData(uint32_t* buffer, int numToRead,
200 units::second_t timeout);
201
202 /**
203 * Get the number of bytes dropped by the automatic SPI transfer engine due
204 * to the receive buffer being full.
205 *
206 * @return Number of bytes dropped
207 */
209
210 /**
211 * Configure the Auto SPI Stall time between reads.
212 *
213 * @param port The number of the port to use. 0-3 for Onboard CS0-CS2, 4 for
214 * MXP.
215 * @param csToSclkTicks the number of ticks to wait before asserting the cs
216 * pin
217 * @param stallTicks the number of ticks to stall for
218 * @param pow2BytesPerRead the number of bytes to read before stalling
219 */
220 void ConfigureAutoStall(HAL_SPIPort port, int csToSclkTicks, int stallTicks,
221 int pow2BytesPerRead);
222
223 /**
224 * Initialize the accumulator.
225 *
226 * @param period Time between reads
227 * @param cmd SPI command to send to request data
228 * @param xferSize SPI transfer size, in bytes
229 * @param validMask Mask to apply to received data for validity checking
230 * @param validValue After valid_mask is applied, required matching value for
231 * validity checking
232 * @param dataShift Bit shift to apply to received data to get actual data
233 * value
234 * @param dataSize Size (in bits) of data field
235 * @param isSigned Is data field signed?
236 * @param bigEndian Is device big endian?
237 */
238 void InitAccumulator(units::second_t period, int cmd, int xferSize,
239 int validMask, int validValue, int dataShift,
240 int dataSize, bool isSigned, bool bigEndian);
241
242 /**
243 * Frees the accumulator.
244 */
246
247 /**
248 * Resets the accumulator to zero.
249 */
251
252 /**
253 * Set the center value of the accumulator.
254 *
255 * The center value is subtracted from each value before it is added to the
256 * accumulator. This is used for the center value of devices like gyros and
257 * accelerometers to make integration work and to take the device offset into
258 * account when integrating.
259 */
260 void SetAccumulatorCenter(int center);
261
262 /**
263 * Set the accumulator's deadband.
264 */
265 void SetAccumulatorDeadband(int deadband);
266
267 /**
268 * Read the last value read by the accumulator engine.
269 */
271
272 /**
273 * Read the accumulated value.
274 *
275 * @return The 64-bit value accumulated since the last Reset().
276 */
277 int64_t GetAccumulatorValue() const;
278
279 /**
280 * Read the number of accumulated values.
281 *
282 * Read the count of the accumulated values since the accumulator was last
283 * Reset().
284 *
285 * @return The number of times samples from the channel were accumulated.
286 */
287 int64_t GetAccumulatorCount() const;
288
289 /**
290 * Read the average of the accumulated value.
291 *
292 * @return The accumulated average value (value / count).
293 */
294 double GetAccumulatorAverage() const;
295
296 /**
297 * Read the accumulated value and the number of accumulated values atomically.
298 *
299 * This function reads the value and count atomically.
300 * This can be used for averaging.
301 *
302 * @param value Pointer to the 64-bit accumulated output.
303 * @param count Pointer to the number of accumulation cycles.
304 */
305 void GetAccumulatorOutput(int64_t& value, int64_t& count) const;
306
307 /**
308 * Set the center value of the accumulator integrator.
309 *
310 * The center value is subtracted from each value*dt before it is added to the
311 * integrated value. This is used for the center value of devices like gyros
312 * and accelerometers to take the device offset into account when integrating.
313 */
315
316 /**
317 * Read the integrated value. This is the sum of (each value * time between
318 * values).
319 *
320 * @return The integrated value accumulated since the last Reset().
321 */
323
324 /**
325 * Read the average of the integrated value. This is the sum of (each value
326 * times the time between values), divided by the count.
327 *
328 * @return The average of the integrated value accumulated since the last
329 * Reset().
330 */
332
333 protected:
336
337 private:
338 void Init();
339
340 class Accumulator;
341 std::unique_ptr<Accumulator> m_accum;
342};
343
344} // 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
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:334
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
Definition: SPI.h:28
@ kOnboardCS2
Definition: SPI.h:28
@ kOnboardCS1
Definition: SPI.h:28
@ kOnboardCS0
Definition: SPI.h:28
@ kOnboardCS3
Definition: SPI.h:28
@ kMXP
Definition: SPI.h:28
int64_t GetAccumulatorValue() const
Read the accumulated value.
Mode
Definition: SPI.h:29
@ kMode2
Definition: SPI.h:33
@ kMode1
Definition: SPI.h:31
@ kMode3
Definition: SPI.h:35
@ kMode0
Definition: SPI.h:30
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:335
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:29
HAL_SPIPort
Definition: SPITypes.h:18
@ HAL_SPI_kMode0
Definition: SPITypes.h:30
@ HAL_SPI_kMode1
Definition: SPITypes.h:31
@ HAL_SPI_kMode2
Definition: SPITypes.h:32
@ HAL_SPI_kMode3
Definition: SPITypes.h:33
constexpr auto count() -> size_t
Definition: core.h:1203
Definition: AprilTagPoseEstimator.h:15