Help us understand the problem. What is going on with this article?

LinuxでSPI (spidev)を使う

More than 3 years have passed since last update.

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

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

参考

eggman
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした