chiark / gitweb /
b8e381a27cd819f809f69974473c165e57a8986a
[wiringPi.git] / wiringPi / wiringPi.c
1 /*
2  * wiringPi:
3  *      Arduino compatable (ish) Wiring library for the Raspberry Pi
4  *      Copyright (c) 2012 Gordon Henderson
5  *      Additional code for pwmSetClock by Chris Hall <chris@kchall.plus.com>
6  *
7  *      Thanks to code samples from Gert Jan van Loo and the
8  *      BCM2835 ARM Peripherals manual, however it's missing
9  *      the clock section /grr/mutter/
10  ***********************************************************************
11  * This file is part of wiringPi:
12  *      https://projects.drogon.net/raspberry-pi/wiringpi/
13  *
14  *    wiringPi is free software: you can redistribute it and/or modify
15  *    it under the terms of the GNU Lesser General Public License as
16  *    published by the Free Software Foundation, either version 3 of the
17  *    License, or (at your option) any later version.
18  *
19  *    wiringPi is distributed in the hope that it will be useful,
20  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *    GNU Lesser General Public License for more details.
23  *
24  *    You should have received a copy of the GNU Lesser General Public
25  *    License along with wiringPi.
26  *    If not, see <http://www.gnu.org/licenses/>.
27  ***********************************************************************
28  */
29
30 // Revisions:
31 //      19 Jul 2012:
32 //              Moved to the LGPL
33 //              Added an abstraction layer to the main routines to save a tiny
34 //              bit of run-time and make the clode a little cleaner (if a little
35 //              larger)
36 //              Added waitForInterrupt code
37 //              Added piHiPri code
38 //
39 //       9 Jul 2012:
40 //              Added in support to use the /sys/class/gpio interface.
41 //       2 Jul 2012:
42 //              Fixed a few more bugs to do with range-checking when in GPIO mode.
43 //      11 Jun 2012:
44 //              Fixed some typos.
45 //              Added c++ support for the .h file
46 //              Added a new function to allow for using my "pin" numbers, or native
47 //                      GPIO pin numbers.
48 //              Removed my busy-loop delay and replaced it with a call to delayMicroseconds
49 //
50 //      02 May 2012:
51 //              Added in the 2 UART pins
52 //              Change maxPins to numPins to more accurately reflect purpose
53
54
55 #include <stdio.h>
56 #include <stdarg.h>
57 #include <stdint.h>
58 #include <stdlib.h>
59 #include <ctype.h>
60 #include <poll.h>
61 #include <unistd.h>
62 #include <errno.h>
63 #include <string.h>
64 #include <time.h>
65 #include <fcntl.h>
66 #include <pthread.h>
67 #include <sys/time.h>
68 #include <sys/mman.h>
69 #include <sys/stat.h>
70 #include <sys/wait.h>
71 #include <sys/ioctl.h>
72
73 #include "wiringPi.h"
74
75 #ifndef TRUE
76 #define TRUE    (1==1)
77 #define FALSE   (1==2)
78 #endif
79
80 // Environment Variables
81
82 #define ENV_DEBUG       "WIRINGPI_DEBUG"
83 #define ENV_CODES       "WIRINGPI_CODES"
84
85
86 // Mask for the bottom 64 pins which belong to the Raspberry Pi
87 //      The others are available for the other devices
88
89 #define PI_GPIO_MASK    (0xFFFFFFC0)
90
91 static struct wiringPiNodeStruct *wiringPiNodes = NULL ;
92
93 // BCM Magic
94
95 #define BCM_PASSWORD            0x5A000000
96
97
98 // The BCM2835 has 54 GPIO pins.
99 //      BCM2835 data sheet, Page 90 onwards.
100 //      There are 6 control registers, each control the functions of a block
101 //      of 10 pins.
102 //      Each control register has 10 sets of 3 bits per GPIO pin - the ALT values
103 //
104 //      000 = GPIO Pin X is an input
105 //      001 = GPIO Pin X is an output
106 //      100 = GPIO Pin X takes alternate function 0
107 //      101 = GPIO Pin X takes alternate function 1
108 //      110 = GPIO Pin X takes alternate function 2
109 //      111 = GPIO Pin X takes alternate function 3
110 //      011 = GPIO Pin X takes alternate function 4
111 //      010 = GPIO Pin X takes alternate function 5
112 //
113 // So the 3 bits for port X are:
114 //      X / 10 + ((X % 10) * 3)
115
116 // Port function select bits
117
118 #define FSEL_INPT               0b000
119 #define FSEL_OUTP               0b001
120 #define FSEL_ALT0               0b100
121 #define FSEL_ALT0               0b100
122 #define FSEL_ALT1               0b101
123 #define FSEL_ALT2               0b110
124 #define FSEL_ALT3               0b111
125 #define FSEL_ALT4               0b011
126 #define FSEL_ALT5               0b010
127
128 // Access from ARM Running Linux
129 //      Taken from Gert/Doms code. Some of this is not in the manual
130 //      that I can find )-:
131
132 #define BCM2708_PERI_BASE                            0x20000000
133 #define GPIO_PADS               (BCM2708_PERI_BASE + 0x00100000)
134 #define CLOCK_BASE              (BCM2708_PERI_BASE + 0x00101000)
135 #define GPIO_BASE               (BCM2708_PERI_BASE + 0x00200000)
136 #define GPIO_TIMER              (BCM2708_PERI_BASE + 0x0000B000)
137 #define GPIO_PWM                (BCM2708_PERI_BASE + 0x0020C000)
138
139 #define PAGE_SIZE               (4*1024)
140 #define BLOCK_SIZE              (4*1024)
141
142 // PWM
143 //      Word offsets into the PWM control region
144
145 #define PWM_CONTROL 0
146 #define PWM_STATUS  1
147 #define PWM0_RANGE  4
148 #define PWM0_DATA   5
149 #define PWM1_RANGE  8
150 #define PWM1_DATA   9
151
152 //      Clock regsiter offsets
153
154 #define PWMCLK_CNTL     40
155 #define PWMCLK_DIV      41
156
157 #define PWM0_MS_MODE    0x0080  // Run in MS mode
158 #define PWM0_USEFIFO    0x0020  // Data from FIFO
159 #define PWM0_REVPOLAR   0x0010  // Reverse polarity
160 #define PWM0_OFFSTATE   0x0008  // Ouput Off state
161 #define PWM0_REPEATFF   0x0004  // Repeat last value if FIFO empty
162 #define PWM0_SERIAL     0x0002  // Run in serial mode
163 #define PWM0_ENABLE     0x0001  // Channel Enable
164
165 #define PWM1_MS_MODE    0x8000  // Run in MS mode
166 #define PWM1_USEFIFO    0x2000  // Data from FIFO
167 #define PWM1_REVPOLAR   0x1000  // Reverse polarity
168 #define PWM1_OFFSTATE   0x0800  // Ouput Off state
169 #define PWM1_REPEATFF   0x0400  // Repeat last value if FIFO empty
170 #define PWM1_SERIAL     0x0200  // Run in serial mode
171 #define PWM1_ENABLE     0x0100  // Channel Enable
172
173 // Timer
174 //      Word offsets
175
176 #define TIMER_LOAD      (0x400 >> 2)
177 #define TIMER_VALUE     (0x404 >> 2)
178 #define TIMER_CONTROL   (0x408 >> 2)
179 #define TIMER_IRQ_CLR   (0x40C >> 2)
180 #define TIMER_IRQ_RAW   (0x410 >> 2)
181 #define TIMER_IRQ_MASK  (0x414 >> 2)
182 #define TIMER_RELOAD    (0x418 >> 2)
183 #define TIMER_PRE_DIV   (0x41C >> 2)
184 #define TIMER_COUNTER   (0x420 >> 2)
185
186 // Locals to hold pointers to the hardware
187
188 static volatile uint32_t *gpio ;
189 static volatile uint32_t *pwm ;
190 static volatile uint32_t *clk ;
191 static volatile uint32_t *pads ;
192
193 #ifdef  USE_TIMER
194 static volatile uint32_t *timer ;
195 static volatile uint32_t *timerIrqRaw ;
196 #endif
197
198 // Time for easy calculations
199
200 static uint64_t epochMilli, epochMicro ;
201
202 // Misc
203
204 static int wiringPiMode = WPI_MODE_UNINITIALISED ;
205 static volatile int    pinPass = -1 ;
206 static pthread_mutex_t pinMutex ;
207
208 // Debugging & Return codes
209
210 int wiringPiDebug       = FALSE ;
211 int wiringPiReturnCodes = FALSE ;
212
213 // sysFds:
214 //      Map a file descriptor from the /sys/class/gpio/gpioX/value
215
216 static int sysFds [64] ;
217
218 // ISR Data
219
220 static void (*isrFunctions [64])(void) ;
221
222
223 // Doing it the Arduino way with lookup tables...
224 //      Yes, it's probably more innefficient than all the bit-twidling, but it
225 //      does tend to make it all a bit clearer. At least to me!
226
227 // pinToGpio:
228 //      Take a Wiring pin (0 through X) and re-map it to the BCM_GPIO pin
229 //      Cope for 2 different board revisions here.
230
231 static int *pinToGpio ;
232
233 static int pinToGpioR1 [64] =
234 {
235   17, 18, 21, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7:   wpi  0 -  7
236    0,  1,                               // I2C  - SDA0, SCL0                            wpi  8 -  9
237    8,  7,                               // SPI  - CE1, CE0                              wpi 10 - 11
238   10,  9, 11,                           // SPI  - MOSI, MISO, SCLK                      wpi 12 - 14
239   14, 15,                               // UART - Tx, Rx                                wpi 15 - 16
240
241 // Padding:
242
243       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 31
244   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
245   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
246 } ;
247
248 static int pinToGpioR2 [64] =
249 {
250   17, 18, 27, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7:   wpi  0 -  7
251    2,  3,                               // I2C  - SDA0, SCL0                            wpi  8 -  9
252    8,  7,                               // SPI  - CE1, CE0                              wpi 10 - 11
253   10,  9, 11,                           // SPI  - MOSI, MISO, SCLK                      wpi 12 - 14
254   14, 15,                               // UART - Tx, Rx                                wpi 15 - 16
255   28, 29, 30, 31,                       // New GPIOs 8 though 11                        wpi 17 - 20
256
257 // Padding:
258
259                       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 31
260   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
261   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
262 } ;
263
264
265 // physToGpio:
266 //      Take a physical pin (1 through 26) and re-map it to the BCM_GPIO pin
267 //      Cope for 2 different board revisions here.
268
269 static int *physToGpio ;
270
271 static int physToGpioR1 [64] =
272 {
273   -1,           // 0
274   -1, -1,       // 1, 2
275    0, -1,
276    1, -1,
277    4, 14,
278   -1, 15,
279   17, 18,
280   21, -1,
281   22, 23,
282   -1, 24,
283   10, -1,
284    9, 25,
285   11,  8,
286   -1,  7,       // 25, 26
287
288 // Padding:
289
290                                               -1, -1, -1, -1, -1,       // ... 31
291   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
292   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
293 } ;
294
295 static int physToGpioR2 [64] =
296 {
297   -1,           // 0
298   -1, -1,       // 1, 2
299    2, -1,
300    3, -1,
301    4, 14,
302   -1, 15,
303   17, 18,
304   27, -1,
305   22, 23,
306   -1, 24,
307   10, -1,
308    9, 25,
309   11,  8,
310   -1,  7,       // 25, 26
311
312 // Padding:
313
314                                               -1, -1, -1, -1, -1,       // ... 31
315   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
316   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
317 } ;
318
319
320 // gpioToGPFSEL:
321 //      Map a BCM_GPIO pin to it's Function Selection
322 //      control port. (GPFSEL 0-5)
323 //      Groups of 10 - 3 bits per Function - 30 bits per port
324
325 static uint8_t gpioToGPFSEL [] =
326 {
327   0,0,0,0,0,0,0,0,0,0,
328   1,1,1,1,1,1,1,1,1,1,
329   2,2,2,2,2,2,2,2,2,2,
330   3,3,3,3,3,3,3,3,3,3,
331   4,4,4,4,4,4,4,4,4,4,
332   5,5,5,5,5,5,5,5,5,5,
333 } ;
334
335
336 // gpioToShift
337 //      Define the shift up for the 3 bits per pin in each GPFSEL port
338
339 static uint8_t gpioToShift [] =
340 {
341   0,3,6,9,12,15,18,21,24,27,
342   0,3,6,9,12,15,18,21,24,27,
343   0,3,6,9,12,15,18,21,24,27,
344   0,3,6,9,12,15,18,21,24,27,
345   0,3,6,9,12,15,18,21,24,27,
346 } ;
347
348
349 // gpioToGPSET:
350 //      (Word) offset to the GPIO Set registers for each GPIO pin
351
352 static uint8_t gpioToGPSET [] =
353 {
354    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
355    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
356 } ;
357
358 // gpioToGPCLR:
359 //      (Word) offset to the GPIO Clear registers for each GPIO pin
360
361 static uint8_t gpioToGPCLR [] =
362 {
363   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
364   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
365 } ;
366
367
368 // gpioToGPLEV:
369 //      (Word) offset to the GPIO Input level registers for each GPIO pin
370
371 static uint8_t gpioToGPLEV [] =
372 {
373   13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
374   14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
375 } ;
376
377
378 #ifdef notYetReady
379 // gpioToEDS
380 //      (Word) offset to the Event Detect Status
381
382 static uint8_t gpioToEDS [] =
383 {
384   16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
385   17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
386 } ;
387
388 // gpioToREN
389 //      (Word) offset to the Rising edgde ENable register
390
391 static uint8_t gpioToREN [] =
392 {
393   19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
394   20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
395 } ;
396
397 // gpioToFEN
398 //      (Word) offset to the Falling edgde ENable register
399
400 static uint8_t gpioToFEN [] =
401 {
402   22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,
403   23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,
404 } ;
405 #endif
406
407
408 // GPPUD:
409 //      GPIO Pin pull up/down register
410
411 #define GPPUD   37
412
413 // gpioToPUDCLK
414 //      (Word) offset to the Pull Up Down Clock regsiter
415
416 static uint8_t gpioToPUDCLK [] =
417 {
418   38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,
419   39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,
420 } ;
421
422
423 // gpioToPwmALT
424 //      the ALT value to put a GPIO pin into PWM mode
425
426 static uint8_t gpioToPwmALT [] =
427 {
428           0,         0,         0,         0,         0,         0,         0,         0,       //  0 ->  7
429           0,         0,         0,         0, FSEL_ALT0, FSEL_ALT0,         0,         0,       //  8 -> 15
430           0,         0, FSEL_ALT5, FSEL_ALT5,         0,         0,         0,         0,       // 16 -> 23
431           0,         0,         0,         0,         0,         0,         0,         0,       // 24 -> 31
432           0,         0,         0,         0,         0,         0,         0,         0,       // 32 -> 39
433   FSEL_ALT0, FSEL_ALT0,         0,         0,         0, FSEL_ALT0,         0,         0,       // 40 -> 47
434           0,         0,         0,         0,         0,         0,         0,         0,       // 48 -> 55
435           0,         0,         0,         0,         0,         0,         0,         0,       // 56 -> 63
436 } ;
437
438
439 // gpioToPwmPort
440 //      The port value to put a GPIO pin into PWM mode
441
442 static uint8_t gpioToPwmPort [] =
443 {
444           0,         0,         0,         0,         0,         0,         0,         0,       //  0 ->  7
445           0,         0,         0,         0, PWM0_DATA, PWM1_DATA,         0,         0,       //  8 -> 15
446           0,         0, PWM0_DATA, PWM1_DATA,         0,         0,         0,         0,       // 16 -> 23
447           0,         0,         0,         0,         0,         0,         0,         0,       // 24 -> 31
448           0,         0,         0,         0,         0,         0,         0,         0,       // 32 -> 39
449   PWM0_DATA, PWM1_DATA,         0,         0,         0, PWM1_DATA,         0,         0,       // 40 -> 47
450           0,         0,         0,         0,         0,         0,         0,         0,       // 48 -> 55
451           0,         0,         0,         0,         0,         0,         0,         0,       // 56 -> 63
452
453 } ;
454
455 // gpioToGpClkALT:
456 //      ALT value to put a GPIO pin into GP Clock mode.
457 //      On the Pi we can really only use BCM_GPIO_4 and BCM_GPIO_21
458 //      for clocks 0 and 1 respectively, however I'll include the full
459 //      list for completeness - maybe one day...
460
461 #define GPIO_CLOCK_SOURCE       1
462
463 // gpioToGpClkALT0:
464
465 static uint8_t gpioToGpClkALT0 [] =
466 {
467           0,         0,         0,         0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0,         0,       //  0 ->  7
468           0,         0,         0,         0,         0,         0,         0,         0,       //  8 -> 15
469           0,         0,         0,         0, FSEL_ALT5, FSEL_ALT5,         0,         0,       // 16 -> 23
470           0,         0,         0,         0,         0,         0,         0,         0,       // 24 -> 31
471   FSEL_ALT0,         0, FSEL_ALT0,         0,         0,         0,         0,         0,       // 32 -> 39
472           0,         0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0,         0,         0,         0,       // 40 -> 47
473           0,         0,         0,         0,         0,         0,         0,         0,       // 48 -> 55
474           0,         0,         0,         0,         0,         0,         0,         0,       // 56 -> 63
475 } ;
476
477 // gpioToClk:
478 //      (word) Offsets to the clock Control and Divisor register
479
480 static uint8_t gpioToClkCon [] =
481 {
482          -1,        -1,        -1,        -1,        28,        30,        32,        -1,       //  0 ->  7
483          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       //  8 -> 15
484          -1,        -1,        -1,        -1,        28,        30,        -1,        -1,       // 16 -> 23
485          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 24 -> 31
486          28,        -1,        28,        -1,        -1,        -1,        -1,        -1,       // 32 -> 39
487          -1,        -1,        28,        30,        28,        -1,        -1,        -1,       // 40 -> 47
488          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 48 -> 55
489          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 56 -> 63
490 } ;
491
492 static uint8_t gpioToClkDiv [] =
493 {
494          -1,        -1,        -1,        -1,        29,        31,        33,        -1,       //  0 ->  7
495          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       //  8 -> 15
496          -1,        -1,        -1,        -1,        29,        31,        -1,        -1,       // 16 -> 23
497          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 24 -> 31
498          29,        -1,        29,        -1,        -1,        -1,        -1,        -1,       // 32 -> 39
499          -1,        -1,        29,        31,        29,        -1,        -1,        -1,       // 40 -> 47
500          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 48 -> 55
501          -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,       // 56 -> 63
502 } ;
503
504
505 /*
506  * Functions
507  *********************************************************************************
508  */
509
510
511 /*
512  * wiringPiFailure:
513  *      Fail. Or not.
514  *********************************************************************************
515  */
516
517 int wiringPiFailure (int fatal, const char *message, ...)
518 {
519   va_list argp ;
520   char buffer [1024] ;
521
522   if (!fatal && wiringPiReturnCodes)
523     return -1 ;
524
525   va_start (argp, message) ;
526     vsnprintf (buffer, 1023, message, argp) ;
527   va_end (argp) ;
528
529   fprintf (stderr, "%s", buffer) ;
530   exit (EXIT_FAILURE) ;
531
532   return 0 ;
533 }
534
535
536 /*
537  * piBoardRev:
538  *      Return a number representing the hardware revision of the board.
539  *      Revision is currently 1 or 2.
540  *
541  *      Much confusion here )-:
542  *      Seems there are some boards with 0000 in them (mistake in manufacture)
543  *      and some board with 0005 in them (another mistake in manufacture?)
544  *      So the distinction between boards that I can see is:
545  *      0000 - Error
546  *      0001 - Not used
547  *      0002 - Rev 1
548  *      0003 - Rev 1
549  *      0004 - Rev 2 (Early reports?
550  *      0005 - Rev 2 (but error?)
551  *      0006 - Rev 2
552  *      0008 - Rev 2 - Model A
553  *      000e - Rev 2 + 512MB
554  *      000f - Rev 2 + 512MB
555  *
556  *      A small thorn is the olde style overvolting - that will add in
557  *              1000000
558  *
559  *********************************************************************************
560  */
561
562 static void piBoardRevOops (const char *why)
563 {
564   fprintf (stderr, "piBoardRev: Unable to determine board revision from /proc/cpuinfo\n") ;
565   fprintf (stderr, " -> %s\n", why) ;
566   fprintf (stderr, " ->  You may want to check:\n") ;
567   fprintf (stderr, " ->  http://www.raspberrypi.org/phpBB3/viewtopic.php?p=184410#p184410\n") ;
568   exit (EXIT_FAILURE) ;
569 }
570
571 int piBoardRev (void)
572 {
573   FILE *cpuFd ;
574   char line [120] ;
575   char *c, lastChar ;
576   static int  boardRev = -1 ;
577
578   if (boardRev != -1)   // No point checking twice
579     return boardRev ;
580
581   if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
582     piBoardRevOops ("Unable to open /proc/cpuinfo") ;
583
584   while (fgets (line, 120, cpuFd) != NULL)
585     if (strncmp (line, "Revision", 8) == 0)
586       break ;
587
588   fclose (cpuFd) ;
589
590   if (strncmp (line, "Revision", 8) != 0)
591     piBoardRevOops ("No \"Revision\" line") ;
592
593   for (c = &line [strlen (line) - 1] ; (*c == '\n') || (*c == '\r') ; --c)
594     *c = 0 ;
595   
596   if (wiringPiDebug)
597     printf ("piboardRev: Revision string: %s\n", line) ;
598
599   for (c = line ; *c ; ++c)
600     if (isdigit (*c))
601       break ;
602
603   if (!isdigit (*c))
604     piBoardRevOops ("No numeric revision string") ;
605
606 // If you have overvolted the Pi, then it appears that the revision
607 //      has 100000 added to it!
608
609   if (wiringPiDebug)
610     if (strlen (c) != 4)
611       printf ("piboardRev: This Pi has/is overvolted!\n") ;
612
613   lastChar = line [strlen (line) - 1] ;
614
615   if (wiringPiDebug)
616     printf ("piboardRev: lastChar is: '%c' (%d, 0x%02X)\n", lastChar, lastChar, lastChar) ;
617
618   /**/ if ((lastChar == '2') || (lastChar == '3'))
619     boardRev = 1 ;
620   else
621     boardRev = 2 ;
622
623   if (wiringPiDebug)
624     printf ("piBoardRev: Returning revision: %d\n", boardRev) ;
625
626   return boardRev ;
627 }
628
629
630 /*
631  * wpiPinToGpio:
632  *      Translate a wiringPi Pin number to native GPIO pin number.
633  *      Provided for external support.
634  *********************************************************************************
635  */
636
637 int wpiPinToGpio (int wpiPin)
638 {
639   return pinToGpio [wpiPin & 63] ;
640 }
641
642
643 /*
644  * physPinToGpio:
645  *      Translate a physical Pin number to native GPIO pin number.
646  *      Provided for external support.
647  *********************************************************************************
648  */
649
650 int physPinToGpio (int physPin)
651 {
652   return physToGpio [physPin & 63] ;
653 }
654
655
656 /*
657  * setPadDrive:
658  *      Set the PAD driver value
659  *********************************************************************************
660  */
661
662 void setPadDrive (int group, int value)
663 {
664   uint32_t wrVal ;
665
666   if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
667   {
668     if ((group < 0) || (group > 2))
669       return ;
670
671     wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
672     *(pads + group + 11) = wrVal ;
673
674     if (wiringPiDebug)
675     {
676       printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
677       printf ("Read : %08X\n", *(pads + group + 11)) ;
678     }
679   }
680 }
681
682
683 /*
684  * getAlt:
685  *      Returns the ALT bits for a given port. Only really of-use
686  *      for the gpio readall command (I think)
687  *********************************************************************************
688  */
689
690 int getAlt (int pin)
691 {
692   int fSel, shift, alt ;
693
694   pin &= 63 ;
695
696   /**/ if (wiringPiMode == WPI_MODE_PINS)
697     pin = pinToGpio [pin] ;
698   else if (wiringPiMode == WPI_MODE_PHYS)
699     pin = physToGpio [pin] ;
700   else if (wiringPiMode != WPI_MODE_GPIO)
701     return 0 ;
702
703   fSel    = gpioToGPFSEL [pin] ;
704   shift   = gpioToShift  [pin] ;
705
706   alt = (*(gpio + fSel) >> shift) & 7 ;
707
708   return alt ;
709 }
710
711
712 /*
713  * pwmSetMode:
714  *      Select the native "balanced" mode, or standard mark:space mode
715  *********************************************************************************
716  */
717
718 void pwmSetMode (int mode)
719 {
720   if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
721   {
722     if (mode == PWM_MODE_MS)
723       *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
724     else
725       *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
726   }
727 }
728
729
730 /*
731  * pwmSetRange:
732  *      Set the PWM range register. We set both range registers to the same
733  *      value. If you want different in your own code, then write your own.
734  *********************************************************************************
735  */
736
737 void pwmSetRange (unsigned int range)
738 {
739   if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
740   {
741     *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
742     *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
743   }
744 }
745
746
747 /*
748  * pwmSetClock:
749  *      Set/Change the PWM clock. Originally my code, but changed
750  *      (for the better!) by Chris Hall, <chris@kchall.plus.com>
751  *      after further study of the manual and testing with a 'scope
752  *********************************************************************************
753  */
754
755 void pwmSetClock (int divisor)
756 {
757   uint32_t pwm_control ;
758   divisor &= 4095 ;
759
760   if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
761   {
762     if (wiringPiDebug)
763       printf ("Setting to: %d. Current: 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
764
765     pwm_control = *(pwm + PWM_CONTROL) ;                // preserve PWM_CONTROL
766
767 // We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
768 // stays high.
769
770     *(pwm + PWM_CONTROL) = 0 ;                          // Stop PWM
771
772 // Stop PWM clock before changing divisor. The delay after this does need to
773 // this big (95uS occasionally fails, 100uS OK), it's almost as though the BUSY
774 // flag is not working properly in balanced mode. Without the delay when DIV is
775 // adjusted the clock sometimes switches to very slow, once slow further DIV
776 // adjustments do nothing and it's difficult to get out of this mode.
777
778     *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ;        // Stop PWM Clock
779       delayMicroseconds (110) ;                 // prevents clock going sloooow
780
781     while ((*(clk + PWMCLK_CNTL) & 0x80) != 0)  // Wait for clock to be !BUSY
782       delayMicroseconds (1) ;
783
784     *(clk + PWMCLK_DIV)  = BCM_PASSWORD | (divisor << 12) ;
785
786     *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ;        // Start PWM clock
787     *(pwm + PWM_CONTROL) = pwm_control ;                // restore PWM_CONTROL
788
789     if (wiringPiDebug)
790       printf ("Set     to: %d. Now    : 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
791   }
792 }
793
794
795 /*
796  * gpioClockSet:
797  *      Set the freuency on a GPIO clock pin
798  *********************************************************************************
799  */
800
801 void gpioClockSet (int pin, int freq)
802 {
803   int divi, divr, divf ;
804
805   pin &= 63 ;
806
807   /**/ if (wiringPiMode == WPI_MODE_PINS)
808     pin = pinToGpio [pin] ;
809   else if (wiringPiMode == WPI_MODE_PHYS)
810     pin = physToGpio [pin] ;
811   else if (wiringPiMode != WPI_MODE_GPIO)
812     return ;
813   
814   divi = 19200000 / freq ;
815   divr = 19200000 % freq ;
816   divf = (int)((double)divr * 4096.0 / 19200000.0) ;
817
818   if (divi > 4095)
819     divi = 4095 ;
820
821   *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | GPIO_CLOCK_SOURCE ;              // Stop GPIO Clock
822   while ((*(clk + gpioToClkCon [pin]) & 0x80) != 0)                             // ... and wait
823     ;
824
825   *(clk + gpioToClkDiv [pin]) = BCM_PASSWORD | (divi << 12) | divf ;            // Set dividers
826   *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | 0x10 | GPIO_CLOCK_SOURCE ;       // Start Clock
827 }
828
829
830 /*
831  * wiringPiFindNode:
832  *      Locate our device node
833  *********************************************************************************
834  */
835
836 static struct wiringPiNodeStruct *wiringPiFindNode (int pin)
837 {
838   struct wiringPiNodeStruct *node = wiringPiNodes ;
839
840   while (node != NULL)
841     if ((pin >= node->pinBase) && (pin <= node->pinMax))
842       return node ;
843     else
844       node = node->next ;
845
846   return NULL ;
847 }
848
849
850 /*
851  * wiringPiNewNode:
852  *      Create a new GPIO node into the wiringPi handling system
853  *********************************************************************************
854  */
855
856 static void pinModeDummy             (struct wiringPiNodeStruct *node, int pin, int mode)  { return ; }
857 static void pullUpDnControlDummy     (struct wiringPiNodeStruct *node, int pin, int pud)   { return ; }
858 static int  digitalReadDummy         (struct wiringPiNodeStruct *node, int pin)            { return LOW ; }
859 static void digitalWriteDummy        (struct wiringPiNodeStruct *node, int pin, int value) { return ; }
860 static void pwmWriteDummy            (struct wiringPiNodeStruct *node, int pin, int value) { return ; }
861 static int  analogReadDummy          (struct wiringPiNodeStruct *node, int pin)            { return 0 ; }
862 static void analogWriteDummy         (struct wiringPiNodeStruct *node, int pin, int value) { return ; }
863
864 struct wiringPiNodeStruct *wiringPiNewNode (int pinBase, int numPins)
865 {
866   int    pin ;
867   struct wiringPiNodeStruct *node ;
868
869 // Minimum pin base is 64
870
871   if (pinBase < 64)
872     (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: pinBase of %d is < 64\n", pinBase) ;
873
874 // Check all pins in-case there is overlap:
875
876   for (pin = pinBase ; pin < (pinBase + numPins) ; ++pin)
877     if (wiringPiFindNode (pin) != NULL)
878       (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Pin %d overlaps with existing definition\n", pin) ;
879
880   node = (struct wiringPiNodeStruct *)calloc (sizeof (struct wiringPiNodeStruct), 1) ;  // calloc zeros
881   if (node == NULL)
882     (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Unable to allocate memory: %s\n", strerror (errno)) ;
883
884   node->pinBase         = pinBase ;
885   node->pinMax          = pinBase + numPins - 1 ;
886   node->pinMode         = pinModeDummy ;
887   node->pullUpDnControl = pullUpDnControlDummy ;
888   node->digitalRead     = digitalReadDummy ;
889   node->digitalWrite    = digitalWriteDummy ;
890   node->pwmWrite        = pwmWriteDummy ;
891   node->analogRead      = analogReadDummy ;
892   node->analogWrite     = analogWriteDummy ;
893   node->next            = wiringPiNodes ;
894   wiringPiNodes         = node ;
895
896   return node ;
897 }
898
899
900 #ifdef notYetReady
901 /*
902  * pinED01:
903  * pinED10:
904  *      Enables edge-detect mode on a pin - from a 0 to a 1 or 1 to 0
905  *      Pin must already be in input mode with appropriate pull up/downs set.
906  *********************************************************************************
907  */
908
909 void pinEnableED01Pi (int pin)
910 {
911   pin = pinToGpio [pin & 63] ;
912 }
913 #endif
914
915
916 /*
917  *********************************************************************************
918  * Core Functions
919  *********************************************************************************
920  */
921
922
923 /*
924  * pinMode:
925  *      Sets the mode of a pin to be input, output or PWM output
926  *********************************************************************************
927  */
928
929 void pinMode (int pin, int mode)
930 {
931   int    fSel, shift, alt ;
932   struct wiringPiNodeStruct *node = wiringPiNodes ;
933
934   if ((pin & PI_GPIO_MASK) == 0)                // On-board pin
935   {
936     /**/ if (wiringPiMode == WPI_MODE_PINS)
937       pin = pinToGpio [pin] ;
938     else if (wiringPiMode == WPI_MODE_PHYS)
939       pin = physToGpio [pin] ;
940     else if (wiringPiMode != WPI_MODE_GPIO)
941       return ;
942
943     fSel    = gpioToGPFSEL [pin] ;
944     shift   = gpioToShift  [pin] ;
945
946     /**/ if (mode == INPUT)
947       *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
948     else if (mode == OUTPUT)
949       *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
950     else if (mode == PWM_OUTPUT)
951     {
952       if ((alt = gpioToPwmALT [pin]) == 0)      // Not a PWM pin
953         return ;
954
955 // Set pin to PWM mode
956
957       *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
958       delayMicroseconds (110) ;         // See comments in pwmSetClockWPi
959
960       pwmSetMode  (PWM_MODE_BAL) ;      // Pi default mode
961       pwmSetRange (1024) ;              // Default range of 1024
962       pwmSetClock (32) ;                        // 19.2 / 32 = 600KHz - Also starts the PWM
963     }
964     else if (mode == GPIO_CLOCK)
965     {
966       if ((alt = gpioToGpClkALT0 [pin]) == 0)   // Not a GPIO_CLOCK pin
967         return ;
968
969 // Set pin to GPIO_CLOCK mode and set the clock frequency to 100KHz
970
971       *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
972       delayMicroseconds (110) ;
973       gpioClockSet      (pin, 100000) ;
974     }
975   }
976   else
977   {
978     if ((node = wiringPiFindNode (pin)) != NULL)
979       node->pinMode (node, pin, mode) ;
980     return ;
981   }
982 }
983
984
985 /*
986  * pullUpDownCtrl:
987  *      Control the internal pull-up/down resistors on a GPIO pin
988  *      The Arduino only has pull-ups and these are enabled by writing 1
989  *      to a port when in input mode - this paradigm doesn't quite apply
990  *      here though.
991  *********************************************************************************
992  */
993
994 void pullUpDnControl (int pin, int pud)
995 {
996   struct wiringPiNodeStruct *node = wiringPiNodes ;
997
998   if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
999   {
1000     /**/ if (wiringPiMode == WPI_MODE_PINS)
1001       pin = pinToGpio [pin] ;
1002     else if (wiringPiMode == WPI_MODE_PHYS)
1003       pin = physToGpio [pin] ;
1004     else if (wiringPiMode != WPI_MODE_GPIO)
1005       return ;
1006
1007     *(gpio + GPPUD)              = pud & 3 ;            delayMicroseconds (5) ;
1008     *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ;    delayMicroseconds (5) ;
1009     
1010     *(gpio + GPPUD)              = 0 ;                  delayMicroseconds (5) ;
1011     *(gpio + gpioToPUDCLK [pin]) = 0 ;                  delayMicroseconds (5) ;
1012   }
1013   else                                          // Extension module
1014   {
1015     if ((node = wiringPiFindNode (pin)) != NULL)
1016       node->pullUpDnControl (node, pin, pud) ;
1017     return ;
1018   }
1019 }
1020
1021
1022 /*
1023  * digitalRead:
1024  *      Read the value of a given Pin, returning HIGH or LOW
1025  *********************************************************************************
1026  */
1027
1028 int digitalRead (int pin)
1029 {
1030   char c ;
1031   struct wiringPiNodeStruct *node = wiringPiNodes ;
1032
1033   if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1034   {
1035     /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS) // Sys mode
1036     {
1037       if (sysFds [pin] == -1)
1038         return LOW ;
1039
1040       lseek  (sysFds [pin], 0L, SEEK_SET) ;
1041       read   (sysFds [pin], &c, 1) ;
1042       return (c == '0') ? LOW : HIGH ;
1043     }
1044     else if (wiringPiMode == WPI_MODE_PINS)
1045       pin = pinToGpio [pin] ;
1046     else if (wiringPiMode == WPI_MODE_PHYS)
1047       pin = physToGpio [pin] ;
1048     else if (wiringPiMode != WPI_MODE_GPIO)
1049       return LOW ;
1050
1051     if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
1052       return HIGH ;
1053     else
1054       return LOW ;
1055   }
1056   else
1057   {
1058     if ((node = wiringPiFindNode (pin)) == NULL)
1059       return LOW ;
1060     return node->digitalRead (node, pin) ;
1061   }
1062 }
1063
1064
1065 /*
1066  * digitalWrite:
1067  *      Set an output bit
1068  *********************************************************************************
1069  */
1070
1071 void digitalWrite (int pin, int value)
1072 {
1073   struct wiringPiNodeStruct *node = wiringPiNodes ;
1074
1075   if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1076   {
1077     /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS) // Sys mode
1078     {
1079       if (sysFds [pin] != -1)
1080       {
1081         if (value == LOW)
1082           write (sysFds [pin], "0\n", 2) ;
1083         else
1084           write (sysFds [pin], "1\n", 2) ;
1085       }
1086       return ;
1087     }
1088     else if (wiringPiMode == WPI_MODE_PINS)
1089       pin = pinToGpio [pin] ;
1090     else if (wiringPiMode == WPI_MODE_PHYS)
1091       pin = physToGpio [pin] ;
1092     else if (wiringPiMode != WPI_MODE_GPIO)
1093       return ;
1094
1095     if (value == LOW)
1096       *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
1097     else
1098       *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
1099   }
1100   else
1101   {
1102     if ((node = wiringPiFindNode (pin)) != NULL)
1103       node->digitalWrite (node, pin, value) ;
1104   }
1105 }
1106
1107
1108 /*
1109  * pwmWrite:
1110  *      Set an output PWM value
1111  *********************************************************************************
1112  */
1113
1114 void pwmWrite (int pin, int value)
1115 {
1116   struct wiringPiNodeStruct *node = wiringPiNodes ;
1117
1118   if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1119   {
1120     /**/ if (wiringPiMode == WPI_MODE_PINS)
1121       pin = pinToGpio [pin] ;
1122     else if (wiringPiMode == WPI_MODE_PHYS)
1123       pin = physToGpio [pin] ;
1124     else if (wiringPiMode != WPI_MODE_GPIO)
1125       return ;
1126
1127     *(pwm + gpioToPwmPort [pin]) = value ;
1128   }
1129   else
1130   {
1131     if ((node = wiringPiFindNode (pin)) != NULL)
1132       node->pwmWrite (node, pin, value) ;
1133   }
1134 }
1135
1136
1137 /*
1138  * analogRead:
1139  *      Read the analog value of a given Pin. 
1140  *      There is no on-board Pi analog hardware,
1141  *      so this needs to go to a new node.
1142  *********************************************************************************
1143  */
1144
1145 int analogRead (int pin)
1146 {
1147   struct wiringPiNodeStruct *node = wiringPiNodes ;
1148
1149   if ((node = wiringPiFindNode (pin)) == NULL)
1150     return 0 ;
1151   else
1152     return node->analogRead (node, pin) ;
1153 }
1154
1155
1156 /*
1157  * analogWrite:
1158  *      Write the analog value to the given Pin. 
1159  *      There is no on-board Pi analog hardware,
1160  *      so this needs to go to a new node.
1161  *********************************************************************************
1162  */
1163
1164 void analogWrite (int pin, int value)
1165 {
1166   struct wiringPiNodeStruct *node = wiringPiNodes ;
1167
1168   if ((node = wiringPiFindNode (pin)) == NULL)
1169     return ;
1170
1171   node->analogWrite (node, pin, value) ;
1172 }
1173
1174
1175
1176 /*
1177  * digitalWriteByte:
1178  *      Pi Specific
1179  *      Write an 8-bit byte to the first 8 GPIO pins - try to do it as
1180  *      fast as possible.
1181  *      However it still needs 2 operations to set the bits, so any external
1182  *      hardware must not rely on seeing a change as there will be a change 
1183  *      to set the outputs bits to zero, then another change to set the 1's
1184  *********************************************************************************
1185  */
1186
1187 void digitalWriteByte (int value)
1188 {
1189   uint32_t pinSet = 0 ;
1190   uint32_t pinClr = 0 ;
1191   int mask = 1 ;
1192   int pin ;
1193
1194   /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)
1195   {
1196     for (pin = 0 ; pin < 8 ; ++pin)
1197     {
1198       digitalWrite (pin, value & mask) ;
1199       mask <<= 1 ;
1200     }
1201     return ;
1202   }
1203   else
1204   {
1205     for (pin = 0 ; pin < 8 ; ++pin)
1206     {
1207       if ((value & mask) == 0)
1208         pinClr |= (1 << pinToGpio [pin]) ;
1209       else
1210         pinSet |= (1 << pinToGpio [pin]) ;
1211
1212       mask <<= 1 ;
1213     }
1214
1215     *(gpio + gpioToGPCLR [0]) = pinClr ;
1216     *(gpio + gpioToGPSET [0]) = pinSet ;
1217   }
1218 }
1219
1220
1221 /*
1222  * waitForInterrupt:
1223  *      Pi Specific.
1224  *      Wait for Interrupt on a GPIO pin.
1225  *      This is actually done via the /sys/class/gpio interface regardless of
1226  *      the wiringPi access mode in-use. Maybe sometime it might get a better
1227  *      way for a bit more efficiency.
1228  *********************************************************************************
1229  */
1230
1231 int waitForInterrupt (int pin, int mS)
1232 {
1233   int fd, x ;
1234   uint8_t c ;
1235   struct pollfd polls ;
1236
1237   /**/ if (wiringPiMode == WPI_MODE_PINS)
1238     pin = pinToGpio [pin] ;
1239   else if (wiringPiMode == WPI_MODE_PHYS)
1240     pin = physToGpio [pin] ;
1241
1242   if ((fd = sysFds [pin]) == -1)
1243     return -2 ;
1244
1245 // Setup poll structure
1246
1247   polls.fd     = fd ;
1248   polls.events = POLLPRI ;      // Urgent data!
1249
1250 // Wait for it ...
1251
1252   x = poll (&polls, 1, mS) ;
1253
1254 // Do a dummy read to clear the interrupt
1255 //      A one character read appars to be enough.
1256
1257   (void)read (fd, &c, 1) ;
1258
1259   return x ;
1260 }
1261
1262
1263 /*
1264  * interruptHandler:
1265  *      This is a thread and gets started to wait for the interrupt we're
1266  *      hoping to catch. It will call the user-function when the interrupt
1267  *      fires.
1268  *********************************************************************************
1269  */
1270
1271 static void *interruptHandler (void *arg)
1272 {
1273   int myPin ;
1274
1275   (void)piHiPri (55) ;  // Only effective if we run as root
1276
1277   myPin   = pinPass ;
1278   pinPass = -1 ;
1279
1280   for (;;)
1281     if (waitForInterrupt (myPin, -1) > 0)
1282       isrFunctions [myPin] () ;
1283
1284   return NULL ;
1285 }
1286
1287
1288 /*
1289  * wiringPiISR:
1290  *      Pi Specific.
1291  *      Take the details and create an interrupt handler that will do a call-
1292  *      back to the user supplied function.
1293  *********************************************************************************
1294  */
1295
1296 int wiringPiISR (int pin, int mode, void (*function)(void))
1297 {
1298   pthread_t threadId ;
1299   const char *modeS ;
1300   char fName   [64] ;
1301   char  pinS [8] ;
1302   pid_t pid ;
1303   int   count, i ;
1304   char  c ;
1305   int   bcmGpioPin ;
1306
1307   pin &= 63 ;
1308
1309   /**/ if (wiringPiMode == WPI_MODE_UNINITIALISED)
1310     return wiringPiFailure (WPI_FATAL, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
1311   else if (wiringPiMode == WPI_MODE_PINS)
1312     bcmGpioPin = pinToGpio [pin] ;
1313   else if (wiringPiMode == WPI_MODE_PHYS)
1314     bcmGpioPin = physToGpio [pin] ;
1315   else
1316     bcmGpioPin = pin ;
1317
1318 // Now export the pin and set the right edge
1319 //      We're going to use the gpio program to do this, so it assumes
1320 //      a full installation of wiringPi. It's a bit 'clunky', but it
1321 //      is a way that will work when we're running in "Sys" mode, as
1322 //      a non-root user. (without sudo)
1323
1324   if (mode != INT_EDGE_SETUP)
1325   {
1326     /**/ if (mode == INT_EDGE_FALLING)
1327       modeS = "falling" ;
1328     else if (mode == INT_EDGE_RISING)
1329       modeS = "rising" ;
1330     else
1331       modeS = "both" ;
1332
1333     sprintf (pinS, "%d", bcmGpioPin) ;
1334
1335     if ((pid = fork ()) < 0)    // Fail
1336       return pid ;
1337
1338     if (pid == 0)       // Child, exec
1339     {
1340       execl ("/usr/local/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
1341       return -1 ;       // Failure ...
1342     }
1343     else                // Parent, wait
1344       wait (NULL) ;
1345   }
1346
1347 // Now pre-open the /sys/class node - it may already be open if
1348 //      we are in Sys mode or if we call here twice, if-so, we'll close it.
1349
1350   if (sysFds [bcmGpioPin] != -1)
1351     close (sysFds [bcmGpioPin]) ;
1352
1353   sprintf (fName, "/sys/class/gpio/gpio%d/value", bcmGpioPin) ;
1354   if ((sysFds [bcmGpioPin] = open (fName, O_RDWR)) < 0)
1355     return -1 ;
1356
1357 // Clear any initial pending interrupt
1358
1359   ioctl (sysFds [bcmGpioPin], FIONREAD, &count) ;
1360   for (i = 0 ; i < count ; ++i)
1361     read (sysFds [bcmGpioPin], &c, 1) ;
1362
1363   isrFunctions [pin] = function ;
1364
1365   pthread_mutex_lock (&pinMutex) ;
1366     pinPass = pin ;
1367     pthread_create (&threadId, NULL, interruptHandler, NULL) ;
1368     while (pinPass != -1)
1369       delay (1) ;
1370   pthread_mutex_unlock (&pinMutex) ;
1371
1372   return 0 ;
1373 }
1374
1375
1376 /*
1377  * initialiseEpoch:
1378  *      Initialise our start-of-time variable to be the current unix
1379  *      time in milliseconds and microseconds.
1380  *********************************************************************************
1381  */
1382
1383 static void initialiseEpoch (void)
1384 {
1385   struct timeval tv ;
1386
1387   gettimeofday (&tv, NULL) ;
1388   epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000    + (uint64_t)(tv.tv_usec / 1000) ;
1389   epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
1390 }
1391
1392
1393 /*
1394  * delay:
1395  *      Wait for some number of milliseconds
1396  *********************************************************************************
1397  */
1398
1399 void delay (unsigned int howLong)
1400 {
1401   struct timespec sleeper, dummy ;
1402
1403   sleeper.tv_sec  = (time_t)(howLong / 1000) ;
1404   sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
1405
1406   nanosleep (&sleeper, &dummy) ;
1407 }
1408
1409
1410 /*
1411  * delayMicroseconds:
1412  *      This is somewhat intersting. It seems that on the Pi, a single call
1413  *      to nanosleep takes some 80 to 130 microseconds anyway, so while
1414  *      obeying the standards (may take longer), it's not always what we
1415  *      want!
1416  *
1417  *      So what I'll do now is if the delay is less than 100uS we'll do it
1418  *      in a hard loop, watching a built-in counter on the ARM chip. This is
1419  *      somewhat sub-optimal in that it uses 100% CPU, something not an issue
1420  *      in a microcontroller, but under a multi-tasking, multi-user OS, it's
1421  *      wastefull, however we've no real choice )-:
1422  *
1423  *      Plan B: It seems all might not be well with that plan, so changing it
1424  *      to use gettimeofday () and poll on that instead...
1425  *********************************************************************************
1426  */
1427
1428 void delayMicrosecondsHard (unsigned int howLong)
1429 {
1430   struct timeval tNow, tLong, tEnd ;
1431
1432   gettimeofday (&tNow, NULL) ;
1433   tLong.tv_sec  = howLong / 1000000 ;
1434   tLong.tv_usec = howLong % 1000000 ;
1435   timeradd (&tNow, &tLong, &tEnd) ;
1436
1437   while (timercmp (&tNow, &tEnd, <))
1438     gettimeofday (&tNow, NULL) ;
1439 }
1440
1441 void delayMicroseconds (unsigned int howLong)
1442 {
1443   struct timespec sleeper ;
1444
1445   /**/ if (howLong ==   0)
1446     return ;
1447   else if (howLong  < 100)
1448     delayMicrosecondsHard (howLong) ;
1449   else
1450   {
1451     sleeper.tv_sec  = 0 ;
1452     sleeper.tv_nsec = (long)(howLong * 1000) ;
1453     nanosleep (&sleeper, NULL) ;
1454   }
1455 }
1456
1457
1458 /*
1459  * millis:
1460  *      Return a number of milliseconds as an unsigned int.
1461  *********************************************************************************
1462  */
1463
1464 unsigned int millis (void)
1465 {
1466   struct timeval tv ;
1467   uint64_t now ;
1468
1469   gettimeofday (&tv, NULL) ;
1470   now  = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
1471
1472   return (uint32_t)(now - epochMilli) ;
1473 }
1474
1475
1476 /*
1477  * micros:
1478  *      Return a number of microseconds as an unsigned int.
1479  *********************************************************************************
1480  */
1481
1482 unsigned int micros (void)
1483 {
1484   struct timeval tv ;
1485   uint64_t now ;
1486
1487   gettimeofday (&tv, NULL) ;
1488   now  = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
1489
1490   return (uint32_t)(now - epochMicro) ;
1491 }
1492
1493
1494 /*
1495  * wiringPiSetup:
1496  *      Must be called once at the start of your program execution.
1497  *
1498  * Default setup: Initialises the system into wiringPi Pin mode and uses the
1499  *      memory mapped hardware directly.
1500  *********************************************************************************
1501  */
1502
1503 int wiringPiSetup (void)
1504 {
1505   int      fd ;
1506   int      boardRev ;
1507
1508   if (getenv (ENV_DEBUG) != NULL)
1509     wiringPiDebug = TRUE ;
1510
1511   if (getenv (ENV_CODES) != NULL)
1512     wiringPiReturnCodes = TRUE ;
1513
1514   if (geteuid () != 0)
1515     (void)wiringPiFailure (WPI_FATAL, "wiringPiSetup: Must be root. (Did you forget sudo?)\n") ;
1516
1517   if (wiringPiDebug)
1518     printf ("wiringPi: wiringPiSetup called\n") ;
1519
1520   boardRev = piBoardRev () ;
1521
1522   if (boardRev == 1)
1523   {
1524      pinToGpio =  pinToGpioR1 ;
1525     physToGpio = physToGpioR1 ;
1526   }
1527   else
1528   {
1529      pinToGpio =  pinToGpioR2 ;
1530     physToGpio = physToGpioR2 ;
1531   }
1532
1533 // Open the master /dev/memory device
1534
1535   if ((fd = open ("/dev/mem", O_RDWR | O_SYNC) ) < 0)
1536     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: Unable to open /dev/mem: %s\n", strerror (errno)) ;
1537
1538 // GPIO:
1539
1540   gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
1541   if ((int32_t)gpio == -1)
1542     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (GPIO) failed: %s\n", strerror (errno)) ;
1543
1544 // PWM
1545
1546   pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
1547   if ((int32_t)pwm == -1)
1548     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PWM) failed: %s\n", strerror (errno)) ;
1549  
1550 // Clock control (needed for PWM)
1551
1552   clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, CLOCK_BASE) ;
1553   if ((int32_t)clk == -1)
1554     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (CLOCK) failed: %s\n", strerror (errno)) ;
1555  
1556 // The drive pads
1557
1558   pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
1559   if ((int32_t)pads == -1)
1560     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PADS) failed: %s\n", strerror (errno)) ;
1561
1562 #ifdef  USE_TIMER
1563 // The system timer
1564
1565   timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
1566   if ((int32_t)timer == -1)
1567     return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (TIMER) failed: %s\n", strerror (errno)) ;
1568
1569 // Set the timer to free-running, 1MHz.
1570 //      0xF9 is 249, the timer divide is base clock / (divide+1)
1571 //      so base clock is 250MHz / 250 = 1MHz.
1572
1573   *(timer + TIMER_CONTROL) = 0x0000280 ;
1574   *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
1575   timerIrqRaw = timer + TIMER_IRQ_RAW ;
1576 #endif
1577
1578   initialiseEpoch () ;
1579
1580   wiringPiMode = WPI_MODE_PINS ;
1581
1582   return 0 ;
1583 }
1584
1585
1586 /*
1587  * wiringPiSetupGpio:
1588  *      Must be called once at the start of your program execution.
1589  *
1590  * GPIO setup: Initialises the system into GPIO Pin mode and uses the
1591  *      memory mapped hardware directly.
1592  *********************************************************************************
1593  */
1594
1595 int wiringPiSetupGpio (void)
1596 {
1597   (void)wiringPiSetup () ;
1598
1599   if (wiringPiDebug)
1600     printf ("wiringPi: wiringPiSetupGpio called\n") ;
1601
1602   wiringPiMode = WPI_MODE_GPIO ;
1603
1604   return 0 ;
1605 }
1606
1607
1608 /*
1609  * wiringPiSetupPhys:
1610  *      Must be called once at the start of your program execution.
1611  *
1612  * Phys setup: Initialises the system into Physical Pin mode and uses the
1613  *      memory mapped hardware directly.
1614  *********************************************************************************
1615  */
1616
1617 int wiringPiSetupPhys (void)
1618 {
1619   (void)wiringPiSetup () ;
1620
1621   if (wiringPiDebug)
1622     printf ("wiringPi: wiringPiSetupPhys called\n") ;
1623
1624   wiringPiMode = WPI_MODE_PHYS ;
1625
1626   return 0 ;
1627 }
1628
1629
1630 /*
1631  * wiringPiSetupSys:
1632  *      Must be called once at the start of your program execution.
1633  *
1634  * Initialisation (again), however this time we are using the /sys/class/gpio
1635  *      interface to the GPIO systems - slightly slower, but always usable as
1636  *      a non-root user, assuming the devices are already exported and setup correctly.
1637  */
1638
1639 int wiringPiSetupSys (void)
1640 {
1641   int boardRev ;
1642   int pin ;
1643   char fName [128] ;
1644
1645   if (getenv (ENV_DEBUG) != NULL)
1646     wiringPiDebug = TRUE ;
1647
1648   if (getenv (ENV_CODES) != NULL)
1649     wiringPiReturnCodes = TRUE ;
1650
1651   if (wiringPiDebug)
1652     printf ("wiringPi: wiringPiSetupSys called\n") ;
1653
1654   boardRev = piBoardRev () ;
1655
1656   if (boardRev == 1)
1657   {
1658      pinToGpio =  pinToGpioR1 ;
1659     physToGpio = physToGpioR1 ;
1660   }
1661   else
1662   {
1663      pinToGpio =  pinToGpioR2 ;
1664     physToGpio = physToGpioR2 ;
1665   }
1666
1667 // Open and scan the directory, looking for exported GPIOs, and pre-open
1668 //      the 'value' interface to speed things up for later
1669   
1670   for (pin = 0 ; pin < 64 ; ++pin)
1671   {
1672     sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1673     sysFds [pin] = open (fName, O_RDWR) ;
1674   }
1675
1676   initialiseEpoch () ;
1677
1678   wiringPiMode = WPI_MODE_GPIO_SYS ;
1679
1680   return 0 ;
1681 }