write code for spi communication using c/c++
时间: 2023-05-17 21:05:20 浏览: 145
Sure, here's an example code for SPI communication using C/C++:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#define SPI_DEVICE "/dev/spidev0.0"
#define SPI_MODE SPI_MODE_0
#define SPI_BITS_PER_WORD 8
#define SPI_SPEED_HZ 1000000
int spi_fd;
int spi_init()
{
int ret = 0;
spi_fd = open(SPI_DEVICE, O_RDWR);
if (spi_fd < 0) {
perror("open");
return -1;
}
uint8_t mode = SPI_MODE;
ret = ioctl(spi_fd, SPI_IOC_WR_MODE, &mode);
if (ret < 0) {
perror("ioctl");
return -1;
}
uint8_t bits_per_word = SPI_BITS_PER_WORD;
ret = ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &bits_per_word);
if (ret < 0) {
perror("ioctl");
return -1;
}
uint32_t speed_hz = SPI_SPEED_HZ;
ret = ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed_hz);
if (ret < 0) {
perror("ioctl");
return -1;
}
return 0;
}
int spi_transfer(uint8_t *tx_buf, uint8_t *rx_buf, size_t len)
{
struct spi_ioc_transfer transfer = {
.tx_buf = (unsigned long)tx_buf,
.rx_buf = (unsigned long)rx_buf,
.len = len,
.speed_hz = SPI_SPEED_HZ,
.bits_per_word = SPI_BITS_PER_WORD,
.delay_usecs = 0,
};
int ret = ioctl(spi_fd, SPI_IOC_MESSAGE(1), &transfer);
if (ret < 0) {
perror("ioctl");
return -1;
}
return 0;
}
int main()
{
int ret = spi_init();
if (ret < 0) {
printf("SPI initialization failed\n");
return -1;
}
uint8_t tx_buf[2] = {0x01, 0x02};
uint8_t rx_buf[2] = {0};
ret = spi_transfer(tx_buf, rx_buf, 2);
if (ret < 0) {
printf("SPI transfer failed\n");
return -1;
}
printf("Received data: 0x%02x 0x%02x\n", rx_buf[0], rx_buf[1]);
close(spi_fd);
return 0;
}
```
This code initializes the SPI device and performs a SPI transfer with a 2-byte transmit buffer and a 2-byte receive buffer. The received data is printed to the console.
阅读全文