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