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