#include #include #include #include #include #include #include #define SPI_DEVICE "/dev/spidev1.0" int main() { system("config-pin P2_25 spi"); system("config-pin P2_27 spi"); system("config-pin P2_29 spi_sclk"); system("config-pin P2_31 spi_cs"); system("echo out > /sys/class/gpio/gpio19/direction"); //CS pin int spi_fd; uint8_t tx_buffer[2] = {0x01, 0x02}; // Example data to send uint8_t rx_buffer[2] = {0}; // Buffer to store received data // Open SPI device spi_fd = open(SPI_DEVICE, O_RDWR); if (spi_fd < 0) { perror("Error opening SPI device"); return 1; } int gpio_fd; gpio_fd = open("/sys/class/gpio/gpio19/value", O_WRONLY); if (gpio_fd < 0) { perror("Error opening CS GPIO"); close(spi_fd); return 1; } // Pull CS pin high (inactive) write(gpio_fd, "1", 1); close(gpio_fd); // Configure SPI mode, speed, etc. // For example, set SPI mode to 0, maximum speed 1MHz uint8_t spi_mode = SPI_MODE_0; uint32_t spi_speed = 1000000; // 1MHz if (ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode) < 0 || ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed) < 0) { perror("Error setting SPI parameters"); close(spi_fd); return 1; } // Pull CS pin low to select the device gpio_fd = open("/sys/class/gpio/gpio19/value", O_WRONLY); if (gpio_fd < 0) { perror("Error opening CS GPIO"); close(spi_fd); return 1; } // Pull CS pin low (active) write(gpio_fd, "0", 1); close(gpio_fd); // Transfer data over SPI if (write(spi_fd, tx_buffer, sizeof(tx_buffer)) != sizeof(tx_buffer)) { perror("Error writing to SPI device"); close(spi_fd); return 1; } if (read(spi_fd, rx_buffer, sizeof(rx_buffer)) != sizeof(rx_buffer)) { perror("Error reading from SPI device"); close(spi_fd); return 1; } // Pull CS pin high to deselect the device gpio_fd = open("/sys/class/gpio/gpio19/value", O_WRONLY); if (gpio_fd < 0) { perror("Error opening CS GPIO"); close(spi_fd); return 1; } // Pull CS pin high (inactive) write(gpio_fd, "1", 1); close(gpio_fd); // Print received data printf("Received data: 0x%02X, 0x%02X\n", rx_buffer[0], rx_buffer[1]); // Close SPI device close(spi_fd); return 0; }