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