こちらと同様のことを、RaspberryPi 4 で行いました。
SPI を有効にする
sudo raspi-config
テスト環境の構築
GPIO9 と GPIO10 を接続する
ライブラリーのインストール
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.75.tar.gz
tar xvfz bcm2835-1.75.tar.gz
cd bcm2835-1.75
./configure
make
sudo make install
プログラム
spi.c
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (!bcm2835_init())
return 1;
bcm2835_spi_begin();
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
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;
}
'''
```text:Makefile
spi: spi.c
gcc -o spi spi.c -l bcm2835
clean:
rm -f spi
コンパイル
make
実行
$ sudo ./spi
Sent to SPI: 0x23. Read back from SPI: 0x23.
少し改造したプログラム
spi.c
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (!bcm2835_init())
return 1;
bcm2835_spi_begin();
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
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");
send_data = 0x51;
read_data = bcm2835_spi_transfer(send_data);
printf("Sent to SPI: 0x%02X. Read back from SPI: 0x%02X.\n", send_data, read_data);
bcm2835_spi_end();
bcm2835_close();
return 0;
}
実行結果
$ sudo ./spi
Sent to SPI: 0x23. Read back from SPI: 0x23.
Sent to SPI: 0x51. Read back from SPI: 0x51.