chiark / gitweb /
Quite a few changes here.
[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 <stdint.h>
57 #include <stdlib.h>
58 #include <ctype.h>
59 #include <poll.h>
60 #include <unistd.h>
61 #include <errno.h>
62 #include <string.h>
63 #include <time.h>
64 #include <fcntl.h>
65 #include <pthread.h>
66 #include <sys/time.h>
67 #include <sys/mman.h>
68 #include <sys/stat.h>
69 #include <sys/wait.h>
70 #include <sys/ioctl.h>
71
72 #include "wiringPi.h"
73
74 // Function stubs
75
76 void (*pinMode)           (int pin, int mode) ;
77 int  (*getAlt)            (int pin) ;
78 void (*pullUpDnControl)   (int pin, int pud) ;
79 void (*digitalWrite)      (int pin, int value) ;
80 void (*digitalWriteByte)  (int value) ;
81 void (*pwmWrite)          (int pin, int value) ;
82 void (*setPadDrive)       (int group, int value) ;
83 int  (*digitalRead)       (int pin) ;
84 int  (*waitForInterrupt)  (int pin, int mS) ;
85 void (*pwmSetMode)        (int mode) ;
86 void (*pwmSetRange)       (unsigned int range) ;
87 void (*pwmSetClock)       (int divisor) ;
88
89
90 #ifndef TRUE
91 #define TRUE    (1==1)
92 #define FALSE   (1==2)
93 #endif
94
95 // BCM Magic
96
97 #define BCM_PASSWORD            0x5A000000
98
99
100 // Port function select bits
101
102 #define FSEL_INPT               0b000
103 #define FSEL_OUTP               0b001
104 #define FSEL_ALT0               0b100
105 #define FSEL_ALT0               0b100
106 #define FSEL_ALT1               0b101
107 #define FSEL_ALT2               0b110
108 #define FSEL_ALT3               0b111
109 #define FSEL_ALT4               0b011
110 #define FSEL_ALT5               0b010
111
112 // Access from ARM Running Linux
113 //      Take from Gert/Doms code. Some of this is not in the manual
114 //      that I can find )-:
115
116 #define BCM2708_PERI_BASE                          0x20000000
117 #define GPIO_PADS               (BCM2708_PERI_BASE + 0x100000)
118 #define CLOCK_BASE              (BCM2708_PERI_BASE + 0x101000)
119 #define GPIO_BASE               (BCM2708_PERI_BASE + 0x200000)
120 #define GPIO_TIMER              (BCM2708_PERI_BASE + 0x00B000)
121 #define GPIO_PWM                (BCM2708_PERI_BASE + 0x20C000)
122
123 #define PAGE_SIZE               (4*1024)
124 #define BLOCK_SIZE              (4*1024)
125
126 // PWM
127
128 #define PWM_CONTROL 0
129 #define PWM_STATUS  1
130 #define PWM0_RANGE  4
131 #define PWM0_DATA   5
132 #define PWM1_RANGE  8
133 #define PWM1_DATA   9
134
135 #define PWMCLK_CNTL     40
136 #define PWMCLK_DIV      41
137
138 #define PWM1_MS_MODE    0x8000  // Run in MS mode
139 #define PWM1_USEFIFO    0x2000  // Data from FIFO
140 #define PWM1_REVPOLAR   0x1000  // Reverse polarity
141 #define PWM1_OFFSTATE   0x0800  // Ouput Off state
142 #define PWM1_REPEATFF   0x0400  // Repeat last value if FIFO empty
143 #define PWM1_SERIAL     0x0200  // Run in serial mode
144 #define PWM1_ENABLE     0x0100  // Channel Enable
145
146 #define PWM0_MS_MODE    0x0080  // Run in MS mode
147 #define PWM0_USEFIFO    0x0020  // Data from FIFO
148 #define PWM0_REVPOLAR   0x0010  // Reverse polarity
149 #define PWM0_OFFSTATE   0x0008  // Ouput Off state
150 #define PWM0_REPEATFF   0x0004  // Repeat last value if FIFO empty
151 #define PWM0_SERIAL     0x0002  // Run in serial mode
152 #define PWM0_ENABLE     0x0001  // Channel Enable
153
154 // Timer
155
156 #define TIMER_LOAD      (0x400 >> 2)
157 #define TIMER_VALUE     (0x404 >> 2)
158 #define TIMER_CONTROL   (0x408 >> 2)
159 #define TIMER_IRQ_CLR   (0x40C >> 2)
160 #define TIMER_IRQ_RAW   (0x410 >> 2)
161 #define TIMER_IRQ_MASK  (0x414 >> 2)
162 #define TIMER_RELOAD    (0x418 >> 2)
163 #define TIMER_PRE_DIV   (0x41C >> 2)
164 #define TIMER_COUNTER   (0x420 >> 2)
165
166 // Locals to hold pointers to the hardware
167
168 static volatile uint32_t *gpio ;
169 static volatile uint32_t *pwm ;
170 static volatile uint32_t *clk ;
171 static volatile uint32_t *pads ;
172 static volatile uint32_t *timer ;
173 static volatile uint32_t *timerIrqRaw ;
174
175 // Time for easy calculations
176
177 static uint64_t epochMilli, epochMicro ;
178
179 // Misc
180
181 static int wiringPiMode = WPI_MODE_UNINITIALISED ;
182
183 // Debugging
184
185 int wiringPiDebug = FALSE ;
186
187 // The BCM2835 has 54 GPIO pins.
188 //      BCM2835 data sheet, Page 90 onwards.
189 //      There are 6 control registers, each control the functions of a block
190 //      of 10 pins.
191 //      Each control register has 10 sets of 3 bits per GPIO pin:
192 //
193 //      000 = GPIO Pin X is an input
194 //      001 = GPIO Pin X is an output
195 //      100 = GPIO Pin X takes alternate function 0
196 //      101 = GPIO Pin X takes alternate function 1
197 //      110 = GPIO Pin X takes alternate function 2
198 //      111 = GPIO Pin X takes alternate function 3
199 //      011 = GPIO Pin X takes alternate function 4
200 //      010 = GPIO Pin X takes alternate function 5
201 //
202 // So the 3 bits for port X are:
203 //      X / 10 + ((X % 10) * 3)
204
205 // sysFds:
206 //      Map a file descriptor from the /sys/class/gpio/gpioX/value
207
208 static int sysFds [64] ;
209
210 // ISR Data
211
212 static void (*isrFunctions [64])(void) ;
213
214
215 // Doing it the Arduino way with lookup tables...
216 //      Yes, it's probably more innefficient than all the bit-twidling, but it
217 //      does tend to make it all a bit clearer. At least to me!
218
219 // pinToGpio:
220 //      Take a Wiring pin (0 through X) and re-map it to the BCM_GPIO pin
221 //      Cope for 2 different board revieions here
222
223 static int *pinToGpio ;
224
225 static int pinToGpioR1 [64] =
226 {
227   17, 18, 21, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7
228    0,  1,                               // I2C  - SDA0, SCL0
229    8,  7,                               // SPI  - CE1, CE0
230   10,  9, 11,                           // SPI  - MOSI, MISO, SCLK
231   14, 15,                               // UART - Tx, Rx
232
233 // Padding:
234
235       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 31
236   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
237   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
238 } ;
239
240 static int pinToGpioR2 [64] =
241 {
242   17, 18, 27, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7:   wpi  0 -  7
243    2,  3,                               // I2C  - SDA0, SCL0                            wpi  8 -  9
244    8,  7,                               // SPI  - CE1, CE0                              wpi 10 - 11
245   10,  9, 11,                           // SPI  - MOSI, MISO, SCLK                      wpi 12 - 14
246   14, 15,                               // UART - Tx, Rx                                wpi 15 - 16
247   28, 29, 30, 31,                       // New GPIOs 8 though 11                        wpi 17 - 20
248
249 // Padding:
250
251                       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 31
252   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 47
253   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,       // ... 63
254 } ;
255
256
257 // gpioToGPFSEL:
258 //      Map a BCM_GPIO pin to it's control port. (GPFSEL 0-5)
259
260 static uint8_t gpioToGPFSEL [] =
261 {
262   0,0,0,0,0,0,0,0,0,0,
263   1,1,1,1,1,1,1,1,1,1,
264   2,2,2,2,2,2,2,2,2,2,
265   3,3,3,3,3,3,3,3,3,3,
266   4,4,4,4,4,4,4,4,4,4,
267   5,5,5,5,5,5,5,5,5,5,
268 } ;
269
270
271 // gpioToShift
272 //      Define the shift up for the 3 bits per pin in each GPFSEL port
273
274 static uint8_t gpioToShift [] =
275 {
276   0,3,6,9,12,15,18,21,24,27,
277   0,3,6,9,12,15,18,21,24,27,
278   0,3,6,9,12,15,18,21,24,27,
279   0,3,6,9,12,15,18,21,24,27,
280   0,3,6,9,12,15,18,21,24,27,
281 } ;
282
283
284 // gpioToGPSET:
285 //      (Word) offset to the GPIO Set registers for each GPIO pin
286
287 static uint8_t gpioToGPSET [] =
288 {
289    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,
290    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,
291 } ;
292
293
294 // gpioToGPCLR:
295 //      (Word) offset to the GPIO Clear registers for each GPIO pin
296
297 static uint8_t gpioToGPCLR [] =
298 {
299   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,
300   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,
301 } ;
302
303
304 // gpioToGPLEV:
305 //      (Word) offset to the GPIO Input level registers for each GPIO pin
306
307 static uint8_t gpioToGPLEV [] =
308 {
309   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,
310   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,
311 } ;
312
313
314 #ifdef notYetReady
315 // gpioToEDS
316 //      (Word) offset to the Event Detect Status
317
318 static uint8_t gpioToEDS [] =
319 {
320   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,
321   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,
322 } ;
323
324 // gpioToREN
325 //      (Word) offset to the Rising edgde ENable register
326
327 static uint8_t gpioToREN [] =
328 {
329   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,
330   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,
331 } ;
332
333 // gpioToFEN
334 //      (Word) offset to the Falling edgde ENable register
335
336 static uint8_t gpioToFEN [] =
337 {
338   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,
339   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,
340 } ;
341 #endif
342
343
344 // gpioToPUDCLK
345 //      (Word) offset to the Pull Up Down Clock regsiter
346
347 #define GPPUD   37
348
349 static uint8_t gpioToPUDCLK [] =
350 {
351   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,
352   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,
353 } ;
354
355
356 // gpioToPwmALT
357 //      the ALT value to put a GPIO pin into PWM mode
358
359 static uint8_t gpioToPwmALT [] =
360 {
361           0,         0,         0,         0,         0,         0,         0,         0,       //  0 ->  7
362           0,         0,         0,         0, FSEL_ALT0, FSEL_ALT0,         0,         0,       //  8 -> 15
363           0,         0, FSEL_ALT5, FSEL_ALT5,         0,         0,         0,         0,       // 16 -> 23
364           0,         0,         0,         0,         0,         0,         0,         0,       // 24 -> 31
365           0,         0,         0,         0,         0,         0,         0,         0,       // 32 -> 39
366   FSEL_ALT0, FSEL_ALT0,         0,         0,         0, FSEL_ALT0,         0,         0,       // 40 -> 47
367           0,         0,         0,         0,         0,         0,         0,         0,       // 48 -> 55
368           0,         0,         0,         0,         0,         0,         0,         0,       // 56 -> 63
369 } ;
370
371 static uint8_t gpioToPwmPort [] =
372 {
373           0,         0,         0,         0,         0,         0,         0,         0,       //  0 ->  7
374           0,         0,         0,         0, PWM0_DATA, PWM1_DATA,         0,         0,       //  8 -> 15
375           0,         0, PWM0_DATA, PWM1_DATA,         0,         0,         0,         0,       // 16 -> 23
376           0,         0,         0,         0,         0,         0,         0,         0,       // 24 -> 31
377           0,         0,         0,         0,         0,         0,         0,         0,       // 32 -> 39
378   PWM0_DATA, PWM1_DATA,         0,         0,         0, PWM1_DATA,         0,         0,       // 40 -> 47
379           0,         0,         0,         0,         0,         0,         0,         0,       // 48 -> 55
380           0,         0,         0,         0,         0,         0,         0,         0,       // 56 -> 63
381
382 } ;
383
384
385 /*
386  * Functions
387  *********************************************************************************
388  */
389
390
391 /*
392  * wpiPinToGpio:
393  *      Translate a wiringPi Pin number to native GPIO pin number.
394  *      (We don't use this here, prefering to just do the lookup directly,
395  *      but it's been requested!)
396  *********************************************************************************
397  */
398
399 int wpiPinToGpio (int wpiPin)
400 {
401   return pinToGpio [wpiPin & 63] ;
402 }
403
404
405 /*
406  * piBoardRev:
407  *      Return a number representing the hardware revision of the board.
408  *      Revision is currently 1 or 2. -1 is returned on error.
409  *
410  *      Much confusion here )-:
411  *      Seems there are some boards with 0000 in them (mistake in manufacture)
412  *      and some board with 0005 in them (another mistake in manufacture?)
413  *      So the distinction between boards that I can see is:
414  *      0000 - Error
415  *      0001 - Not used
416  *      0002 - Rev 1
417  *      0003 - Rev 1
418  *      0004 - Rev 2
419  *      0005 - Rev 2 (but error)
420  *      0006 - Rev 2
421  *      000f - Rev 2 + 512MB
422  *
423  *      A small thorn is the olde style overvolting - that will add in
424  *              1000000
425  *
426  *********************************************************************************
427  */
428
429 static void piBoardRevOops (char *why)
430 {
431   fprintf (stderr, "piBoardRev: Unable to determine board revision from /proc/cpuinfo\n") ;
432   fprintf (stderr, " -> %s\n", why) ;
433   fprintf (stderr, " ->  You may want to check:\n") ;
434   fprintf (stderr, " ->  http://www.raspberrypi.org/phpBB3/viewtopic.php?p=184410#p184410\n") ;
435   exit (EXIT_FAILURE) ;
436 }
437
438 int piBoardRev (void)
439 {
440   FILE *cpuFd ;
441   char line [120] ;
442   char *c, lastChar ;
443   static int  boardRev = -1 ;
444
445 // No point checking twice...
446
447   if (boardRev != -1)
448     return boardRev ;
449
450   if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
451     return -1 ;
452
453   while (fgets (line, 120, cpuFd) != NULL)
454     if (strncmp (line, "Revision", 8) == 0)
455       break ;
456
457   fclose (cpuFd) ;
458
459   if (line == NULL)
460     piBoardRevOops ("No \"Revision\" line") ;
461
462   line [strlen (line) - 1] = 0 ; // Chomp LF
463   
464   if (wiringPiDebug)
465     printf ("piboardRev: Revision string: %s\n", line) ;
466
467   for (c = line ; *c ; ++c)
468     if (isdigit (*c))
469       break ;
470
471   if (!isdigit (*c))
472     piBoardRevOops ("No numeric revision string") ;
473
474 // If you have overvolted the Pi, then it appears that the revision
475 //      has 100000 added to it!
476
477   if (wiringPiDebug)
478     if (strlen (c) != 4)
479       printf ("piboardRev: This Pi has/is overvolted!\n") ;
480
481   lastChar = line [strlen (line) - 1] ;
482
483   if (wiringPiDebug)
484     printf ("piboardRev: lastChar is: '%c' (%d, 0x%02X)\n", lastChar, lastChar, lastChar) ;
485
486   /**/ if ((lastChar == '2') || (lastChar == '3'))
487     boardRev = 1 ;
488   else
489     boardRev = 2 ;
490
491   if (wiringPiDebug)
492     printf ("piBoardRev: Returning revision: %d\n", boardRev) ;
493
494   return boardRev ;
495 }
496
497
498
499 /*
500  * pinMode:
501  *      Sets the mode of a pin to be input, output or PWM output
502  *********************************************************************************
503  */
504
505 void pinModeGpio (int pin, int mode)
506 {
507 //  register int barrier ;
508
509   int fSel, shift, alt ;
510
511   pin &= 63 ;
512
513   fSel    = gpioToGPFSEL [pin] ;
514   shift   = gpioToShift  [pin] ;
515
516   /**/ if (mode == INPUT)
517     *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
518   else if (mode == OUTPUT)
519     *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
520   else if (mode == PWM_OUTPUT)
521   {
522     if ((alt = gpioToPwmALT [pin]) == 0)        // Not a PWM pin
523       return ;
524
525 // Set pin to PWM mode
526
527     *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
528
529     delayMicroseconds (110) ;                           // See comments in pwmSetClockWPi
530     *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
531
532 //  Page 107 of the BCM Peripherals manual talks about the GPIO clocks,
533 //      but I'm assuming (hoping!) that this applies to other clocks too.
534
535     *(pwm + PWM_CONTROL) = 0 ;                          // Stop PWM
536
537     *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ;        // Stop PWM Clock
538     delayMicroseconds (110) ;                           // See comments in pwmSetClockWPi
539
540     while ((*(clk + PWMCLK_CNTL) & 0x80) != 0)          // Wait for clock to be !BUSY
541       delayMicroseconds (1) ;
542
543     *(clk + PWMCLK_DIV)  = BCM_PASSWORD | (32 << 12) ;  // set pwm div to 32 (19.2/32 = 600KHz)
544     *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ;        // enable clk
545
546     delayMicroseconds (110) ;                           // See comments in pwmSetClockWPi
547
548 // Default range register of 1024
549
550     *(pwm + PWM0_RANGE) = 1024 ; delayMicroseconds (10) ;
551     *(pwm + PWM1_RANGE) = 1024 ; delayMicroseconds (10) ;
552     *(pwm + PWM0_DATA)  =    0 ; delayMicroseconds (10) ;
553     *(pwm + PWM1_DATA)  =    0 ; delayMicroseconds (10) ;
554
555 // Enable PWMs in balanced mode (default)
556
557     *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
558
559     delay (100) ;
560   }
561
562
563 // When we change mode of any pin, we remove the pull up/downs
564 //      Or we used to... Hm. Commented out now because for some wieird reason,
565 //      it seems to block subsequent attempts to set the pull up/downs and I've
566 //      not quite gotten to the bottom of why this happens
567 //      The down-side is that the pull up/downs are rememberd in the SoC between
568 //      power cycles, so it's going to be a good idea to explicitly set them in
569 //      any new code.
570 //
571 //  pullUpDnControl (pin, PUD_OFF) ;
572
573 }
574
575 void pinModeWPi (int pin, int mode)
576 {
577   pinModeGpio (pinToGpio [pin & 63], mode) ;
578 }
579
580 void pinModeSys (int pin, int mode)
581 {
582   return ;
583 }
584
585
586 /*
587  * getAlt:
588  *      Returns the ALT bits for a given port. Only really of-use
589  *      for the gpio readall command (I think)
590  *********************************************************************************
591  */
592
593 int getAltGpio (int pin)
594 {
595   int fSel, shift, alt ;
596
597   pin &= 63 ;
598
599   fSel    = gpioToGPFSEL [pin] ;
600   shift   = gpioToShift  [pin] ;
601
602   alt = (*(gpio + fSel) >> shift) & 7 ;
603
604   return alt ;
605 }
606
607 int getAltWPi (int pin)
608 {
609   return getAltGpio (pinToGpio [pin & 63]) ;
610 }
611
612 int getAltSys (int pin)
613 {
614   return 0 ;
615 }
616
617
618 /*
619  * pwmControl:
620  *      Allow the user to control some of the PWM functions
621  *********************************************************************************
622  */
623
624 void pwmSetModeWPi (int mode)
625 {
626   if (mode == PWM_MODE_MS)
627     *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
628   else
629     *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
630 }
631
632 void pwmSetModeSys (int mode)
633 {
634   return ;
635 }
636
637
638 void pwmSetRangeWPi (unsigned int range)
639 {
640   *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
641   *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
642 }
643
644 void pwmSetRangeSys (unsigned int range)
645 {
646   return ;
647 }
648
649 /*
650  * pwmSetClockWPi:
651  *      Set/Change the PWM clock. Originally my code, but changed
652  *      (for the better!) by Chris Hall, <chris@kchall.plus.com>
653  *      after further study of the manual and testing with a 'scope
654  *********************************************************************************
655  */
656
657 void pwmSetClockWPi (int divisor)
658 {
659   uint32_t pwm_control ;
660   divisor &= 4095 ;
661
662   if (wiringPiDebug)
663     printf ("Setting to: %d. Current: 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
664
665   pwm_control = *(pwm + PWM_CONTROL) ;          // preserve PWM_CONTROL
666
667 // We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
668 // stays high.
669
670   *(pwm + PWM_CONTROL) = 0 ;                    // Stop PWM
671
672 // Stop PWM clock before changing divisor. The delay after this does need to
673 // this big (95uS occasionally fails, 100uS OK), it's almost as though the BUSY
674 // flag is not working properly in balanced mode. Without the delay when DIV is
675 // adjusted the clock sometimes switches to very slow, once slow further DIV
676 // adjustments do nothing and it's difficult to get out of this mode.
677
678   *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ;  // Stop PWM Clock
679     delayMicroseconds (110) ;                   // prevents clock going sloooow
680
681   while ((*(clk + PWMCLK_CNTL) & 0x80) != 0)    // Wait for clock to be !BUSY
682     delayMicroseconds (1) ;
683
684   *(clk + PWMCLK_DIV)  = BCM_PASSWORD | (divisor << 12) ;
685
686   *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ;  // Start PWM clock
687   *(pwm + PWM_CONTROL) = pwm_control ;          // restore PWM_CONTROL
688
689   if (wiringPiDebug)
690     printf ("Set     to: %d. Now    : 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
691 }
692
693 void pwmSetClockSys (int divisor)
694 {
695   return ;
696 }
697
698
699 #ifdef notYetReady
700 /*
701  * pinED01:
702  * pinED10:
703  *      Enables edge-detect mode on a pin - from a 0 to a 1 or 1 to 0
704  *      Pin must already be in input mode with appropriate pull up/downs set.
705  *********************************************************************************
706  */
707
708 void pinEnableED01Pi (int pin)
709 {
710   pin = pinToGpio [pin & 63] ;
711 }
712 #endif
713
714
715
716 /*
717  * digitalWrite:
718  *      Set an output bit
719  *********************************************************************************
720  */
721
722 void digitalWriteWPi (int pin, int value)
723 {
724   pin = pinToGpio [pin & 63] ;
725
726   if (value == LOW)
727     *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
728   else
729     *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
730 }
731
732 void digitalWriteGpio (int pin, int value)
733 {
734   pin &= 63 ;
735
736   if (value == LOW)
737     *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
738   else
739     *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
740 }
741
742 void digitalWriteSys (int pin, int value)
743 {
744   pin &= 63 ;
745
746   if (sysFds [pin] != -1)
747   {
748     if (value == LOW)
749       write (sysFds [pin], "0\n", 2) ;
750     else
751       write (sysFds [pin], "1\n", 2) ;
752   }
753 }
754
755
756 /*
757  * digitalWriteByte:
758  *      Write an 8-bit byte to the first 8 GPIO pins - try to do it as
759  *      fast as possible.
760  *      However it still needs 2 operations to set the bits, so any external
761  *      hardware must not rely on seeing a change as there will be a change 
762  *      to set the outputs bits to zero, then another change to set the 1's
763  *********************************************************************************
764  */
765
766 void digitalWriteByteGpio (int value)
767 {
768   uint32_t pinSet = 0 ;
769   uint32_t pinClr = 0 ;
770   int mask = 1 ;
771   int pin ;
772
773   for (pin = 0 ; pin < 8 ; ++pin)
774   {
775     if ((value & mask) == 0)
776       pinClr |= (1 << pinToGpio [pin]) ;
777     else
778       pinSet |= (1 << pinToGpio [pin]) ;
779
780     mask <<= 1 ;
781   }
782
783   *(gpio + gpioToGPCLR [0]) = pinClr ;
784   *(gpio + gpioToGPSET [0]) = pinSet ;
785 }
786
787 void digitalWriteByteSys (int value)
788 {
789   int mask = 1 ;
790   int pin ;
791
792   for (pin = 0 ; pin < 8 ; ++pin)
793   {
794     digitalWriteSys (pinToGpio [pin], value & mask) ;
795     mask <<= 1 ;
796   }
797 }
798
799
800 /*
801  * pwmWrite:
802  *      Set an output PWM value
803  *********************************************************************************
804  */
805
806 void pwmWriteGpio (int pin, int value)
807 {
808   int port ;
809
810   pin  = pin & 63 ;
811   port = gpioToPwmPort [pin] ;
812
813   *(pwm + port) = value ;
814 }
815
816 void pwmWriteWPi (int pin, int value)
817 {
818   pwmWriteGpio (pinToGpio [pin & 63], value) ;
819 }
820
821 void pwmWriteSys (int pin, int value)
822 {
823   return ;
824 }
825
826
827 /*
828  * setPadDrive:
829  *      Set the PAD driver value
830  *********************************************************************************
831  */
832
833 void setPadDriveWPi (int group, int value)
834 {
835   uint32_t wrVal ;
836
837   if ((group < 0) || (group > 2))
838     return ;
839
840   wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
841   *(pads + group + 11) = wrVal ;
842
843   if (wiringPiDebug)
844   {
845     printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
846     printf ("Read : %08X\n", *(pads + group + 11)) ;
847   }
848 }
849
850 void setPadDriveGpio (int group, int value)
851 {
852   setPadDriveWPi (group, value) ;
853 }
854
855 void setPadDriveSys (int group, int value)
856 {
857   return ;
858 }
859
860
861 /*
862  * digitalRead:
863  *      Read the value of a given Pin, returning HIGH or LOW
864  *********************************************************************************
865  */
866
867 int digitalReadWPi (int pin)
868 {
869   pin = pinToGpio [pin & 63] ;
870
871   if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
872     return HIGH ;
873   else
874     return LOW ;
875 }
876
877 int digitalReadGpio (int pin)
878 {
879   pin &= 63 ;
880
881   if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
882     return HIGH ;
883   else
884     return LOW ;
885 }
886
887 int digitalReadSys (int pin)
888 {
889   char c ;
890
891   pin &= 63 ;
892
893   if (sysFds [pin] == -1)
894     return 0 ;
895
896   lseek (sysFds [pin], 0L, SEEK_SET) ;
897   read  (sysFds [pin], &c, 1) ;
898   return (c == '0') ? 0 : 1 ;
899 }
900
901
902 /*
903  * pullUpDownCtrl:
904  *      Control the internal pull-up/down resistors on a GPIO pin
905  *      The Arduino only has pull-ups and these are enabled by writing 1
906  *      to a port when in input mode - this paradigm doesn't quite apply
907  *      here though.
908  *********************************************************************************
909  */
910
911 void pullUpDnControlGpio (int pin, int pud)
912 {
913   pin &= 63 ;
914   pud &=  3 ;
915
916   *(gpio + GPPUD)              = pud ;                  delayMicroseconds (5) ;
917   *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ;      delayMicroseconds (5) ;
918   
919   *(gpio + GPPUD)              = 0 ;                    delayMicroseconds (5) ;
920   *(gpio + gpioToPUDCLK [pin]) = 0 ;                    delayMicroseconds (5) ;
921 }
922
923 void pullUpDnControlWPi (int pin, int pud)
924 {
925   pullUpDnControlGpio (pinToGpio [pin & 63], pud) ;
926 }
927
928 void pullUpDnControlSys (int pin, int pud)
929 {
930   return ;
931 }
932
933
934 /*
935  * waitForInterrupt:
936  *      Wait for Interrupt on a GPIO pin.
937  *      This is actually done via the /sys/class/gpio interface regardless of
938  *      the wiringPi access mode in-use. Maybe sometime it might get a better
939  *      way for a bit more efficiency.
940  *********************************************************************************
941  */
942
943 int waitForInterruptSys (int pin, int mS)
944 {
945   int fd, x ;
946   uint8_t c ;
947   struct pollfd polls ;
948
949   if ((fd = sysFds [pin & 63]) == -1)
950     return -2 ;
951
952 // Setup poll structure
953
954   polls.fd     = fd ;
955   polls.events = POLLPRI ;      // Urgent data!
956
957 // Wait for it ...
958
959   x = poll (&polls, 1, mS) ;
960
961 // Do a dummy read to clear the interrupt
962 //      A one character read appars to be enough.
963
964   (void)read (fd, &c, 1) ;
965
966   return x ;
967 }
968
969 int waitForInterruptWPi (int pin, int mS)
970 {
971   return waitForInterruptSys (pinToGpio [pin & 63], mS) ;
972 }
973
974 int waitForInterruptGpio (int pin, int mS)
975 {
976   return waitForInterruptSys (pin, mS) ;
977 }
978
979
980 /*
981  * interruptHandler:
982  *      This is a thread and gets started to wait for the interrupt we're
983  *      hoping to catch. It will call the user-function when the interrupt
984  *      fires.
985  *********************************************************************************
986  */
987
988 static void *interruptHandler (void *arg)
989 {
990   int myPin = *(int *)arg ;
991
992   (void)piHiPri (55) ;  // Only effective if we run as root
993
994   for (;;)
995     if (waitForInterruptSys (myPin, -1) > 0)
996       isrFunctions [myPin] () ;
997
998   return NULL ;
999 }
1000
1001
1002 /*
1003  * wiringPiISR:
1004  *      Take the details and create an interrupt handler that will do a call-
1005  *      back to the user supplied function.
1006  *********************************************************************************
1007  */
1008
1009 int wiringPiISR (int pin, int mode, void (*function)(void))
1010 {
1011   pthread_t threadId ;
1012   char fName   [64] ;
1013   char *modeS ;
1014   char  pinS [8] ;
1015   pid_t pid ;
1016   int   count, i ;
1017   uint8_t c ;
1018
1019   pin &= 63 ;
1020
1021   if (wiringPiMode == WPI_MODE_UNINITIALISED)
1022   {
1023     fprintf (stderr, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
1024     exit (EXIT_FAILURE) ;
1025   }
1026   else if (wiringPiMode == WPI_MODE_PINS)
1027     pin = pinToGpio [pin] ;
1028
1029 // Now export the pin and set the right edge
1030 //      We're going to use the gpio program to do this, so it assumes
1031 //      a full installation of wiringPi. It's a bit 'clunky', but it
1032 //      is a way that will work when we're running in "Sys" mode, as
1033 //      a non-root user. (without sudo)
1034
1035   if (mode != INT_EDGE_SETUP)
1036   {
1037     /**/ if (mode == INT_EDGE_FALLING)
1038       modeS = "falling" ;
1039     else if (mode == INT_EDGE_RISING)
1040       modeS = "rising" ;
1041     else
1042       modeS = "both" ;
1043
1044     sprintf (pinS, "%d", pin) ;
1045
1046     if ((pid = fork ()) < 0)    // Fail
1047       return pid ;
1048
1049     if (pid == 0)       // Child, exec
1050     {
1051       execl ("/usr/local/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
1052       return -1 ;       // Failure ...
1053     }
1054     else                // Parent, wait
1055       wait (NULL) ;
1056   }
1057
1058 // Now pre-open the /sys/class node - it may already be open if
1059 //      we are in Sys mode, but this will do no harm.
1060
1061   sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1062   if ((sysFds [pin] = open (fName, O_RDWR)) < 0)
1063     return -1 ;
1064
1065 // Clear any initial pending interrupt
1066
1067   ioctl (sysFds [pin], FIONREAD, &count) ;
1068   for (i = 0 ; i < count ; ++i)
1069     read (sysFds [pin], &c, 1) ;
1070
1071   isrFunctions [pin] = function ;
1072
1073   pthread_create (&threadId, NULL, interruptHandler, &pin) ;
1074
1075   delay (1) ;
1076
1077   return 0 ;
1078 }
1079
1080
1081 /*
1082  * initialiseEpoch:
1083  *      Initialise our start-of-time variable to be the current unix
1084  *      time in milliseconds.
1085  *********************************************************************************
1086  */
1087
1088 static void initialiseEpoch (void)
1089 {
1090   struct timeval tv ;
1091
1092   gettimeofday (&tv, NULL) ;
1093   epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000    + (uint64_t)(tv.tv_usec / 1000) ;
1094   epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
1095 }
1096
1097 /*
1098  * delay:
1099  *      Wait for some number of milli seconds
1100  *********************************************************************************
1101  */
1102
1103 void delay (unsigned int howLong)
1104 {
1105   struct timespec sleeper, dummy ;
1106
1107   sleeper.tv_sec  = (time_t)(howLong / 1000) ;
1108   sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
1109
1110   nanosleep (&sleeper, &dummy) ;
1111 }
1112
1113
1114 /*
1115  * delayMicroseconds:
1116  *      This is somewhat intersting. It seems that on the Pi, a single call
1117  *      to nanosleep takes some 80 to 130 microseconds anyway, so while
1118  *      obeying the standards (may take longer), it's not always what we
1119  *      want!
1120  *
1121  *      So what I'll do now is if the delay is less than 100uS we'll do it
1122  *      in a hard loop, watching a built-in counter on the ARM chip. This is
1123  *      somewhat sub-optimal in that it uses 100% CPU, something not an issue
1124  *      in a microcontroller, but under a multi-tasking, multi-user OS, it's
1125  *      wastefull, however we've no real choice )-:
1126  *
1127  *      Plan B: It seems all might not be well with that plan, so changing it
1128  *      to use gettimeofday () and poll on that instead...
1129  *********************************************************************************
1130  */
1131
1132 void delayMicrosecondsHard (unsigned int howLong)
1133 {
1134   struct timeval tNow, tLong, tEnd ;
1135
1136   gettimeofday (&tNow, NULL) ;
1137   tLong.tv_sec  = howLong / 1000000 ;
1138   tLong.tv_usec = howLong % 1000000 ;
1139   timeradd (&tNow, &tLong, &tEnd) ;
1140
1141   while (timercmp (&tNow, &tEnd, <))
1142     gettimeofday (&tNow, NULL) ;
1143 }
1144
1145 void delayMicroseconds (unsigned int howLong)
1146 {
1147   struct timespec sleeper ;
1148
1149   /**/ if (howLong ==   0)
1150     return ;
1151   else if (howLong  < 100)
1152     delayMicrosecondsHard (howLong) ;
1153   else
1154   {
1155     sleeper.tv_sec  = 0 ;
1156     sleeper.tv_nsec = (long)(howLong * 1000) ;
1157     nanosleep (&sleeper, NULL) ;
1158   }
1159 }
1160
1161
1162 /*
1163  * millis:
1164  *      Return a number of milliseconds as an unsigned int.
1165  *********************************************************************************
1166  */
1167
1168 unsigned int millis (void)
1169 {
1170   struct timeval tv ;
1171   uint64_t now ;
1172
1173   gettimeofday (&tv, NULL) ;
1174   now  = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
1175
1176   return (uint32_t)(now - epochMilli) ;
1177 }
1178
1179
1180 /*
1181  * micros:
1182  *      Return a number of microseconds as an unsigned int.
1183  *********************************************************************************
1184  */
1185
1186 unsigned int micros (void)
1187 {
1188   struct timeval tv ;
1189   uint64_t now ;
1190
1191   gettimeofday (&tv, NULL) ;
1192   now  = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
1193
1194   return (uint32_t)(now - epochMicro) ;
1195 }
1196
1197
1198 /*
1199  * wiringPiSetup:
1200  *      Must be called once at the start of your program execution.
1201  *
1202  * Default setup: Initialises the system into wiringPi Pin mode and uses the
1203  *      memory mapped hardware directly.
1204  *********************************************************************************
1205  */
1206
1207 int wiringPiSetup (void)
1208 {
1209   int      fd ;
1210   int      boardRev ;
1211
1212   if (geteuid () != 0)
1213   {
1214     fprintf (stderr, "wiringPi:\n  Must be root to call wiringPiSetup().\n  (Did you forget sudo?)\n") ;
1215     exit (EXIT_FAILURE) ;
1216   }
1217
1218   if (getenv ("WIRINGPI_DEBUG") != NULL)
1219   {
1220     printf ("wiringPi: Debug mode enabled\n") ;
1221     wiringPiDebug = TRUE ;
1222   }
1223
1224   if (wiringPiDebug)
1225     printf ("wiringPi: wiringPiSetup called\n") ;
1226
1227             pinMode =           pinModeWPi ;
1228              getAlt =            getAltWPi ;
1229     pullUpDnControl =   pullUpDnControlWPi ;
1230        digitalWrite =      digitalWriteWPi ;
1231    digitalWriteByte = digitalWriteByteGpio ;    // Same code
1232            pwmWrite =          pwmWriteWPi ;
1233         setPadDrive =       setPadDriveWPi ;
1234         digitalRead =       digitalReadWPi ;
1235    waitForInterrupt =  waitForInterruptWPi ;
1236          pwmSetMode =        pwmSetModeWPi ;
1237         pwmSetRange =       pwmSetRangeWPi ;
1238         pwmSetClock =       pwmSetClockWPi ;
1239   
1240   boardRev = piBoardRev () ;
1241
1242   if (boardRev == 1)
1243     pinToGpio = pinToGpioR1 ;
1244   else
1245     pinToGpio = pinToGpioR2 ;
1246
1247 // Open the master /dev/memory device
1248
1249   if ((fd = open ("/dev/mem", O_RDWR | O_SYNC) ) < 0)
1250   {
1251     if (wiringPiDebug)
1252     {
1253       int serr = errno ;
1254         fprintf (stderr, "wiringPiSetup: Unable to open /dev/mem: %s\n", strerror (errno)) ;
1255       errno = serr ;
1256     }
1257     return -1 ;
1258   }
1259
1260 // GPIO:
1261
1262   gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
1263   if ((int32_t)gpio == -1)
1264   {
1265     if (wiringPiDebug)
1266     {
1267       int serr = errno ;
1268         fprintf (stderr, "wiringPiSetup: mmap failed: %s\n", strerror (errno)) ;
1269       errno = serr ;
1270     }
1271     return -1 ;
1272   }
1273
1274 // PWM
1275
1276   pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
1277   if ((int32_t)pwm == -1)
1278   {
1279     if (wiringPiDebug)
1280     {
1281       int serr = errno ;
1282         fprintf (stderr, "wiringPiSetup: mmap failed (pwm): %s\n", strerror (errno)) ;
1283       errno = serr ;
1284     }
1285     return -1 ;
1286   }
1287  
1288 // Clock control (needed for PWM)
1289
1290   clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, CLOCK_BASE) ;
1291   if ((int32_t)clk == -1)
1292   {
1293     if (wiringPiDebug)
1294     {
1295       int serr = errno ;
1296         fprintf (stderr, "wiringPiSetup: mmap failed (clk): %s\n", strerror (errno)) ;
1297       errno = serr ;
1298     }
1299     return -1 ;
1300   }
1301  
1302 // The drive pads
1303
1304   pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
1305   if ((int32_t)pads == -1)
1306   {
1307     if (wiringPiDebug)
1308     {
1309       int serr = errno ;
1310         fprintf (stderr, "wiringPiSetup: mmap failed (pads): %s\n", strerror (errno)) ;
1311       errno = serr ;
1312     }
1313     return -1 ;
1314   }
1315
1316 // The system timer
1317
1318   timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
1319   if ((int32_t)timer == -1)
1320   {
1321     if (wiringPiDebug)
1322     {
1323       int serr = errno ;
1324         fprintf (stderr, "wiringPiSetup: mmap failed (timer): %s\n", strerror (errno)) ;
1325       errno = serr ;
1326     }
1327     return -1 ;
1328   }
1329
1330 // Set the timer to free-running, 1MHz.
1331 //      0xF9 is 249, the timer divide is base clock / (divide+1)
1332 //      so base clock is 250MHz / 250 = 1MHz.
1333
1334   *(timer + TIMER_CONTROL) = 0x0000280 ;
1335   *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
1336   timerIrqRaw = timer + TIMER_IRQ_RAW ;
1337
1338   initialiseEpoch () ;
1339
1340   wiringPiMode = WPI_MODE_PINS ;
1341
1342   return 0 ;
1343 }
1344
1345
1346 /*
1347  * wiringPiSetupGpio:
1348  *      Must be called once at the start of your program execution.
1349  *
1350  * GPIO setup: Initialises the system into GPIO Pin mode and uses the
1351  *      memory mapped hardware directly.
1352  *********************************************************************************
1353  */
1354
1355 int wiringPiSetupGpio (void)
1356 {
1357   int x  ;
1358
1359   if (geteuid () != 0)
1360   {
1361     fprintf (stderr, "Must be root to call wiringPiSetupGpio(). (Did you forget sudo?)\n") ;
1362     exit (EXIT_FAILURE) ;
1363   }
1364
1365   if ((x = wiringPiSetup ()) < 0)
1366     return x ;
1367
1368   if (wiringPiDebug)
1369     printf ("wiringPi: wiringPiSetupGpio called\n") ;
1370
1371             pinMode =           pinModeGpio ;
1372              getAlt =            getAltGpio ;
1373     pullUpDnControl =   pullUpDnControlGpio ;
1374        digitalWrite =      digitalWriteGpio ;
1375    digitalWriteByte =  digitalWriteByteGpio ;
1376            pwmWrite =          pwmWriteGpio ;
1377         setPadDrive =       setPadDriveGpio ;
1378         digitalRead =       digitalReadGpio ;
1379    waitForInterrupt =  waitForInterruptGpio ;
1380          pwmSetMode =        pwmSetModeWPi ;
1381         pwmSetRange =       pwmSetRangeWPi ;
1382         pwmSetClock =       pwmSetClockWPi ;
1383
1384   wiringPiMode = WPI_MODE_GPIO ;
1385
1386   return 0 ;
1387 }
1388
1389
1390 /*
1391  * wiringPiSetupSys:
1392  *      Must be called once at the start of your program execution.
1393  *
1394  * Initialisation (again), however this time we are using the /sys/class/gpio
1395  *      interface to the GPIO systems - slightly slower, but always usable as
1396  *      a non-root user, assuming the devices are already exported and setup correctly.
1397  */
1398
1399 int wiringPiSetupSys (void)
1400 {
1401   int boardRev ;
1402   int pin ;
1403   char fName [128] ;
1404
1405   if (getenv ("WIRINGPI_DEBUG") != NULL)
1406     wiringPiDebug = TRUE ;
1407
1408   if (wiringPiDebug)
1409     printf ("wiringPi: wiringPiSetupSys called\n") ;
1410
1411             pinMode =           pinModeSys ;
1412              getAlt =            getAltSys ;
1413     pullUpDnControl =   pullUpDnControlSys ;
1414        digitalWrite =      digitalWriteSys ;
1415    digitalWriteByte =  digitalWriteByteSys ;
1416            pwmWrite =          pwmWriteSys ;
1417         setPadDrive =       setPadDriveSys ;
1418         digitalRead =       digitalReadSys ;
1419    waitForInterrupt =  waitForInterruptSys ;
1420          pwmSetMode =        pwmSetModeSys ;
1421         pwmSetRange =       pwmSetRangeSys ;
1422         pwmSetClock =       pwmSetClockSys ;
1423
1424   boardRev = piBoardRev () ;
1425
1426   if (boardRev == 1)
1427     pinToGpio = pinToGpioR1 ;
1428   else
1429     pinToGpio = pinToGpioR2 ;
1430
1431 // Open and scan the directory, looking for exported GPIOs, and pre-open
1432 //      the 'value' interface to speed things up for later
1433   
1434   for (pin = 0 ; pin < 64 ; ++pin)
1435   {
1436     sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1437     sysFds [pin] = open (fName, O_RDWR) ;
1438   }
1439
1440   initialiseEpoch () ;
1441
1442   wiringPiMode = WPI_MODE_GPIO_SYS ;
1443
1444   return 0 ;
1445 }