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