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