SPI access (using helper class)
The helper class version is a more abstract implementation. Creating a transceiver
object for reading and writing is the start of using the bus, and destroying the object is the end of using the bus.
By creating the object in the decision expression of the if statement, the validity period of the object is limited to the scope of the if clause, and the object is destroyed when it exits the if clause, at which point the bus usage termination procedure is performed.
In addition, read/write objects implement the mwx::stream
interface, allowing the use of the <<
operator, etc.
The start and end of bus usage is aligned with the validity period of the object to improve the visibility of the source code and to prevent omissions in the termination procedure, etc.
Unify read/write procedures with the mwx::stream
interface
Reading process and its termination procedure in scope if() { ... }
to do the reading with a helper class.
In the above, the x
object created by the get_rwer()
method is used to read and write one byte at a time. 1.
create x
object in if(...)
Generate the x
object in the get_rwer()
method. At the same time, set the select pin of the SPI bus. (The type is resolved with the universal reference auto&&
by type inference. 2.)
the generated x
object has a operator bool ()
defined, which is used to evaluate the decision expression, which is always true
for the SPI bus.
x
object defines uint8_t transfer(uint8_t)
method, which is called to perform 8bit read/write transfer to SPI. 4. 4.if() { ... }
Destructor of x
is called at the end of the scope to release the select pin of the SPI bus.
Obtains the worker object used to read/write the SPI bus.
Each transfers 8-bit, 16-bit, and 32-bit data, and returns the read result with the same data width as the written data width.
The int
and uint8_t
types perform 8-bit transfer.
Types uint16_t
and uint32_t
perform 16-bit and 32-bit transfers, respectively.
The transfer result is stored in an internal FIFO queue of up to 16 bytes and read by the >>
operator. Since the buffer is not large, it is assumed to be read out after each transfer.
Specify a variable with the same data width as the previous transfer.
If the result of the read is not needed, use the null_stream() object; it skips reading by the data byte specified by i. If the result of the read is not needed, use the null_stream() object.