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