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
54 // Pad drive current fiddling
71 #include <sys/types.h>
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) ;
100 #define BCM_PASSWORD 0x5A000000
103 // Port function select bits
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
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 )-:
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)
126 #define PAGE_SIZE (4*1024)
127 #define BLOCK_SIZE (4*1024)
131 #define PWM_CONTROL 0
138 #define PWMCLK_CNTL 40
139 #define PWMCLK_DIV 41
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
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
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)
169 // Locals to hold pointers to the hardware
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 ;
178 // Time for easy calculations
180 static unsigned long long epoch ;
184 static int wiringPiMode = WPI_MODE_UNINITIALISED ;
188 int wiringPiDebug = FALSE ;
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
194 // Each control register has 10 sets of 3 bits per GPIO pin:
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
205 // So the 3 bits for port X are:
206 // X / 10 + ((X % 10) * 3)
209 // Map a file descriptor from the /sys/class/gpio/gpioX/value
211 static int sysFds [64] ;
215 static void (*isrFunctions [64])(void) ;
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!
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
226 static int *pinToGpio ;
228 static int pinToGpioR1 [64] =
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
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
243 static int pinToGpioR2 [64] =
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
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
261 // Map a BCM_GPIO pin to it's control port. (GPFSEL 0-5)
263 static uint8_t gpioToGPFSEL [] =
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,
275 // Define the shift up for the 3 bits per pin in each GPFSEL port
277 static uint8_t gpioToShift [] =
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,
288 // (Word) offset to the GPIO Set registers for each GPIO pin
290 static uint8_t gpioToGPSET [] =
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,
298 // (Word) offset to the GPIO Clear registers for each GPIO pin
300 static uint8_t gpioToGPCLR [] =
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,
308 // (Word) offset to the GPIO Input level registers for each GPIO pin
310 static uint8_t gpioToGPLEV [] =
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,
319 // (Word) offset to the Event Detect Status
321 static uint8_t gpioToEDS [] =
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,
328 // (Word) offset to the Rising edgde ENable register
330 static uint8_t gpioToREN [] =
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,
337 // (Word) offset to the Falling edgde ENable register
339 static uint8_t gpioToFEN [] =
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,
348 // (Word) offset to the Pull Up Down Clock regsiter
352 static uint8_t gpioToPUDCLK [] =
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,
360 // the ALT value to put a GPIO pin into PWM mode
362 static uint8_t gpioToPwmALT [] =
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
374 static uint8_t gpioToPwmPort [] =
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
390 *********************************************************************************
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 *********************************************************************************
402 int wpiPinToGpio (int wpiPin)
404 return pinToGpio [wpiPin & 63] ;
410 * Return a number representing the hardware revision of the board.
411 * Revision is currently 1 or 2. -1 is returned on error.
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:
422 * 0005 - Rev 2 (but error)
424 * 000f - Rev 2 + 512MB
426 * A small thorn is the olde style overvolting - that will add in
429 *********************************************************************************
432 static void piBoardRevOops (char *why)
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) ;
441 int piBoardRev (void)
446 static int boardRev = -1 ;
448 // No point checking twice...
453 if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
456 while (fgets (line, 120, cpuFd) != NULL)
457 if (strncmp (line, "Revision", 8) == 0)
463 piBoardRevOops ("No \"Revision\" line") ;
465 line [strlen (line) - 1] = 0 ; // Chomp LF
468 printf ("piboardRev: Revision string: %s\n", line) ;
470 for (c = line ; *c ; ++c)
475 piBoardRevOops ("No numeric revision string") ;
477 // If you have overvolted the Pi, then it appears that the revision
478 // has 100000 added to it!
482 printf ("piboardRev: This Pi has/is overvolted!\n") ;
484 lastChar = line [strlen (line) - 1] ;
487 printf ("piboardRev: lastChar is: '%c' (%d, 0x%02X)\n", lastChar, lastChar, lastChar) ;
489 /**/ if ((lastChar == '2') || (lastChar == '3'))
495 printf ("piBoardRev: Returning revision: %d\n", boardRev) ;
504 * Sets the mode of a pin to be input, output or PWM output
505 *********************************************************************************
508 void pinModeGpio (int pin, int mode)
510 // register int barrier ;
512 int fSel, shift, alt ;
516 fSel = gpioToGPFSEL [pin] ;
517 shift = gpioToShift [pin] ;
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)
525 if ((alt = gpioToPwmALT [pin]) == 0) // Not a PWM pin
528 // Set pin to PWM mode
530 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
532 delayMicroseconds (110) ; // See comments in pwmSetClockWPi
533 *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
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.
538 *(pwm + PWM_CONTROL) = 0 ; // Stop PWM
540 *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ; // Stop PWM Clock
541 delayMicroseconds (110) ; // See comments in pwmSetClockWPi
543 while ((*(clk + PWMCLK_CNTL) & 0x80) != 0) // Wait for clock to be !BUSY
544 delayMicroseconds (1) ;
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
549 delayMicroseconds (110) ; // See comments in pwmSetClockWPi
551 // Default range register of 1024
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) ;
558 // Enable PWMs in balanced mode (default)
560 *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
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
574 // pullUpDnControl (pin, PUD_OFF) ;
578 void pinModeWPi (int pin, int mode)
580 pinModeGpio (pinToGpio [pin & 63], mode) ;
583 void pinModeSys (int pin, int mode)
591 * Allow the user to control some of the PWM functions
592 *********************************************************************************
595 void pwmSetModeWPi (int mode)
597 if (mode == PWM_MODE_MS)
598 *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
600 *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
603 void pwmSetModeSys (int mode)
609 void pwmSetRangeWPi (unsigned int range)
611 *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
612 *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
615 void pwmSetRangeSys (unsigned int range)
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 *********************************************************************************
628 void pwmSetClockWPi (int divisor)
630 unsigned int pwm_control ;
634 printf ("Setting to: %d. Current: 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
636 pwm_control = *(pwm + PWM_CONTROL) ; // preserve PWM_CONTROL
638 // We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
641 *(pwm + PWM_CONTROL) = 0 ; // Stop PWM
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.
649 *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ; // Stop PWM Clock
650 delayMicroseconds (110) ; // prevents clock going sloooow
652 while ((*(clk + PWMCLK_CNTL) & 0x80) != 0) // Wait for clock to be !BUSY
653 delayMicroseconds (1) ;
655 *(clk + PWMCLK_DIV) = BCM_PASSWORD | (divisor << 12) ;
657 *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ; // Start PWM clock
658 *(pwm + PWM_CONTROL) = pwm_control ; // restore PWM_CONTROL
661 printf ("Set to: %d. Now : 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
664 void pwmSetClockSys (int divisor)
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 *********************************************************************************
679 void pinEnableED01Pi (int pin)
681 pin = pinToGpio [pin & 63] ;
690 *********************************************************************************
693 void digitalWriteWPi (int pin, int value)
695 pin = pinToGpio [pin & 63] ;
698 *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
700 *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
703 void digitalWriteGpio (int pin, int value)
708 *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
710 *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
713 void digitalWriteSys (int pin, int value)
717 if (sysFds [pin] != -1)
720 write (sysFds [pin], "0\n", 2) ;
722 write (sysFds [pin], "1\n", 2) ;
729 * Write an 8-bit byte to the first 8 GPIO pins - try to do it as
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 *********************************************************************************
737 void digitalWriteByteGpio (int value)
739 uint32_t pinSet = 0 ;
740 uint32_t pinClr = 0 ;
744 for (pin = 0 ; pin < 8 ; ++pin)
746 if ((value & mask) == 0)
747 pinClr |= (1 << pinToGpio [pin]) ;
749 pinSet |= (1 << pinToGpio [pin]) ;
754 *(gpio + gpioToGPCLR [0]) = pinClr ;
755 *(gpio + gpioToGPSET [0]) = pinSet ;
758 void digitalWriteByteSys (int value)
763 for (pin = 0 ; pin < 8 ; ++pin)
765 digitalWriteSys (pinToGpio [pin], value & mask) ;
773 * Set an output PWM value
774 *********************************************************************************
777 void pwmWriteGpio (int pin, int value)
782 port = gpioToPwmPort [pin] ;
784 *(pwm + port) = value ;
787 void pwmWriteWPi (int pin, int value)
789 pwmWriteGpio (pinToGpio [pin & 63], value) ;
792 void pwmWriteSys (int pin, int value)
800 * Set the PAD driver value
801 *********************************************************************************
804 void setPadDriveWPi (int group, int value)
808 if ((group < 0) || (group > 2))
811 wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
812 *(pads + group + 11) = wrVal ;
815 printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
816 printf ("Read : %08X\n", *(pads + group + 11)) ;
820 void setPadDriveGpio (int group, int value)
822 setPadDriveWPi (group, value) ;
825 void setPadDriveSys (int group, int value)
833 * Read the value of a given Pin, returning HIGH or LOW
834 *********************************************************************************
837 int digitalReadWPi (int pin)
839 pin = pinToGpio [pin & 63] ;
841 if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
847 int digitalReadGpio (int pin)
851 if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
857 int digitalReadSys (int pin)
863 if (sysFds [pin] == -1)
866 lseek (sysFds [pin], 0L, SEEK_SET) ;
867 read (sysFds [pin], &c, 1) ;
868 return (c == '0') ? 0 : 1 ;
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
878 *********************************************************************************
881 void pullUpDnControlGpio (int pin, int pud)
886 *(gpio + GPPUD) = pud ; delayMicroseconds (5) ;
887 *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ; delayMicroseconds (5) ;
889 *(gpio + GPPUD) = 0 ; delayMicroseconds (5) ;
890 *(gpio + gpioToPUDCLK [pin]) = 0 ; delayMicroseconds (5) ;
893 void pullUpDnControlWPi (int pin, int pud)
895 pullUpDnControlGpio (pinToGpio [pin & 63], pud) ;
898 void pullUpDnControlSys (int pin, int pud)
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 *********************************************************************************
913 int waitForInterruptSys (int pin, int mS)
917 struct pollfd polls ;
919 if ((fd = sysFds [pin & 63]) == -1)
924 x = read (fd, buf, 6) ;
930 lseek (fd, 0, SEEK_SET) ;
932 // Setup poll structure
935 polls.events = POLLPRI ; // Urgent data!
939 return poll (&polls, 1, mS) ;
942 int waitForInterruptWPi (int pin, int mS)
944 return waitForInterruptSys (pinToGpio [pin & 63], mS) ;
947 int waitForInterruptGpio (int pin, int mS)
949 return waitForInterruptSys (pin, mS) ;
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
958 *********************************************************************************
961 static void *interruptHandler (void *arg)
963 int myPin = *(int *)arg ;
965 (void)piHiPri (55) ; // Only effective if we run as root
968 if (waitForInterruptSys (myPin, -1) > 0)
969 isrFunctions [myPin] () ;
977 * Take the details and create an interrupt handler that will do a call-
978 * back to the user supplied function.
979 *********************************************************************************
982 int wiringPiISR (int pin, int mode, void (*function)(void))
992 if (wiringPiMode == WPI_MODE_UNINITIALISED)
994 fprintf (stderr, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
995 exit (EXIT_FAILURE) ;
997 else if (wiringPiMode == WPI_MODE_PINS)
998 pin = pinToGpio [pin] ;
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)
1006 if (mode != INT_EDGE_SETUP)
1008 /**/ if (mode == INT_EDGE_FALLING)
1010 else if (mode == INT_EDGE_RISING)
1015 sprintf (pinS, "%d", pin) ;
1017 if ((pid = fork ()) < 0) // Fail
1020 if (pid == 0) // Child, exec
1022 execl ("/usr/local/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
1023 return -1 ; // Failure ...
1025 else // Parent, wait
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.
1032 sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1033 if ((sysFds [pin] = open (fName, O_RDWR)) < 0)
1036 isrFunctions [pin] = function ;
1038 pthread_create (&threadId, NULL, interruptHandler, &pin) ;
1048 * Wait for some number of milli seconds
1049 *********************************************************************************
1052 void delay (unsigned int howLong)
1054 struct timespec sleeper, dummy ;
1056 sleeper.tv_sec = (time_t)(howLong / 1000) ;
1057 sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
1059 nanosleep (&sleeper, &dummy) ;
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
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 )-:
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 *********************************************************************************
1081 void delayMicrosecondsSys (unsigned int howLong)
1083 struct timespec sleeper, dummy ;
1085 sleeper.tv_sec = 0 ;
1086 sleeper.tv_nsec = (long)(howLong * 1000) ;
1088 nanosleep (&sleeper, &dummy) ;
1091 void delayMicrosecondsHard (unsigned int howLong)
1094 volatile unsigned int dummy ;
1096 *(timer + TIMER_LOAD) = howLong ;
1097 *(timer + TIMER_IRQ_CLR) = 0 ;
1099 dummy = *timerIrqRaw ;
1101 dummy = *timerIrqRaw ;
1103 struct timeval tNow, tLong, tEnd ;
1105 gettimeofday (&tNow, NULL) ;
1106 tLong.tv_sec = howLong / 1000000 ;
1107 tLong.tv_usec = howLong % 1000000 ;
1108 timeradd (&tNow, &tLong, &tEnd) ;
1110 while (timercmp (&tNow, &tEnd, <))
1111 gettimeofday (&tNow, NULL) ;
1115 void delayMicrosecondsWPi (unsigned int howLong)
1117 struct timespec sleeper ;
1119 /**/ if (howLong == 0)
1121 else if (howLong < 100)
1122 delayMicrosecondsHard (howLong) ;
1125 sleeper.tv_sec = 0 ;
1126 sleeper.tv_nsec = (long)(howLong * 1000) ;
1127 nanosleep (&sleeper, NULL) ;
1134 * Return a number of milliseconds as an unsigned int.
1135 *********************************************************************************
1138 unsigned int millis (void)
1141 unsigned long long t1 ;
1143 gettimeofday (&tv, NULL) ;
1145 t1 = (tv.tv_sec * 1000000 + tv.tv_usec) / 1000 ;
1147 return (uint32_t)(t1 - epoch) ;
1153 * Must be called once at the start of your program execution.
1155 * Default setup: Initialises the system into wiringPi Pin mode and uses the
1156 * memory mapped hardware directly.
1157 *********************************************************************************
1160 int wiringPiSetup (void)
1164 //uint8_t *gpioMem, *pwmMem, *clkMem, *padsMem, *timerMem ;
1167 if (geteuid () != 0)
1169 fprintf (stderr, "wiringPi:\n Must be root to call wiringPiSetup().\n (Did you forget sudo?)\n") ;
1170 exit (EXIT_FAILURE) ;
1173 if (getenv ("WIRINGPI_DEBUG") != NULL)
1175 printf ("wiringPi: Debug mode enabled\n") ;
1176 wiringPiDebug = TRUE ;
1180 printf ("wiringPi: wiringPiSetup called\n") ;
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 ;
1195 boardRev = piBoardRev () ;
1198 pinToGpio = pinToGpioR1 ;
1200 pinToGpio = pinToGpioR2 ;
1202 // Open the master /dev/memory device
1204 if ((fd = open ("/dev/mem", O_RDWR | O_SYNC) ) < 0)
1207 fprintf (stderr, "wiringPiSetup: Unable to open /dev/mem: %s\n", strerror (errno)) ;
1213 gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
1214 if ((int32_t)gpio == -1)
1217 fprintf (stderr, "wiringPiSetup: mmap failed: %s\n", strerror (errno)) ;
1223 pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
1224 if ((int32_t)pwm == -1)
1227 fprintf (stderr, "wiringPiSetup: mmap failed (pwm): %s\n", strerror (errno)) ;
1231 // Clock control (needed for PWM)
1233 clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, CLOCK_BASE) ;
1234 if ((int32_t)clk < 0)
1237 fprintf (stderr, "wiringPiSetup: mmap failed (clk): %s\n", strerror (errno)) ;
1243 pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
1244 if ((int32_t)pads < 0)
1247 fprintf (stderr, "wiringPiSetup: mmap failed (pads): %s\n", strerror (errno)) ;
1252 printf ("Checking pads @ 0x%08X\n", (unsigned int)pads) ;
1253 printf (" -> %08X %08X %08X\n", *(pads + 11), *(pads + 12), *(pads + 13)) ;
1258 timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
1259 if ((int32_t)timer < 0)
1262 fprintf (stderr, "wiringPiSetup: mmap failed (timer): %s\n", strerror (errno)) ;
1266 // Set the timer to free-running, 1MHz.
1267 // 0xF9 is 249, the timer divide is base clock / (divide+1)
1268 // so base clock is 250MHz / 250 = 1MHz.
1270 *(timer + TIMER_CONTROL) = 0x0000280 ;
1271 *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
1272 timerIrqRaw = timer + TIMER_IRQ_RAW ;
1274 // Initialise our epoch for millis()
1276 gettimeofday (&tv, NULL) ;
1277 epoch = (tv.tv_sec * 1000000 + tv.tv_usec) / 1000 ;
1279 wiringPiMode = WPI_MODE_PINS ;
1286 * wiringPiSetupGpio:
1287 * Must be called once at the start of your program execution.
1289 * GPIO setup: Initialises the system into GPIO Pin mode and uses the
1290 * memory mapped hardware directly.
1291 *********************************************************************************
1294 int wiringPiSetupGpio (void)
1298 if (geteuid () != 0)
1300 fprintf (stderr, "Must be root to call wiringPiSetupGpio(). (Did you forget sudo?)\n") ;
1301 exit (EXIT_FAILURE) ;
1304 if ((x = wiringPiSetup ()) < 0)
1308 printf ("wiringPi: wiringPiSetupGpio called\n") ;
1310 pinMode = pinModeGpio ;
1311 pullUpDnControl = pullUpDnControlGpio ;
1312 digitalWrite = digitalWriteGpio ;
1313 digitalWriteByte = digitalWriteByteGpio ;
1314 pwmWrite = pwmWriteGpio ;
1315 setPadDrive = setPadDriveGpio ;
1316 digitalRead = digitalReadGpio ;
1317 waitForInterrupt = waitForInterruptGpio ;
1318 delayMicroseconds = delayMicrosecondsWPi ; // Same
1319 pwmSetMode = pwmSetModeWPi ;
1320 pwmSetRange = pwmSetRangeWPi ;
1321 pwmSetClock = pwmSetClockWPi ;
1323 wiringPiMode = WPI_MODE_GPIO ;
1331 * Must be called once at the start of your program execution.
1333 * Initialisation (again), however this time we are using the /sys/class/gpio
1334 * interface to the GPIO systems - slightly slower, but always usable as
1335 * a non-root user, assuming the devices are already exported and setup correctly.
1338 int wiringPiSetupSys (void)
1345 if (getenv ("WIRINGPI_DEBUG") != NULL)
1346 wiringPiDebug = TRUE ;
1349 printf ("wiringPi: wiringPiSetupSys called\n") ;
1351 pinMode = pinModeSys ;
1352 pullUpDnControl = pullUpDnControlSys ;
1353 digitalWrite = digitalWriteSys ;
1354 digitalWriteByte = digitalWriteByteSys ;
1355 pwmWrite = pwmWriteSys ;
1356 setPadDrive = setPadDriveSys ;
1357 digitalRead = digitalReadSys ;
1358 waitForInterrupt = waitForInterruptSys ;
1359 delayMicroseconds = delayMicrosecondsSys ;
1360 pwmSetMode = pwmSetModeSys ;
1361 pwmSetRange = pwmSetRangeSys ;
1362 pwmSetClock = pwmSetClockSys ;
1364 boardRev = piBoardRev () ;
1367 pinToGpio = pinToGpioR1 ;
1369 pinToGpio = pinToGpioR2 ;
1371 // Open and scan the directory, looking for exported GPIOs, and pre-open
1372 // the 'value' interface to speed things up for later
1374 for (pin = 0 ; pin < 64 ; ++pin)
1376 sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
1377 sysFds [pin] = open (fName, O_RDWR) ;
1380 // Initialise the epoch for mills() ...
1382 gettimeofday (&tv, NULL) ;
1383 epoch = (tv.tv_sec * 1000000 + tv.tv_usec) / 1000 ;
1385 wiringPiMode = WPI_MODE_GPIO_SYS ;