Ansteuerung der Hardware/Beispiele > SPI-Ansteuerung > Beispiel in C

Navigation:

 

Ansteuerung der Hardware/Beispiele > SPI-Ansteuerung >



Beispiel in C

Previous pageReturn to chapter overviewNext page

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <string.h>

 

#include <sys/ioctl.h>

#include <sys/types.h>

#include <sys/stat.h>

 

#include </opt/kernel-2.6.30_ecpu800/source/include/linux/types.h>

#include</opt/kernel-2.6.30_ecpu800/source/include/linux/spi/spidev.h>

 

 

static int verbose;

 

void spi_tx(int fd, unsigned char d0, unsigned char d1)

{

 struct spi_ioc_transfer xfer[2];

 unsigned char buf_tx[32],buf_rx[32];

 int status;

 

 memset(xfer, 0, sizeof xfer);

 

 // Send 2 Bytes

 buf_tx[0] = d0;

 buf_tx[1] = d1;

 

 xfer[0].tx_buf = (__u64) buf_tx;

 xfer[0].len = 2;

 xfer[0].rx_buf = (__u64) buf_rx;

 

 status = ioctl(fd, SPI_IOC_MESSAGE(1), xfer);

 if (status < 0) {

         perror("SPI_IOC_MESSAGE");

         return;

 }

 

 printf("Status=%d\n", status);

 printf("Tx-buffer = 0x%x, 0x%x\n", *buf_tx, *(buf_tx+1));

 printf("Rx-buffer = 0x%x, 0x%x\n", *buf_rx, *(buf_rx+1));

}

 

int main(int argc, char **argv)

{

 int             c;

 int             readcount = 0;

 int             msglen = 0;

 int             fd;

 const char      *name;

 

 name = "/dev/spidev1.0"        ;

 printf("Name = %s\n", name);

 

        fd = open(name, O_RDWR);

        if (fd < 0) {

                perror("open");

                return 1;

        }

 

 

 

 printf("Start\n");

 

 // Send Data to SPI

 spi_tx(fd, 4, 0xff);

 sleep(1);

 spi_tx(fd, 5, 0xff);

 sleep(1);

 spi_tx(fd, 4, 0x1);

 sleep(1);

 spi_tx(fd, 5, 0x1);

 sleep(1);

 

 close(fd);

 return 0;

}