树莓派SPI回环测试

文章目录

  • 1 准备工作
  • 2 基于bcm2835的测试代码

1 准备工作

  • 首先将树莓派的MISO,MOSI引脚用杜邦线短接。
  • 然后使能树莓派的SPI
    树莓派SPI回环测试_第1张图片
sudo raspi-config

树莓派SPI回环测试_第2张图片
树莓派SPI回环测试_第3张图片

  • 然后查看是否成功

树莓派SPI回环测试_第4张图片

2 基于bcm2835的测试代码

在这里插入图片描述

#include 
#include 
 
int main(int argc, char **argv)
{
    // If you call this, it will not actually access the GPIO
// Use for testing
//        bcm2835_set_debug(1);
 
    if (!bcm2835_init())
    {
      printf("bcm2835_init failed. Are you running as root??\n");
      return 1;
    }
 
    if (!bcm2835_spi_begin())
    {
      printf("bcm2835_spi_begin failed. Are you running as root??\n");
      return 1;
    }
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // The default
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);                   // The default
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);                      // The default
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);      // the default
    
    // Send a byte to the slave and simultaneously read a byte back from the slave
    // If you tie MISO to MOSI, you should read back what was sent
    uint8_t send_data = 0x23;
    uint8_t read_data = bcm2835_spi_transfer(send_data);
    printf("Sent to SPI: 0x%02X. Read back from SPI: 0x%02X.\n", send_data, read_data);
    if (send_data != read_data)
      printf("Do you have the loopback from MOSI to MISO connected?\n");
    bcm2835_spi_end();
    bcm2835_close();
    return 0;
}

  • 然后编译
gcc spi_test_loop.c -o test -l bcm2835

树莓派SPI回环测试_第5张图片
如果不是不加sudo,会出现上面第一个红框的提示。下面的红框说明回环测试成功。

  • 如果我们将MISO拔了,会出现下面的问题
    在这里插入图片描述

你可能感兴趣的:(Linux,LoRaWAN)