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