pihwm
A lightweight C library for Raspberry Pi hardware modules.
 All Data Structures Files Functions Groups Pages
pi_spi.c
Go to the documentation of this file.
1 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <stdint.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <sys/ioctl.h>
34 #include <linux/types.h>
35 #include <linux/spi/spidev.h>
36 
37 #include "pihwm.h"
38 #include "pi_spi.h"
39 
52 int
53 spi_init (uint8_t channel)
54 {
55  int fd;
56 
57  if ( check_kernel_module("spidev") < 0 )
58  {
59  debug ("[%s] Kernel module \"spidev\" not loaded.\n", __func__);
60  return -1;
61  }
62 
63  if ( check_kernel_module("spi_bcm2708") < 0 )
64  {
65  debug ("[%s] Kernel module \"spi_bcm2708\" not loaded.\n", __func__);
66  return -1;
67  }
68 
69  if ( channel == 0 )
70  {
71  fd = open("/dev/spidev0.0", O_RDWR);
72  }
73  else if ( channel == 1 )
74  {
75  fd = open("/dev/spidev0.1", O_RDWR);
76  }
77  else
78  {
79  debug ("[%s] Invalid SPI channel: %d\n", __func__, channel);
80  fd = -1;
81  }
82 
83  if ( fd < 0 )
84  {
85  debug ("[%s] Can't open SPI device.\n", __func__);
86  return -1;
87  }
88  else
89  {
90  // device open, config default values
91  if ( spi_config_default(fd) )
92  {
93  return fd;
94  }
95  else
96  {
97  debug ("[%s] Can't set default SPI config.\n", __func__);
98  return -1;
99  }
100  }
101 }
102 
103 
115 int
116 spi_config(int fd, uint8_t mode, uint8_t bits, uint32_t speed, uint16_t delay)
117 {
118  int ret;
119 
120  //spi mode
121  ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
122  if ( ret == -1 )
123  {
124  debug ("[%s] Can't set SPI mode.\n", __func__);
125  return -1;
126  }
127 
128  // bits per word
129  ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
130  if ( ret == -1 )
131  {
132  debug ("[%s] Can't set SPI bits per word.\n", __func__);
133  return -1;
134  }
135 
136  // max speed hz
137  ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
138  if ( ret == -1 )
139  {
140  debug ("[%s] Can't set SPI max speed.\n", __func__);
141  return -1;
142  }
143 
144  return 1;
145 }
146 
154 int
156 {
157  int ret;
158 
159  ret = spi_config (fd, SPI_DEFAULT_MODE, SPI_DEFAULT_BPW, SPI_DEFAULT_SPEED, SPI_DEFAULT_DELAY);
160 
161  return ret;
162 }
163 
174 int
175 spi_transfer (int fd, uint8_t txbuf[], uint8_t rxbuf[], uint8_t len)
176 {
177  int ret;
178 
179  struct spi_ioc_transfer transfer = {
180  .tx_buf = (unsigned long)txbuf,
181  .rx_buf = (unsigned long)rxbuf,
182  .len = len,
183  .delay_usecs = SPI_DEFAULT_DELAY,
184  .speed_hz = SPI_DEFAULT_SPEED,
185  .bits_per_word = SPI_DEFAULT_BPW,
186  };
187 
188  ret = ioctl(fd, SPI_IOC_MESSAGE(1), &transfer);
189  if ( ret < 1 )
190  {
191  debug ("[%s] Can't send SPI message.\n", __func__);
192  return -1;
193  }
194  else
195  {
196  return 1;
197  }
198 }
199