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