20
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LinuxでSPI (spidev)を使う

Posted at

LinuxでSPIを使う方法を調べてみました。

言語はCで、デバイスドライバはspidevを使う想定です。

端子

SPIでは通常4本の端子を使う。

  • MOSI : Master Out Slave In
  • MISO : Master In Slave Out
  • SCLK : SPI clock
  • GND : GND

その他に以下の端子を使う場合がある

  • CS : ChipSelect
  • SYNC : 転送単位を表す信号。 8bit単位、16bit単位などが良く使われる。

API

デバイスのオープン

  • デバイスは /dev/spidev.0.0 などとなる。 数字の部分が変わる。
int fd;
fd = open("/dev/spidev0.0", O_RDWR);

SPIデータ読み書き用のAPI

  • ioctlを使う。
  • SPI_IOC_MESSAGE(N)を使う。Nは一度に転送するspi_ioc_transferの個数。
  • 読み書きの例
#define HOGE_SPI_SPEED_HZ    1000000
#define HOGE_SPI_DELAY_USECS 0
#define HOGE_SPI_BITS        8


uint8_t tx[3] = {1, 2, 3};
uint8_t rx[3] = {0, };
struct spi_ioc_transfer tr[1];

tr[0].tx_buf        = (unsigned long)tx;
tr[0].rx_buf        = (unsigned long)rx;
tr[0].len           = ARRAY_SIZE(tx);
tr[0].delay_usecs   = HOGE_SPI_DELAY_USECS;
tr[0].speed_hz      = HOGE_SPI_SPEED_HZ;
tr[0].bits_per_word = HOGE_SPI_BITS;
tr[0].cs_change     = 0;

ioctl(fd, SPI_IOC_MESSAGE(1), tr);

SPI設定用のAPI

  • ioctlを使う。
#include <linux/spi/spidev.h>
  • 設定用ioctlの説明
ioctl description
SPI_IOC_WR_MOD Read of SPI mode (SPI_MODE_0..SPI_MODE_3)
SPI_IOC_WR_MODE Write of SPI mode (SPI_MODE_0..SPI_MODE_3)
SPI_IOC_RD_LSB_FIRST Read SPI bit justification
SPI_IOC_WR_LSB_FIRST Write SPI bit justification
SPI_IOC_RD_BITS_PER_WORD Read SPI device word length (1..N)
SPI_IOC_WR_BITS_PER_WORD Write SPI device word length (1..N)
SPI_IOC_RD_MAX_SPEED_HZ Read SPI device default max speed hz
SPI_IOC_WR_MAX_SPEED_HZ Write SPI device default max speed hz

あとで実際に試した結果を追記予定。

参考

20
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?