29 SpiDevice(
const std::string& device, uint32_t speed, uint8_t mode)
30 : fd_(open(device.c_str(), O_RDWR)), speed_(speed) {
31 assert(!device.empty());
34 std::perror(
"Failed to open SPI device");
37 if (ioctl(fd_, SPI_IOC_WR_MODE, &mode) < 0 ||
38 ioctl(fd_, SPI_IOC_WR_MAX_SPEED_HZ, &speed_) < 0) {
40 std::perror(
"Failed to configure SPI device");
61 std::array<uint8_t, 2> tx_buf = {{
static_cast<uint8_t
>(reg | 0x80), 0}};
62 std::array<uint8_t, 2> rx_buf = {{0, 0}};
63 struct spi_ioc_transfer transfer{};
64 transfer.tx_buf =
reinterpret_cast<uint64_t
>(tx_buf.data());
65 transfer.rx_buf =
reinterpret_cast<uint64_t
>(rx_buf.data());
66 transfer.len = tx_buf.size();
67 transfer.speed_hz = speed_;
68 transfer.bits_per_word = 8;
72 if (ioctl(fd_, SPI_IOC_MESSAGE(1), &transfer) < 0) {
74 std::perror(
"SPI read failed");
91 std::array<uint8_t, 2> tx_buf = {{reg, value}};
92 struct spi_ioc_transfer transfer{};
93 transfer.tx_buf =
reinterpret_cast<uint64_t
>(tx_buf.data());
94 transfer.len = tx_buf.size();
95 transfer.speed_hz = speed_;
96 transfer.bits_per_word = 8;
100 if (ioctl(fd_, SPI_IOC_MESSAGE(1), &transfer) < 0) {
102 std::perror(
"SPI write failed");
107 void ReadRegisters(
Gpio* cs, uint8_t reg, uint8_t* buffer,
size_t length) {
111 std::vector<uint8_t> tx_buf(length + 1, 0);
112 std::vector<uint8_t> rx_buf(length + 1, 0);
113 tx_buf[0] = reg | 0x80;
115 struct spi_ioc_transfer transfer{};
116 transfer.tx_buf =
reinterpret_cast<uint64_t
>(tx_buf.data());
117 transfer.rx_buf =
reinterpret_cast<uint64_t
>(rx_buf.data());
118 transfer.len = tx_buf.size();
119 transfer.speed_hz = speed_;
120 transfer.bits_per_word = 8;
124 if (ioctl(fd_, SPI_IOC_MESSAGE(1), &transfer) < 0) {
126 std::perror(
"SPI multiple read failed");
130 std::memcpy(buffer, rx_buf.data() + 1, length);
133 int Fd()
const {
return fd_; }
135 uint32_t Speed()
const {
return speed_; }