|
A projects to learn the SPI API of the RP2040 C SDK, and to use it to control an external Flash IC. In this post, I refine the m25 c++ class again. Return byte arrays as Standard Template Library (stl) containers |
Arrays as return values instead of output parameters
Usually, when a function returns multiple values, we pass it a buffer as one of the parameters, and the function can fill it. There are other options, but this is often how we see it done.
In c++ you can return a container as a return value. You can construct it in the function - right size and value, then hand it over to the calling function. Here's a function that reads 3 bytes from the m25 IC over SPI, then hands over the results an stl vector:
std::vector<uint8_t> m25::rdid() {
uint8_t buf[3];
// command
uint8_t cmdbuf[] = {
RDID,
};
setDataBits(8);
select();
spi_write_blocking(spi, cmdbuf, 1);
spi_read_blocking(spi, 0, buf, 1); // Manufacturer Identification
spi_read_blocking(spi, 0, buf + sizeof buf[0], 2); // Device Identification (Memory Type || Memory Capacity)
deselect();
return std::vector<uint8_t> (buf, buf + (sizeof buf/sizeof buf[0]));
}
The calling program can use it like this:
// get and print read identifier
bytes = eeprom->rdid();
std::cout << "read identifier: ";
for ( auto bte: bytes ) std::cout << std::hex << static_cast<int>(bte) << " ";
std::cout << std::endl;
Result:
read identifier: 20 20 15
VSCode project attached: spi_flash_20221203.zip









Top Comments