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