LoginSignup
4
8

More than 5 years have passed since last update.

Raspberry PiでSPI通信

Last updated at Posted at 2017-04-04

Raspberry PiでSPI通信する

 Raspberry Piで「wiringPiSPI」ライブラリを使ってSPI通信をするためのプログラムです。8bitのデータを4回送信するサンプルプログラムです。

環境

ハードウェア:Raspberry Pi 2
OS:Debian GNU/Linux 8
言語:C

ソースコード

//スレッド2 SPI通信処理
#include <wiringPiSPI.h>
#include <wiringPi.h>
#include <stdio.h>

//定数定義
#define SS_PORT 22                  //GPIO 22
#define SPI_CHANNEL 0                   //SPIチャンネル
#define MILLI_SEC 1000000               //ms

int main(void)
{
    int i;
    int buffSize = 4;
    int speed;                                      //通信速度(Hz)
    unsigned char spi_buff[buffSize];                      //送受信用バッファ
    struct timespec req;

    //sleep設定
    req.tv_sec = 0;
    req.tv_nsec = 1000 * MILLI_SEC;             //sleep時間msで設定

    //バッファ初期化
    for(i = 0; i < buffSize; i++){
        spi_buff[i] = 0x0;
    }

    //SPI通信速度設定
    speed = 10000000;                               //通信速度100kHz

    //SPIチャンネル初期化
    if((wiringPiSPISetup (SPI_CHANNEL, speed)) < 0){
        printf("wiringPiSPISetup error \n");
        return -1 ;
    }

    printf("Setup SPI...\n");

    //GPIO初期化
    if(wiringPiSetupGpio() == -1){
        printf("wiringPiSetupGpio error\n");
        return -1;
    }
    pinMode(SS_PORT, OUTPUT);                       //22pinを出力に設定
    digitalWrite(SS_PORT, 1);                       //SS信号初期化

    printf("Start SPI...\n");

    //通信処理
    while(1){
        //送信用データをバッファにセット
        spi_buff[0] = 0x01;     //送信テスト用データ
        spi_buff[1] = 0x02;     //送信テスト用データ
        spi_buff[2] = 0x03;     //送信テスト用データ
        spi_buff[3] = 0x04;     //送信テスト用データ

        //SPI通信実行
        digitalWrite(SS_PORT, 0);                   //SS信号をLOW出力にして通信開始
        wiringPiSPIDataRW(SPI_CHANNEL, spi_buff, 4);             //データ送受信
        digitalWrite(SS_PORT, 1);                   //SS信号をHIGH出力にして通信終了

        //インターバル
        nanosleep(&req, NULL);
    }

    return 0;
}
4
8
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
4
8