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