2016年9月14日 星期三

[Raspberry] 在Raspberry Pi 2 使用SPI(一)

Enable SPI Kernel Module

ls /dev 會看到有 spidev0.0 spidev0.1



程式::

#include <cstdlib>

#include <stdio.h>

#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include <unistd.h>

#include <string.h>

using namespace std;

int spi_cs0_fd;

unsigned char spi_mode;
unsigned char spi_bitsPerWord;
unsigned int spi_speed;


int spiOpenPort()
{
    int *spi_cs_fd;
   
    int status_value=-1;
   
    spi_mode=SPI_MODE_0;
    spi_bitsPerWord=8;
    spi_speed=1000000;
   
    spi_cs_fd=&spi_cs0_fd;
   
    *spi_cs_fd=open("/dev/spidev0.0",O_RDWR);
   
    if(*spi_cs_fd<0)
    {
        printf("Open /dev/spidev0.0 failed\r\n");
        exit(1);
    }
   
    status_value=ioctl(*spi_cs_fd,SPI_IOC_WR_MODE,&spi_mode);
    if(status_value<0)
    {
        printf("W spi_mode failed\r\n");
        exit(1);
    }
   
    status_value=ioctl(*spi_cs_fd,SPI_IOC_RD_MODE,&spi_mode);
    if(status_value<0)
    {
        printf("RD spi_mode failed\r\n");
        exit(1);
    }
   
    status_value=ioctl(*spi_cs_fd,SPI_IOC_WR_BITS_PER_WORD,&spi_bitsPerWord);
    if(status_value<0)
    {
        printf("WR sp_bitsPerWord failed\r\n");
        exit(1);
    }
   
    status_value=ioctl(*spi_cs_fd,SPI_IOC_RD_BITS_PER_WORD,&spi_bitsPerWord);
    if(status_value<0)
    {
        printf("RD sp_bitsPerWord failed\r\n");
        exit(1);
    }
   
    status_value=ioctl(*spi_cs_fd,SPI_IOC_WR_MAX_SPEED_HZ,&spi_speed);
    if(status_value<0)
    {
        printf("WR spi_spped failed\r\n");
        exit(1);
    }
       
    status_value=ioctl(*spi_cs_fd,SPI_IOC_RD_MAX_SPEED_HZ,&spi_speed);
    if(status_value<0)
    {
        printf("RD spi_spped failed\r\n");
        exit(1);
    }
         
    return(status_value);   
}


int SpiWriteAndRead(unsigned char *data,int length)
{
    struct spi_ioc_transfer spi[length];
    int i=0;
    int retVal =-1;
    int *spi_cs_fd;
   
    spi_cs_fd=&spi_cs0_fd;
   
    for(i=0;i<length;i++)
    {
        memset(&spi[i],0,sizeof(spi[i]));
        spi[i].tx_buf=(unsigned long)(data+i);
        spi[i].rx_buf=(unsigned long)(data+i);
        spi[i].len=sizeof(*(data+i));
        spi[i].delay_usecs=0;
        spi[i].speed_hz=spi_speed;
        spi[i].bits_per_word=spi_bitsPerWord;
        spi[i].cs_change=0;
    }
   
    retVal=ioctl(*spi_cs_fd,SPI_IOC_MESSAGE(length),&spi);
   
    if(retVal<0)
    {
        printf("tran error \n\r");
        exit(1);
    }
    return retVal;  
}


int main(int argc, char** argv) {

    unsigned char buffer[100];
   
    for(int j=0;j<100;j++)buffer[j]=0x55;
   
    if(spiOpenPort()<0)
    {
        return -1;
    }

    SpiWriteAndRead(buffer,100);
   
    close(spi_cs0_fd);
   
    return 0;
}





 參考資料:

Using the SPI Interface
C library for Broadcom BCM 2835 as used in Raspberry Pi
Interfacing an SPI ADC(MCP3008) chip to Raspberry Pi using C++(spidev)




















沒有留言:

張貼留言