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