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