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>
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/
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.
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.
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 ***********************************************************************
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
36 // Added waitForInterrupt code
40 // Added in support to use the /sys/class/gpio interface.
42 // Fixed a few more bugs to do with range-checking when in GPIO mode.
45 // Added c++ support for the .h file
46 // Added a new function to allow for using my "pin" numbers, or native
48 // Removed my busy-loop delay and replaced it with a call to delayMicroseconds
51 // Added in the 2 UART pins
52 // Change maxPins to numPins to more accurately reflect purpose
70 #include <sys/ioctl.h>
76 void (*pinMode) (int pin, int mode) ;
77 int (*getAlt) (int pin) ;
78 void (*pullUpDnControl) (int pin, int pud) ;
79 void (*digitalWrite) (int pin, int value) ;
80 void (*digitalWriteByte) (int value) ;
81 void (*pwmWrite) (int pin, int value) ;
82 void (*gpioClockSet) (int pin, int value) ;
83 void (*setPadDrive) (int group, int value) ;
84 int (*digitalRead) (int pin) ;
85 int (*waitForInterrupt) (int pin, int mS) ;
86 void (*pwmSetMode) (int mode) ;
87 void (*pwmSetRange) (unsigned int range) ;
88 void (*pwmSetClock) (int divisor) ;
98 #define BCM_PASSWORD 0x5A000000
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
105 // Each control register has 10 sets of 3 bits per GPIO pin - the ALT values
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
116 // So the 3 bits for port X are:
117 // X / 10 + ((X % 10) * 3)
119 // Port function select bits
121 #define FSEL_INPT 0b000
122 #define FSEL_OUTP 0b001
123 #define FSEL_ALT0 0b100
124 #define FSEL_ALT0 0b100
125 #define FSEL_ALT1 0b101
126 #define FSEL_ALT2 0b110
127 #define FSEL_ALT3 0b111
128 #define FSEL_ALT4 0b011
129 #define FSEL_ALT5 0b010
131 // Access from ARM Running Linux
132 // Taken from Gert/Doms code. Some of this is not in the manual
133 // that I can find )-:
135 #define BCM2708_PERI_BASE 0x20000000
136 #define GPIO_PADS (BCM2708_PERI_BASE + 0x00100000)
137 #define CLOCK_BASE (BCM2708_PERI_BASE + 0x00101000)
138 #define GPIO_BASE (BCM2708_PERI_BASE + 0x00200000)
139 #define GPIO_TIMER (BCM2708_PERI_BASE + 0x0000B000)
140 #define GPIO_PWM (BCM2708_PERI_BASE + 0x0020C000)
142 #define PAGE_SIZE (4*1024)
143 #define BLOCK_SIZE (4*1024)
146 // Word offsets into the PWM control region
148 #define PWM_CONTROL 0
155 // Clock regsiter offsets
157 #define PWMCLK_CNTL 40
158 #define PWMCLK_DIV 41
160 #define PWM0_MS_MODE 0x0080 // Run in MS mode
161 #define PWM0_USEFIFO 0x0020 // Data from FIFO
162 #define PWM0_REVPOLAR 0x0010 // Reverse polarity
163 #define PWM0_OFFSTATE 0x0008 // Ouput Off state
164 #define PWM0_REPEATFF 0x0004 // Repeat last value if FIFO empty
165 #define PWM0_SERIAL 0x0002 // Run in serial mode
166 #define PWM0_ENABLE 0x0001 // Channel Enable
168 #define PWM1_MS_MODE 0x8000 // Run in MS mode
169 #define PWM1_USEFIFO 0x2000 // Data from FIFO
170 #define PWM1_REVPOLAR 0x1000 // Reverse polarity
171 #define PWM1_OFFSTATE 0x0800 // Ouput Off state
172 #define PWM1_REPEATFF 0x0400 // Repeat last value if FIFO empty
173 #define PWM1_SERIAL 0x0200 // Run in serial mode
174 #define PWM1_ENABLE 0x0100 // Channel Enable
179 #define TIMER_LOAD (0x400 >> 2)
180 #define TIMER_VALUE (0x404 >> 2)
181 #define TIMER_CONTROL (0x408 >> 2)
182 #define TIMER_IRQ_CLR (0x40C >> 2)
183 #define TIMER_IRQ_RAW (0x410 >> 2)
184 #define TIMER_IRQ_MASK (0x414 >> 2)
185 #define TIMER_RELOAD (0x418 >> 2)
186 #define TIMER_PRE_DIV (0x41C >> 2)
187 #define TIMER_COUNTER (0x420 >> 2)
189 // Locals to hold pointers to the hardware
191 static volatile uint32_t *gpio ;
192 static volatile uint32_t *pwm ;
193 static volatile uint32_t *clk ;
194 static volatile uint32_t *pads ;
195 static volatile uint32_t *timer ;
196 static volatile uint32_t *timerIrqRaw ;
198 // Time for easy calculations
200 static uint64_t epochMilli, epochMicro ;
204 static int wiringPiMode = WPI_MODE_UNINITIALISED ;
208 int wiringPiDebug = FALSE ;
211 // Map a file descriptor from the /sys/class/gpio/gpioX/value
213 static int sysFds [64] ;
217 static void (*isrFunctions [64])(void) ;
220 // Doing it the Arduino way with lookup tables...
221 // Yes, it's probably more innefficient than all the bit-twidling, but it
222 // does tend to make it all a bit clearer. At least to me!
225 // Take a Wiring pin (0 through X) and re-map it to the BCM_GPIO pin
226 // Cope for 2 different board revieions here
228 static int *pinToGpio ;
230 static int pinToGpioR1 [64] =
232 17, 18, 21, 22, 23, 24, 25, 4, // From the Original Wiki - GPIO 0 through 7
233 0, 1, // I2C - SDA0, SCL0
234 8, 7, // SPI - CE1, CE0
235 10, 9, 11, // SPI - MOSI, MISO, SCLK
236 14, 15, // UART - Tx, Rx
240 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 31
241 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 47
242 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 63
245 static int pinToGpioR2 [64] =
247 17, 18, 27, 22, 23, 24, 25, 4, // From the Original Wiki - GPIO 0 through 7: wpi 0 - 7
248 2, 3, // I2C - SDA0, SCL0 wpi 8 - 9
249 8, 7, // SPI - CE1, CE0 wpi 10 - 11
250 10, 9, 11, // SPI - MOSI, MISO, SCLK wpi 12 - 14
251 14, 15, // UART - Tx, Rx wpi 15 - 16
252 28, 29, 30, 31, // New GPIOs 8 though 11 wpi 17 - 20
256 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 31
257 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 47
258 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 63
263 // Map a BCM_GPIO pin to it's control port. (GPFSEL 0-5)
265 static uint8_t gpioToGPFSEL [] =
267 0,0,0,0,0,0,0,0,0,0,
268 1,1,1,1,1,1,1,1,1,1,
269 2,2,2,2,2,2,2,2,2,2,
270 3,3,3,3,3,3,3,3,3,3,
271 4,4,4,4,4,4,4,4,4,4,
272 5,5,5,5,5,5,5,5,5,5,
277 // Define the shift up for the 3 bits per pin in each GPFSEL port
279 static uint8_t gpioToShift [] =
281 0,3,6,9,12,15,18,21,24,27,
282 0,3,6,9,12,15,18,21,24,27,
283 0,3,6,9,12,15,18,21,24,27,
284 0,3,6,9,12,15,18,21,24,27,
285 0,3,6,9,12,15,18,21,24,27,
290 // (Word) offset to the GPIO Set registers for each GPIO pin
292 static uint8_t gpioToGPSET [] =
294 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
295 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
300 // (Word) offset to the GPIO Clear registers for each GPIO pin
302 static uint8_t gpioToGPCLR [] =
304 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
305 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
310 // (Word) offset to the GPIO Input level registers for each GPIO pin
312 static uint8_t gpioToGPLEV [] =
314 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
315 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
321 // (Word) offset to the Event Detect Status
323 static uint8_t gpioToEDS [] =
325 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
326 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
330 // (Word) offset to the Rising edgde ENable register
332 static uint8_t gpioToREN [] =
334 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
335 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
339 // (Word) offset to the Falling edgde ENable register
341 static uint8_t gpioToFEN [] =
343 22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,
344 23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,
350 // GPIO Pin pull up/down register
355 // (Word) offset to the Pull Up Down Clock regsiter
357 static uint8_t gpioToPUDCLK [] =
359 38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,
360 39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,
365 // the ALT value to put a GPIO pin into PWM mode
367 static uint8_t gpioToPwmALT [] =
369 0, 0, 0, 0, 0, 0, 0, 0, // 0 -> 7
370 0, 0, 0, 0, FSEL_ALT0, FSEL_ALT0, 0, 0, // 8 -> 15
371 0, 0, FSEL_ALT5, FSEL_ALT5, 0, 0, 0, 0, // 16 -> 23
372 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
373 0, 0, 0, 0, 0, 0, 0, 0, // 32 -> 39
374 FSEL_ALT0, FSEL_ALT0, 0, 0, 0, FSEL_ALT0, 0, 0, // 40 -> 47
375 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
376 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
380 // The port value to put a GPIO pin into PWM mode
382 static uint8_t gpioToPwmPort [] =
384 0, 0, 0, 0, 0, 0, 0, 0, // 0 -> 7
385 0, 0, 0, 0, PWM0_DATA, PWM1_DATA, 0, 0, // 8 -> 15
386 0, 0, PWM0_DATA, PWM1_DATA, 0, 0, 0, 0, // 16 -> 23
387 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
388 0, 0, 0, 0, 0, 0, 0, 0, // 32 -> 39
389 PWM0_DATA, PWM1_DATA, 0, 0, 0, PWM1_DATA, 0, 0, // 40 -> 47
390 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
391 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
396 // ALT value to put a GPIO pin into GP Clock mode.
397 // On the Pi we can really only use BCM_GPIO_4 and BCM_GPIO_21
398 // for clocks 0 and 1 respectivey, however I'll include the full
399 // list for completeness - maybe one day...
401 #define GPIO_CLOCK_SOURCE 1
405 static uint8_t gpioToGpClkALT0 [] =
407 0, 0, 0, 0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0, 0, // 0 -> 7
408 0, 0, 0, 0, 0, 0, 0, 0, // 8 -> 15
409 0, 0, 0, 0, FSEL_ALT5, FSEL_ALT5, 0, 0, // 16 -> 23
410 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
411 FSEL_ALT0, 0, FSEL_ALT0, 0, 0, 0, 0, 0, // 32 -> 39
412 0, 0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0, 0, 0, 0, // 40 -> 47
413 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
414 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
418 // (word) Offsets to the clock Control and Divisor register
420 static uint8_t gpioToClkCon [] =
422 -1, -1, -1, -1, 28, 30, 32, -1, // 0 -> 7
423 -1, -1, -1, -1, -1, -1, -1, -1, // 8 -> 15
424 -1, -1, -1, -1, 28, 30, -1, -1, // 16 -> 23
425 -1, -1, -1, -1, -1, -1, -1, -1, // 24 -> 31
426 28, -1, 28, -1, -1, -1, -1, -1, // 32 -> 39
427 -1, -1, 28, 30, 28, -1, -1, -1, // 40 -> 47
428 -1, -1, -1, -1, -1, -1, -1, -1, // 48 -> 55
429 -1, -1, -1, -1, -1, -1, -1, -1, // 56 -> 63
432 static uint8_t gpioToClkDiv [] =
434 -1, -1, -1, -1, 29, 31, 33, -1, // 0 -> 7
435 -1, -1, -1, -1, -1, -1, -1, -1, // 8 -> 15
436 -1, -1, -1, -1, 29, 31, -1, -1, // 16 -> 23
437 -1, -1, -1, -1, -1, -1, -1, -1, // 24 -> 31
438 29, -1, 29, -1, -1, -1, -1, -1, // 32 -> 39
439 -1, -1, 29, 31, 29, -1, -1, -1, // 40 -> 47
440 -1, -1, -1, -1, -1, -1, -1, -1, // 48 -> 55
441 -1, -1, -1, -1, -1, -1, -1, -1, // 56 -> 63
447 *********************************************************************************
453 * Translate a wiringPi Pin number to native GPIO pin number.
454 * (We don't use this here, prefering to just do the lookup directly,
455 * but it's been requested!)
456 *********************************************************************************
459 int wpiPinToGpio (int wpiPin)
461 return pinToGpio [wpiPin & 63] ;
467 * Return a number representing the hardware revision of the board.
468 * Revision is currently 1 or 2. -1 is returned on error.
470 * Much confusion here )-:
471 * Seems there are some boards with 0000 in them (mistake in manufacture)
472 * and some board with 0005 in them (another mistake in manufacture?)
473 * So the distinction between boards that I can see is:
478 * 0004 - Rev 2 (Early reports?
479 * 0005 - Rev 2 (but error?)
481 * 0008 - Rev 2 - Model A
482 * 000e - Rev 2 + 512MB
483 * 000f - Rev 2 + 512MB
485 * A small thorn is the olde style overvolting - that will add in
488 *********************************************************************************
491 static void piBoardRevOops (char *why)
493 fprintf (stderr, "piBoardRev: Unable to determine board revision from /proc/cpuinfo\n") ;
494 fprintf (stderr, " -> %s\n", why) ;
495 fprintf (stderr, " -> You may want to check:\n") ;
496 fprintf (stderr, " -> http://www.raspberrypi.org/phpBB3/viewtopic.php?p=184410#p184410\n") ;
497 exit (EXIT_FAILURE) ;
500 int piBoardRev (void)
505 static int boardRev = -1 ;
507 if (boardRev != -1) // No point checking twice
510 if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
511 piBoardRevOops ("Unable to open /proc/cpuinfo") ;
513 while (fgets (line, 120, cpuFd) != NULL)
514 if (strncmp (line, "Revision", 8) == 0)
519 if (strncmp (line, "Revision", 8) != 0)
520 piBoardRevOops ("No \"Revision\" line") ;
522 for (c = &line [strlen (line) - 1] ; (*c == '\n') || (*c == '\r') ; --c)
526 printf ("piboardRev: Revision string: %s\n", line) ;
528 for (c = line ; *c ; ++c)
533 piBoardRevOops ("No numeric revision string") ;
535 // If you have overvolted the Pi, then it appears that the revision
536 // has 100000 added to it!
540 printf ("piboardRev: This Pi has/is overvolted!\n") ;
542 lastChar = line [strlen (line) - 1] ;
545 printf ("piboardRev: lastChar is: '%c' (%d, 0x%02X)\n", lastChar, lastChar, lastChar) ;
547 /**/ if ((lastChar == '2') || (lastChar == '3'))
553 printf ("piBoardRev: Returning revision: %d\n", boardRev) ;
562 * Returns the ALT bits for a given port. Only really of-use
563 * for the gpio readall command (I think)
564 *********************************************************************************
567 int getAltGpio (int pin)
569 int fSel, shift, alt ;
573 fSel = gpioToGPFSEL [pin] ;
574 shift = gpioToShift [pin] ;
576 alt = (*(gpio + fSel) >> shift) & 7 ;
581 int getAltWPi (int pin)
583 return getAltGpio (pinToGpio [pin & 63]) ;
586 int getAltSys (int pin)
594 * Allow the user to control some of the PWM functions
595 *********************************************************************************
598 void pwmSetModeWPi (int mode)
600 if (mode == PWM_MODE_MS)
601 *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
603 *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
606 void pwmSetModeSys (int mode)
612 void pwmSetRangeWPi (unsigned int range)
614 *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
615 *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
618 void pwmSetRangeSys (unsigned int range)
625 * Set/Change the PWM clock. Originally my code, but changed
626 * (for the better!) by Chris Hall, <chris@kchall.plus.com>
627 * after further study of the manual and testing with a 'scope
628 *********************************************************************************
631 void pwmSetClockWPi (int divisor)
633 uint32_t pwm_control ;
637 printf ("Setting to: %d. Current: 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
639 pwm_control = *(pwm + PWM_CONTROL) ; // preserve PWM_CONTROL
641 // We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
644 *(pwm + PWM_CONTROL) = 0 ; // Stop PWM
646 // Stop PWM clock before changing divisor. The delay after this does need to
647 // this big (95uS occasionally fails, 100uS OK), it's almost as though the BUSY
648 // flag is not working properly in balanced mode. Without the delay when DIV is
649 // adjusted the clock sometimes switches to very slow, once slow further DIV
650 // adjustments do nothing and it's difficult to get out of this mode.
652 *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ; // Stop PWM Clock
653 delayMicroseconds (110) ; // prevents clock going sloooow
655 while ((*(clk + PWMCLK_CNTL) & 0x80) != 0) // Wait for clock to be !BUSY
656 delayMicroseconds (1) ;
658 *(clk + PWMCLK_DIV) = BCM_PASSWORD | (divisor << 12) ;
660 *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ; // Start PWM clock
661 *(pwm + PWM_CONTROL) = pwm_control ; // restore PWM_CONTROL
664 printf ("Set to: %d. Now : 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
667 void pwmSetClockSys (int divisor)
677 * Enables edge-detect mode on a pin - from a 0 to a 1 or 1 to 0
678 * Pin must already be in input mode with appropriate pull up/downs set.
679 *********************************************************************************
682 void pinEnableED01Pi (int pin)
684 pin = pinToGpio [pin & 63] ;
693 *********************************************************************************
696 void digitalWriteWPi (int pin, int value)
698 pin = pinToGpio [pin & 63] ;
701 *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
703 *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
706 void digitalWriteGpio (int pin, int value)
711 *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
713 *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
716 void digitalWriteSys (int pin, int value)
720 if (sysFds [pin] != -1)
723 write (sysFds [pin], "0\n", 2) ;
725 write (sysFds [pin], "1\n", 2) ;
732 * Write an 8-bit byte to the first 8 GPIO pins - try to do it as
734 * However it still needs 2 operations to set the bits, so any external
735 * hardware must not rely on seeing a change as there will be a change
736 * to set the outputs bits to zero, then another change to set the 1's
737 *********************************************************************************
740 void digitalWriteByteGpio (int value)
742 uint32_t pinSet = 0 ;
743 uint32_t pinClr = 0 ;
747 for (pin = 0 ; pin < 8 ; ++pin)
749 if ((value & mask) == 0)
750 pinClr |= (1 << pinToGpio [pin]) ;
752 pinSet |= (1 << pinToGpio [pin]) ;
757 *(gpio + gpioToGPCLR [0]) = pinClr ;
758 *(gpio + gpioToGPSET [0]) = pinSet ;
761 void digitalWriteByteSys (int value)
766 for (pin = 0 ; pin < 8 ; ++pin)
768 digitalWriteSys (pinToGpio [pin], value & mask) ;
776 * Set an output PWM value
777 *********************************************************************************
780 void pwmWriteGpio (int pin, int value)
785 port = gpioToPwmPort [pin] ;
787 *(pwm + port) = value ;
790 void pwmWriteWPi (int pin, int value)
792 pwmWriteGpio (pinToGpio [pin & 63], value) ;
795 void pwmWriteSys (int pin, int value)
803 * Set the freuency on a GPIO clock pin
804 *********************************************************************************
807 void gpioClockSetGpio (int pin, int freq)
809 int divi, divr, divf ;
813 divi = 19200000 / freq ;
814 divr = 19200000 % freq ;
815 divf = (int)((double)divr * 4096.0 / 19200000.0) ;
820 *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | GPIO_CLOCK_SOURCE ; // Stop GPIO Clock
821 while ((*(clk + gpioToClkCon [pin]) & 0x80) != 0) // ... and wait
824 *(clk + gpioToClkDiv [pin]) = BCM_PASSWORD | (divi << 12) | divf ; // Set dividers
825 *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | 0x10 | GPIO_CLOCK_SOURCE ; // Start Clock
828 void gpioClockSetWPi (int pin, int freq)
830 gpioClockSetGpio (pinToGpio [pin & 63], freq) ;
833 void gpioClockSetSys (int pin, int freq)
841 * Set the PAD driver value
842 *********************************************************************************
845 void setPadDriveWPi (int group, int value)
849 if ((group < 0) || (group > 2))
852 wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
853 *(pads + group + 11) = wrVal ;
857 printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
858 printf ("Read : %08X\n", *(pads + group + 11)) ;
862 void setPadDriveGpio (int group, int value)
864 setPadDriveWPi (group, value) ;
867 void setPadDriveSys (int group, int value)
875 * Read the value of a given Pin, returning HIGH or LOW
876 *********************************************************************************
879 int digitalReadWPi (int pin)
881 pin = pinToGpio [pin & 63] ;
883 if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
889 int digitalReadGpio (int pin)
893 if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
899 int digitalReadSys (int pin)
905 if (sysFds [pin] == -1)
908 lseek (sysFds [pin], 0L, SEEK_SET) ;
909 read (sysFds [pin], &c, 1) ;
910 return (c == '0') ? 0 : 1 ;
916 * Control the internal pull-up/down resistors on a GPIO pin
917 * The Arduino only has pull-ups and these are enabled by writing 1
918 * to a port when in input mode - this paradigm doesn't quite apply
920 *********************************************************************************
923 void pullUpDnControlGpio (int pin, int pud)
928 *(gpio + GPPUD) = pud ; delayMicroseconds (5) ;
929 *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ; delayMicroseconds (5) ;
931 *(gpio + GPPUD) = 0 ; delayMicroseconds (5) ;
932 *(gpio + gpioToPUDCLK [pin]) = 0 ; delayMicroseconds (5) ;
935 void pullUpDnControlWPi (int pin, int pud)
937 pullUpDnControlGpio (pinToGpio [pin & 63], pud) ;
940 void pullUpDnControlSys (int pin, int pud)
948 * Sets the mode of a pin to be input, output or PWM output
949 *********************************************************************************
952 void pinModeGpio (int pin, int mode)
954 // register int barrier ;
956 int fSel, shift, alt ;
960 fSel = gpioToGPFSEL [pin] ;
961 shift = gpioToShift [pin] ;
963 /**/ if (mode == INPUT)
964 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
965 else if (mode == OUTPUT)
966 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
967 else if (mode == PWM_OUTPUT)
969 if ((alt = gpioToPwmALT [pin]) == 0) // Not a PWM pin
972 // Set pin to PWM mode
974 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
975 delayMicroseconds (110) ; // See comments in pwmSetClockWPi
977 pwmSetModeWPi (PWM_MODE_BAL) ; // Pi default mode
978 pwmSetRangeWPi (1024) ; // Default range of 1024
979 pwmSetClockWPi (32) ; // 19.2 / 32 = 600KHz - Also starts the PWM
981 else if (mode == GPIO_CLOCK)
983 if ((alt = gpioToGpClkALT0 [pin]) == 0) // Not a GPIO_CLOCK pin
986 // Set pin to GPIO_CLOCK mode and set the clock frequency to 100KHz
988 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
989 delayMicroseconds (110) ;
990 gpioClockSetGpio (pin, 100000) ;
994 void pinModeWPi (int pin, int mode)
996 pinModeGpio (pinToGpio [pin & 63], mode) ;
999 void pinModeSys (int pin, int mode)
1007 * Wait for Interrupt on a GPIO pin.
1008 * This is actually done via the /sys/class/gpio interface regardless of
1009 * the wiringPi access mode in-use. Maybe sometime it might get a better
1010 * way for a bit more efficiency.
1011 *********************************************************************************
1014 int waitForInterruptSys (int pin, int mS)
1018 struct pollfd polls ;
1020 if ((fd = sysFds [pin & 63]) == -1)
1023 // Setup poll structure
1026 polls.events = POLLPRI ; // Urgent data!
1030 x = poll (&polls, 1, mS) ;
1032 // Do a dummy read to clear the interrupt
1033 // A one character read appars to be enough.
1035 (void)read (fd, &c, 1) ;
1040 int waitForInterruptWPi (int pin, int mS)
1042 return waitForInterruptSys (pinToGpio [pin & 63], mS) ;
1045 int waitForInterruptGpio (int pin, int mS)
1047 return waitForInterruptSys (pin, mS) ;
1053 * This is a thread and gets started to wait for the interrupt we're
1054 * hoping to catch. It will call the user-function when the interrupt
1056 *********************************************************************************
1059 static void *interruptHandler (void *arg)
1061 int myPin = *(int *)arg ;
1063 (void)piHiPri (55) ; // Only effective if we run as root
1066 if (waitForInterruptSys (myPin, -1) > 0)
1067 isrFunctions [myPin] () ;
1075 * Take the details and create an interrupt handler that will do a call-
1076 * back to the user supplied function.
1077 *********************************************************************************
1080 int wiringPiISR (int pin, int mode, void (*function)(void))
1082 pthread_t threadId ;
1092 if (wiringPiMode == WPI_MODE_UNINITIALISED)
1094 fprintf (stderr, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
1095 exit (EXIT_FAILURE) ;
1097 else if (wiringPiMode == WPI_MODE_PINS)
1098 pin = pinToGpio [pin] ;
1100 // Now export the pin and set the right edge
1101 // We're going to use the gpio program to do this, so it assumes
1102 // a full installation of wiringPi. It's a bit 'clunky', but it
1103 // is a way that will work when we're running in "Sys" mode, as
1104 // a non-root user. (without sudo)
1106 if (mode != INT_EDGE_SETUP)
1108 /**/ if (mode == INT_EDGE_FALLING)
1110 else if (mode == INT_EDGE_RISING)
1115 sprintf (pinS, "%d", pin) ;
1117 if ((pid = fork ()) < 0) // Fail
1120 if (pid == 0) // Child, exec
1122 execl ("/usr/local/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
1123 return -1 ; // Failure ...
1125 else // Parent, wait
1129 // Now pre-open the /sys/class node - it may already be open if
1130 // we are in Sys mode, but this will do no harm.
1132 sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1133 if ((sysFds [pin] = open (fName, O_RDWR)) < 0)
1136 // Clear any initial pending interrupt
1138 ioctl (sysFds [pin], FIONREAD, &count) ;
1139 for (i = 0 ; i < count ; ++i)
1140 read (sysFds [pin], &c, 1) ;
1142 isrFunctions [pin] = function ;
1144 pthread_create (&threadId, NULL, interruptHandler, &pin) ;
1154 * Initialise our start-of-time variable to be the current unix
1155 * time in milliseconds.
1156 *********************************************************************************
1159 static void initialiseEpoch (void)
1163 gettimeofday (&tv, NULL) ;
1164 epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
1165 epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
1170 * Wait for some number of milli seconds
1171 *********************************************************************************
1174 void delay (unsigned int howLong)
1176 struct timespec sleeper, dummy ;
1178 sleeper.tv_sec = (time_t)(howLong / 1000) ;
1179 sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
1181 nanosleep (&sleeper, &dummy) ;
1186 * delayMicroseconds:
1187 * This is somewhat intersting. It seems that on the Pi, a single call
1188 * to nanosleep takes some 80 to 130 microseconds anyway, so while
1189 * obeying the standards (may take longer), it's not always what we
1192 * So what I'll do now is if the delay is less than 100uS we'll do it
1193 * in a hard loop, watching a built-in counter on the ARM chip. This is
1194 * somewhat sub-optimal in that it uses 100% CPU, something not an issue
1195 * in a microcontroller, but under a multi-tasking, multi-user OS, it's
1196 * wastefull, however we've no real choice )-:
1198 * Plan B: It seems all might not be well with that plan, so changing it
1199 * to use gettimeofday () and poll on that instead...
1200 *********************************************************************************
1203 void delayMicrosecondsHard (unsigned int howLong)
1205 struct timeval tNow, tLong, tEnd ;
1207 gettimeofday (&tNow, NULL) ;
1208 tLong.tv_sec = howLong / 1000000 ;
1209 tLong.tv_usec = howLong % 1000000 ;
1210 timeradd (&tNow, &tLong, &tEnd) ;
1212 while (timercmp (&tNow, &tEnd, <))
1213 gettimeofday (&tNow, NULL) ;
1216 void delayMicroseconds (unsigned int howLong)
1218 struct timespec sleeper ;
1220 /**/ if (howLong == 0)
1222 else if (howLong < 100)
1223 delayMicrosecondsHard (howLong) ;
1226 sleeper.tv_sec = 0 ;
1227 sleeper.tv_nsec = (long)(howLong * 1000) ;
1228 nanosleep (&sleeper, NULL) ;
1235 * Return a number of milliseconds as an unsigned int.
1236 *********************************************************************************
1239 unsigned int millis (void)
1244 gettimeofday (&tv, NULL) ;
1245 now = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
1247 return (uint32_t)(now - epochMilli) ;
1253 * Return a number of microseconds as an unsigned int.
1254 *********************************************************************************
1257 unsigned int micros (void)
1262 gettimeofday (&tv, NULL) ;
1263 now = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
1265 return (uint32_t)(now - epochMicro) ;
1271 * Must be called once at the start of your program execution.
1273 * Default setup: Initialises the system into wiringPi Pin mode and uses the
1274 * memory mapped hardware directly.
1275 *********************************************************************************
1278 int wiringPiSetup (void)
1283 if (geteuid () != 0)
1285 fprintf (stderr, "wiringPi:\n Must be root to call wiringPiSetup().\n (Did you forget sudo?)\n") ;
1286 exit (EXIT_FAILURE) ;
1289 if (getenv ("WIRINGPI_DEBUG") != NULL)
1291 printf ("wiringPi: Debug mode enabled\n") ;
1292 wiringPiDebug = TRUE ;
1296 printf ("wiringPi: wiringPiSetup called\n") ;
1298 pinMode = pinModeWPi ;
1299 getAlt = getAltWPi ;
1300 pullUpDnControl = pullUpDnControlWPi ;
1301 digitalWrite = digitalWriteWPi ;
1302 digitalWriteByte = digitalWriteByteGpio ; // Same code
1303 gpioClockSet = gpioClockSetWPi ;
1304 pwmWrite = pwmWriteWPi ;
1305 setPadDrive = setPadDriveWPi ;
1306 digitalRead = digitalReadWPi ;
1307 waitForInterrupt = waitForInterruptWPi ;
1308 pwmSetMode = pwmSetModeWPi ;
1309 pwmSetRange = pwmSetRangeWPi ;
1310 pwmSetClock = pwmSetClockWPi ;
1312 boardRev = piBoardRev () ;
1315 pinToGpio = pinToGpioR1 ;
1317 pinToGpio = pinToGpioR2 ;
1319 // Open the master /dev/memory device
1321 if ((fd = open ("/dev/mem", O_RDWR | O_SYNC) ) < 0)
1326 fprintf (stderr, "wiringPiSetup: Unable to open /dev/mem: %s\n", strerror (errno)) ;
1334 gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
1335 if ((int32_t)gpio == -1)
1340 fprintf (stderr, "wiringPiSetup: mmap failed: %s\n", strerror (errno)) ;
1348 pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
1349 if ((int32_t)pwm == -1)
1354 fprintf (stderr, "wiringPiSetup: mmap failed (pwm): %s\n", strerror (errno)) ;
1360 // Clock control (needed for PWM)
1362 clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, CLOCK_BASE) ;
1363 if ((int32_t)clk == -1)
1368 fprintf (stderr, "wiringPiSetup: mmap failed (clk): %s\n", strerror (errno)) ;
1376 pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
1377 if ((int32_t)pads == -1)
1382 fprintf (stderr, "wiringPiSetup: mmap failed (pads): %s\n", strerror (errno)) ;
1390 timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
1391 if ((int32_t)timer == -1)
1396 fprintf (stderr, "wiringPiSetup: mmap failed (timer): %s\n", strerror (errno)) ;
1402 // Set the timer to free-running, 1MHz.
1403 // 0xF9 is 249, the timer divide is base clock / (divide+1)
1404 // so base clock is 250MHz / 250 = 1MHz.
1406 *(timer + TIMER_CONTROL) = 0x0000280 ;
1407 *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
1408 timerIrqRaw = timer + TIMER_IRQ_RAW ;
1410 initialiseEpoch () ;
1412 wiringPiMode = WPI_MODE_PINS ;
1419 * wiringPiSetupGpio:
1420 * Must be called once at the start of your program execution.
1422 * GPIO setup: Initialises the system into GPIO Pin mode and uses the
1423 * memory mapped hardware directly.
1424 *********************************************************************************
1427 int wiringPiSetupGpio (void)
1431 if (geteuid () != 0)
1433 fprintf (stderr, "Must be root to call wiringPiSetupGpio(). (Did you forget sudo?)\n") ;
1434 exit (EXIT_FAILURE) ;
1437 if ((x = wiringPiSetup ()) < 0)
1441 printf ("wiringPi: wiringPiSetupGpio called\n") ;
1443 pinMode = pinModeGpio ;
1444 getAlt = getAltGpio ;
1445 pullUpDnControl = pullUpDnControlGpio ;
1446 digitalWrite = digitalWriteGpio ;
1447 digitalWriteByte = digitalWriteByteGpio ;
1448 gpioClockSet = gpioClockSetGpio ;
1449 pwmWrite = pwmWriteGpio ;
1450 setPadDrive = setPadDriveGpio ;
1451 digitalRead = digitalReadGpio ;
1452 waitForInterrupt = waitForInterruptGpio ;
1453 pwmSetMode = pwmSetModeWPi ;
1454 pwmSetRange = pwmSetRangeWPi ;
1455 pwmSetClock = pwmSetClockWPi ;
1457 wiringPiMode = WPI_MODE_GPIO ;
1465 * Must be called once at the start of your program execution.
1467 * Initialisation (again), however this time we are using the /sys/class/gpio
1468 * interface to the GPIO systems - slightly slower, but always usable as
1469 * a non-root user, assuming the devices are already exported and setup correctly.
1472 int wiringPiSetupSys (void)
1478 if (getenv ("WIRINGPI_DEBUG") != NULL)
1479 wiringPiDebug = TRUE ;
1482 printf ("wiringPi: wiringPiSetupSys called\n") ;
1484 pinMode = pinModeSys ;
1485 getAlt = getAltSys ;
1486 pullUpDnControl = pullUpDnControlSys ;
1487 digitalWrite = digitalWriteSys ;
1488 digitalWriteByte = digitalWriteByteSys ;
1489 gpioClockSet = gpioClockSetSys ;
1490 pwmWrite = pwmWriteSys ;
1491 setPadDrive = setPadDriveSys ;
1492 digitalRead = digitalReadSys ;
1493 waitForInterrupt = waitForInterruptSys ;
1494 pwmSetMode = pwmSetModeSys ;
1495 pwmSetRange = pwmSetRangeSys ;
1496 pwmSetClock = pwmSetClockSys ;
1498 boardRev = piBoardRev () ;
1501 pinToGpio = pinToGpioR1 ;
1503 pinToGpio = pinToGpioR2 ;
1505 // Open and scan the directory, looking for exported GPIOs, and pre-open
1506 // the 'value' interface to speed things up for later
1508 for (pin = 0 ; pin < 64 ; ++pin)
1510 sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1511 sysFds [pin] = open (fName, O_RDWR) ;
1514 initialiseEpoch () ;
1516 wiringPiMode = WPI_MODE_GPIO_SYS ;