Statistics
| Branch: | Revision:

ddr4s / fw / wiringPi / wiringPi / wiringPi.c @ 32:cadb9025f1e0

History | View | Annotate | Download (69.4 KB)

1
/*
2
 * wiringPi:
3
 *        Arduino look-a-like Wiring library for the Raspberry Pi
4
 *        Copyright (c) 2012-2017 Gordon Henderson
5
 *        Additional code for pwmSetClock by Chris Hall <chris@kchall.plus.com>
6
 *
7
 *        Thanks to code samples from Gert Jan van Loo and the
8
 *        BCM2835 ARM Peripherals manual, however it's missing
9
 *        the clock section /grr/mutter/
10
 ***********************************************************************
11
 * This file is part of wiringPi:
12
 *        https://projects.drogon.net/raspberry-pi/wiringpi/
13
 *
14
 *    wiringPi is free software: you can redistribute it and/or modify
15
 *    it under the terms of the GNU Lesser General Public License as
16
 *    published by the Free Software Foundation, either version 3 of the
17
 *    License, or (at your option) any later version.
18
 *
19
 *    wiringPi is distributed in the hope that it will be useful,
20
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *    GNU Lesser General Public License for more details.
23
 *
24
 *    You should have received a copy of the GNU Lesser General Public
25
 *    License along with wiringPi.
26
 *    If not, see <http://www.gnu.org/licenses/>.
27
 ***********************************************************************
28
 */
29

    
30
// Revisions:
31
//        19 Jul 2012:
32
//                Moved to the LGPL
33
//                Added an abstraction layer to the main routines to save a tiny
34
//                bit of run-time and make the clode a little cleaner (if a little
35
//                larger)
36
//                Added waitForInterrupt code
37
//                Added piHiPri code
38
//
39
//         9 Jul 2012:
40
//                Added in support to use the /sys/class/gpio interface.
41
//         2 Jul 2012:
42
//                Fixed a few more bugs to do with range-checking when in GPIO mode.
43
//        11 Jun 2012:
44
//                Fixed some typos.
45
//                Added c++ support for the .h file
46
//                Added a new function to allow for using my "pin" numbers, or native
47
//                        GPIO pin numbers.
48
//                Removed my busy-loop delay and replaced it with a call to delayMicroseconds
49
//
50
//        02 May 2012:
51
//                Added in the 2 UART pins
52
//                Change maxPins to numPins to more accurately reflect purpose
53

    
54

    
55
#include <stdio.h>
56
#include <stdarg.h>
57
#include <stdint.h>
58
#include <stdlib.h>
59
#include <ctype.h>
60
#include <poll.h>
61
#include <unistd.h>
62
#include <errno.h>
63
#include <string.h>
64
#include <time.h>
65
#include <fcntl.h>
66
#include <pthread.h>
67
#include <sys/time.h>
68
#include <sys/mman.h>
69
#include <sys/stat.h>
70
#include <sys/wait.h>
71
#include <sys/ioctl.h>
72
#include <asm/ioctl.h>
73

    
74
#include "softPwm.h"
75
#include "softTone.h"
76

    
77
#include "wiringPi.h"
78
#include "../version.h"
79

    
80
// Environment Variables
81

    
82
#define        ENV_DEBUG        "WIRINGPI_DEBUG"
83
#define        ENV_CODES        "WIRINGPI_CODES"
84
#define        ENV_GPIOMEM        "WIRINGPI_GPIOMEM"
85

    
86

    
87
// Extend wiringPi with other pin-based devices and keep track of
88
//        them in this structure
89

    
90
struct wiringPiNodeStruct *wiringPiNodes = NULL ;
91

    
92
// BCM Magic
93

    
94
#define        BCM_PASSWORD                0x5A000000
95

    
96

    
97
// The BCM2835 has 54 GPIO pins.
98
//        BCM2835 data sheet, Page 90 onwards.
99
//        There are 6 control registers, each control the functions of a block
100
//        of 10 pins.
101
//        Each control register has 10 sets of 3 bits per GPIO pin - the ALT values
102
//
103
//        000 = GPIO Pin X is an input
104
//        001 = GPIO Pin X is an output
105
//        100 = GPIO Pin X takes alternate function 0
106
//        101 = GPIO Pin X takes alternate function 1
107
//        110 = GPIO Pin X takes alternate function 2
108
//        111 = GPIO Pin X takes alternate function 3
109
//        011 = GPIO Pin X takes alternate function 4
110
//        010 = GPIO Pin X takes alternate function 5
111
//
112
// So the 3 bits for port X are:
113
//        X / 10 + ((X % 10) * 3)
114

    
115
// Port function select bits
116

    
117
#define        FSEL_INPT                0b000
118
#define        FSEL_OUTP                0b001
119
#define        FSEL_ALT0                0b100
120
#define        FSEL_ALT1                0b101
121
#define        FSEL_ALT2                0b110
122
#define        FSEL_ALT3                0b111
123
#define        FSEL_ALT4                0b011
124
#define        FSEL_ALT5                0b010
125

    
126
// Access from ARM Running Linux
127
//        Taken from Gert/Doms code. Some of this is not in the manual
128
//        that I can find )-:
129
//
130
// Updates in September 2015 - all now static variables (and apologies for the caps)
131
//        due to the Pi v2, v3, etc. and the new /dev/gpiomem interface
132

    
133
static volatile unsigned int GPIO_PADS ;
134
static volatile unsigned int GPIO_CLOCK_BASE ;
135
static volatile unsigned int GPIO_BASE ;
136
static volatile unsigned int GPIO_TIMER ;
137
static volatile unsigned int GPIO_PWM ;
138

    
139
#define        PAGE_SIZE                (4*1024)
140
#define        BLOCK_SIZE                (4*1024)
141

    
142
static unsigned int usingGpioMem    = FALSE ;
143
static          int wiringPiSetuped = FALSE ;
144

    
145
// PWM
146
//        Word offsets into the PWM control region
147

    
148
#define        PWM_CONTROL 0
149
#define        PWM_STATUS  1
150
#define        PWM0_RANGE  4
151
#define        PWM0_DATA   5
152
#define        PWM1_RANGE  8
153
#define        PWM1_DATA   9
154

    
155
//        Clock regsiter offsets
156

    
157
#define        PWMCLK_CNTL        40
158
#define        PWMCLK_DIV        41
159

    
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
167

    
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
175

    
176
// Timer
177
//        Word offsets
178

    
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)
188

    
189
// Locals to hold pointers to the hardware
190

    
191
static volatile unsigned int *gpio ;
192
static volatile unsigned int *pwm ;
193
static volatile unsigned int *clk ;
194
static volatile unsigned int *pads ;
195
static volatile unsigned int *timer ;
196
static volatile unsigned int *timerIrqRaw ;
197

    
198
// Export variables for the hardware pointers
199

    
200
volatile unsigned int *_wiringPiGpio ;
201
volatile unsigned int *_wiringPiPwm ;
202
volatile unsigned int *_wiringPiClk ;
203
volatile unsigned int *_wiringPiPads ;
204
volatile unsigned int *_wiringPiTimer ;
205
volatile unsigned int *_wiringPiTimerIrqRaw ;
206

    
207

    
208
// Data for use with the boardId functions.
209
//        The order of entries here to correspond with the PI_MODEL_X
210
//        and PI_VERSION_X defines in wiringPi.h
211
//        Only intended for the gpio command - use at your own risk!
212

    
213
// piGpioBase:
214
//        The base address of the GPIO memory mapped hardware IO
215

    
216
#define        GPIO_PERI_BASE_OLD        0x20000000
217
#define        GPIO_PERI_BASE_NEW        0x3F000000
218

    
219
static volatile unsigned int piGpioBase = 0 ;
220

    
221
const char *piModelNames [20] =
222
{
223
  "Model A",        //  0
224
  "Model B",        //  1
225
  "Model A+",        //  2
226
  "Model B+",        //  3
227
  "Pi 2",        //  4
228
  "Alpha",        //  5
229
  "CM",                //  6
230
  "Unknown07",        // 07
231
  "Pi 3",        // 08
232
  "Pi Zero",        // 09
233
  "CM3",        // 10
234
  "Unknown11",        // 11
235
  "Pi Zero-W",        // 12
236
  "Pi 3B+",        // 13
237
  "Pi 3A+",        // 14
238
  "Unknown15",        // 15
239
  "CM3+",        // 16
240
  "Unknown17",        // 17
241
  "Unknown18",        // 18
242
  "Unknown19",        // 19
243
} ;
244

    
245
const char *piRevisionNames [16] =
246
{
247
  "00",
248
  "01",
249
  "02",
250
  "03",
251
  "04",
252
  "05",
253
  "06",
254
  "07",
255
  "08",
256
  "09",
257
  "10",
258
  "11",
259
  "12",
260
  "13",
261
  "14",
262
  "15",
263
} ;
264

    
265
const char *piMakerNames [16] =
266
{
267
  "Sony",        //         0
268
  "Egoman",        //         1
269
  "Embest",        //         2
270
  "Unknown",        //         3
271
  "Embest",        //         4
272
  "Unknown05",        //         5
273
  "Unknown06",        //         6
274
  "Unknown07",        //         7
275
  "Unknown08",        //         8
276
  "Unknown09",        //         9
277
  "Unknown10",        //        10
278
  "Unknown11",        //        11
279
  "Unknown12",        //        12
280
  "Unknown13",        //        13
281
  "Unknown14",        //        14
282
  "Unknown15",        //        15
283
} ;
284

    
285
const int piMemorySize [8] =
286
{
287
   256,                //         0
288
   512,                //         1
289
  1024,                //         2
290
     0,                //         3
291
     0,                //         4
292
     0,                //         5
293
     0,                //         6
294
     0,                //         7
295
} ;
296

    
297
// Time for easy calculations
298

    
299
static uint64_t epochMilli, epochMicro ;
300

    
301
// Misc
302

    
303
static int wiringPiMode = WPI_MODE_UNINITIALISED ;
304
static volatile int    pinPass = -1 ;
305
static pthread_mutex_t pinMutex ;
306

    
307
// Debugging & Return codes
308

    
309
int wiringPiDebug       = FALSE ;
310
int wiringPiReturnCodes = FALSE ;
311

    
312
// Use /dev/gpiomem ?
313

    
314
int wiringPiTryGpioMem  = FALSE ;
315

    
316
// sysFds:
317
//        Map a file descriptor from the /sys/class/gpio/gpioX/value
318

    
319
static int sysFds [64] =
320
{
321
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
322
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
323
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
324
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
325
} ;
326

    
327
// ISR Data
328

    
329
static void (*isrFunctions [64])(void) ;
330

    
331

    
332
// Doing it the Arduino way with lookup tables...
333
//        Yes, it's probably more innefficient than all the bit-twidling, but it
334
//        does tend to make it all a bit clearer. At least to me!
335

    
336
// pinToGpio:
337
//        Take a Wiring pin (0 through X) and re-map it to the BCM_GPIO pin
338
//        Cope for 3 different board revisions here.
339

    
340
static int *pinToGpio ;
341

    
342
// Revision 1, 1.1:
343

    
344
static int pinToGpioR1 [64] =
345
{
346
  17, 18, 21, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7:        wpi  0 -  7
347
   0,  1,                                // I2C  - SDA1, SCL1                                wpi  8 -  9
348
   8,  7,                                // SPI  - CE1, CE0                                wpi 10 - 11
349
  10,  9, 11,                                 // SPI  - MOSI, MISO, SCLK                        wpi 12 - 14
350
  14, 15,                                // UART - Tx, Rx                                wpi 15 - 16
351

    
352
// Padding:
353

    
354
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 31
355
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 47
356
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 63
357
} ;
358

    
359
// Revision 2:
360

    
361
static int pinToGpioR2 [64] =
362
{
363
  17, 18, 27, 22, 23, 24, 25, 4,        // From the Original Wiki - GPIO 0 through 7:        wpi  0 -  7
364
   2,  3,                                // I2C  - SDA0, SCL0                                wpi  8 -  9
365
   8,  7,                                // SPI  - CE1, CE0                                wpi 10 - 11
366
  10,  9, 11,                                 // SPI  - MOSI, MISO, SCLK                        wpi 12 - 14
367
  14, 15,                                // UART - Tx, Rx                                wpi 15 - 16
368
  28, 29, 30, 31,                        // Rev 2: New GPIOs 8 though 11                        wpi 17 - 20
369
   5,  6, 13, 19, 26,                        // B+                                                wpi 21, 22, 23, 24, 25
370
  12, 16, 20, 21,                        // B+                                                wpi 26, 27, 28, 29
371
   0,  1,                                // B+                                                wpi 30, 31
372

    
373
// Padding:
374

    
375
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 47
376
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 63
377
} ;
378

    
379

    
380
// physToGpio:
381
//        Take a physical pin (1 through 26) and re-map it to the BCM_GPIO pin
382
//        Cope for 2 different board revisions here.
383
//        Also add in the P5 connector, so the P5 pins are 3,4,5,6, so 53,54,55,56
384

    
385
static int *physToGpio ;
386

    
387
static int physToGpioR1 [64] =
388
{
389
  -1,                // 0
390
  -1, -1,        // 1, 2
391
   0, -1,
392
   1, -1,
393
   4, 14,
394
  -1, 15,
395
  17, 18,
396
  21, -1,
397
  22, 23,
398
  -1, 24,
399
  10, -1,
400
   9, 25,
401
  11,  8,
402
  -1,  7,        // 25, 26
403

    
404
                                              -1, -1, -1, -1, -1,        // ... 31
405
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 47
406
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,        // ... 63
407
} ;
408

    
409
static int physToGpioR2 [64] =
410
{
411
  -1,                // 0
412
  -1, -1,        // 1, 2
413
   2, -1,
414
   3, -1,
415
   4, 14,
416
  -1, 15,
417
  17, 18,
418
  27, -1,
419
  22, 23,
420
  -1, 24,
421
  10, -1,
422
   9, 25,
423
  11,  8,
424
  -1,  7,        // 25, 26
425

    
426
// B+
427

    
428
   0,  1,
429
   5, -1,
430
   6, 12,
431
  13, -1,
432
  19, 16,
433
  26, 20,
434
  -1, 21,
435

    
436
// the P5 connector on the Rev 2 boards:
437

    
438
  -1, -1,
439
  -1, -1,
440
  -1, -1,
441
  -1, -1,
442
  -1, -1,
443
  28, 29,
444
  30, 31,
445
  -1, -1,
446
  -1, -1,
447
  -1, -1,
448
  -1, -1,
449
} ;
450

    
451
// gpioToGPFSEL:
452
//        Map a BCM_GPIO pin to it's Function Selection
453
//        control port. (GPFSEL 0-5)
454
//        Groups of 10 - 3 bits per Function - 30 bits per port
455

    
456
static uint8_t gpioToGPFSEL [] =
457
{
458
  0,0,0,0,0,0,0,0,0,0,
459
  1,1,1,1,1,1,1,1,1,1,
460
  2,2,2,2,2,2,2,2,2,2,
461
  3,3,3,3,3,3,3,3,3,3,
462
  4,4,4,4,4,4,4,4,4,4,
463
  5,5,5,5,5,5,5,5,5,5,
464
} ;
465

    
466

    
467
// gpioToShift
468
//        Define the shift up for the 3 bits per pin in each GPFSEL port
469

    
470
static uint8_t gpioToShift [] =
471
{
472
  0,3,6,9,12,15,18,21,24,27,
473
  0,3,6,9,12,15,18,21,24,27,
474
  0,3,6,9,12,15,18,21,24,27,
475
  0,3,6,9,12,15,18,21,24,27,
476
  0,3,6,9,12,15,18,21,24,27,
477
  0,3,6,9,12,15,18,21,24,27,
478
} ;
479

    
480

    
481
// gpioToGPSET:
482
//        (Word) offset to the GPIO Set registers for each GPIO pin
483

    
484
static uint8_t gpioToGPSET [] =
485
{
486
   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,
487
   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,
488
} ;
489

    
490
// gpioToGPCLR:
491
//        (Word) offset to the GPIO Clear registers for each GPIO pin
492

    
493
static uint8_t gpioToGPCLR [] =
494
{
495
  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,
496
  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,
497
} ;
498

    
499

    
500
// gpioToGPLEV:
501
//        (Word) offset to the GPIO Input level registers for each GPIO pin
502

    
503
static uint8_t gpioToGPLEV [] =
504
{
505
  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,
506
  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,
507
} ;
508

    
509

    
510
#ifdef notYetReady
511
// gpioToEDS
512
//        (Word) offset to the Event Detect Status
513

    
514
static uint8_t gpioToEDS [] =
515
{
516
  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,
517
  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,
518
} ;
519

    
520
// gpioToREN
521
//        (Word) offset to the Rising edge ENable register
522

    
523
static uint8_t gpioToREN [] =
524
{
525
  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,
526
  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,
527
} ;
528

    
529
// gpioToFEN
530
//        (Word) offset to the Falling edgde ENable register
531

    
532
static uint8_t gpioToFEN [] =
533
{
534
  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,
535
  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,
536
} ;
537
#endif
538

    
539

    
540
// GPPUD:
541
//        GPIO Pin pull up/down register
542

    
543
#define        GPPUD        37
544

    
545
// gpioToPUDCLK
546
//        (Word) offset to the Pull Up Down Clock regsiter
547

    
548
static uint8_t gpioToPUDCLK [] =
549
{
550
  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,
551
  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,
552
} ;
553

    
554

    
555
// gpioToPwmALT
556
//        the ALT value to put a GPIO pin into PWM mode
557

    
558
static uint8_t gpioToPwmALT [] =
559
{
560
          0,         0,         0,         0,         0,         0,         0,         0,        //  0 ->  7
561
          0,         0,         0,         0, FSEL_ALT0, FSEL_ALT0,         0,         0,         //  8 -> 15
562
          0,         0, FSEL_ALT5, FSEL_ALT5,         0,         0,         0,         0,         // 16 -> 23
563
          0,         0,         0,         0,         0,         0,         0,         0,        // 24 -> 31
564
          0,         0,         0,         0,         0,         0,         0,         0,        // 32 -> 39
565
  FSEL_ALT0, FSEL_ALT0,         0,         0,         0, FSEL_ALT0,         0,         0,        // 40 -> 47
566
          0,         0,         0,         0,         0,         0,         0,         0,        // 48 -> 55
567
          0,         0,         0,         0,         0,         0,         0,         0,        // 56 -> 63
568
} ;
569

    
570

    
571
// gpioToPwmPort
572
//        The port value to put a GPIO pin into PWM mode
573

    
574
static uint8_t gpioToPwmPort [] =
575
{
576
          0,         0,         0,         0,         0,         0,         0,         0,        //  0 ->  7
577
          0,         0,         0,         0, PWM0_DATA, PWM1_DATA,         0,         0,         //  8 -> 15
578
          0,         0, PWM0_DATA, PWM1_DATA,         0,         0,         0,         0,         // 16 -> 23
579
          0,         0,         0,         0,         0,         0,         0,         0,        // 24 -> 31
580
          0,         0,         0,         0,         0,         0,         0,         0,        // 32 -> 39
581
  PWM0_DATA, PWM1_DATA,         0,         0,         0, PWM1_DATA,         0,         0,        // 40 -> 47
582
          0,         0,         0,         0,         0,         0,         0,         0,        // 48 -> 55
583
          0,         0,         0,         0,         0,         0,         0,         0,        // 56 -> 63
584

    
585
} ;
586

    
587
// gpioToGpClkALT:
588
//        ALT value to put a GPIO pin into GP Clock mode.
589
//        On the Pi we can really only use BCM_GPIO_4 and BCM_GPIO_21
590
//        for clocks 0 and 1 respectively, however I'll include the full
591
//        list for completeness - maybe one day...
592

    
593
#define        GPIO_CLOCK_SOURCE        1
594

    
595
// gpioToGpClkALT0:
596

    
597
static uint8_t gpioToGpClkALT0 [] =
598
{
599
          0,         0,         0,         0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0,         0,        //  0 ->  7
600
          0,         0,         0,         0,         0,         0,         0,         0,         //  8 -> 15
601
          0,         0,         0,         0, FSEL_ALT5, FSEL_ALT5,         0,         0,         // 16 -> 23
602
          0,         0,         0,         0,         0,         0,         0,         0,        // 24 -> 31
603
  FSEL_ALT0,         0, FSEL_ALT0,         0,         0,         0,         0,         0,        // 32 -> 39
604
          0,         0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0,         0,         0,         0,        // 40 -> 47
605
          0,         0,         0,         0,         0,         0,         0,         0,        // 48 -> 55
606
          0,         0,         0,         0,         0,         0,         0,         0,        // 56 -> 63
607
} ;
608

    
609
// gpioToClk:
610
//        (word) Offsets to the clock Control and Divisor register
611

    
612
static uint8_t gpioToClkCon [] =
613
{
614
         -1,        -1,        -1,        -1,        28,        30,        32,        -1,        //  0 ->  7
615
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,         //  8 -> 15
616
         -1,        -1,        -1,        -1,        28,        30,        -1,        -1,         // 16 -> 23
617
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 24 -> 31
618
         28,        -1,        28,        -1,        -1,        -1,        -1,        -1,        // 32 -> 39
619
         -1,        -1,        28,        30,        28,        -1,        -1,        -1,        // 40 -> 47
620
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 48 -> 55
621
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 56 -> 63
622
} ;
623

    
624
static uint8_t gpioToClkDiv [] =
625
{
626
         -1,        -1,        -1,        -1,        29,        31,        33,        -1,        //  0 ->  7
627
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,         //  8 -> 15
628
         -1,        -1,        -1,        -1,        29,        31,        -1,        -1,         // 16 -> 23
629
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 24 -> 31
630
         29,        -1,        29,        -1,        -1,        -1,        -1,        -1,        // 32 -> 39
631
         -1,        -1,        29,        31,        29,        -1,        -1,        -1,        // 40 -> 47
632
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 48 -> 55
633
         -1,        -1,        -1,        -1,        -1,        -1,        -1,        -1,        // 56 -> 63
634
} ;
635

    
636

    
637
/*
638
 * Functions
639
 *********************************************************************************
640
 */
641

    
642

    
643
/*
644
 * wiringPiFailure:
645
 *        Fail. Or not.
646
 *********************************************************************************
647
 */
648

    
649
int wiringPiFailure (int fatal, const char *message, ...)
650
{
651
  va_list argp ;
652
  char buffer [1024] ;
653

    
654
  if (!fatal && wiringPiReturnCodes)
655
    return -1 ;
656

    
657
  va_start (argp, message) ;
658
    vsnprintf (buffer, 1023, message, argp) ;
659
  va_end (argp) ;
660

    
661
  fprintf (stderr, "%s", buffer) ;
662
  exit (EXIT_FAILURE) ;
663

    
664
  return 0 ;
665
}
666

    
667

    
668
/*
669
 * setupCheck
670
 *        Another sanity check because some users forget to call the setup
671
 *        function. Mosty because they need feeding C drip by drip )-:
672
 *********************************************************************************
673
 */
674

    
675
static void setupCheck (const char *fName)
676
{
677
  if (!wiringPiSetuped)
678
  {
679
    fprintf (stderr, "%s: You have not called one of the wiringPiSetup\n"
680
        "  functions, so I'm aborting your program before it crashes anyway.\n", fName) ;
681
    exit (EXIT_FAILURE) ;
682
  }
683
}
684

    
685
/*
686
 * gpioMemCheck:
687
 *        See if we're using the /dev/gpiomem interface, if-so then some operations
688
 *        can't be done and will crash the Pi.
689
 *********************************************************************************
690
 */
691

    
692
static void usingGpioMemCheck (const char *what)
693
{
694
  if (usingGpioMem)
695
  {
696
    fprintf (stderr, "%s: Unable to do this when using /dev/gpiomem. Try sudo?\n", what) ;
697
    exit (EXIT_FAILURE) ;
698
  }
699
}
700

    
701

    
702

    
703
/*
704
 * piGpioLayout:
705
 *        Return a number representing the hardware revision of the board.
706
 *        This is not strictly the board revision but is used to check the
707
 *        layout of the GPIO connector - and there are 2 types that we are
708
 *        really interested in here. The very earliest Pi's and the
709
 *        ones that came after that which switched some pins ....
710
 *
711
 *        Revision 1 really means the early Model A and B's.
712
 *        Revision 2 is everything else - it covers the B, B+ and CM.
713
 *                ... and the Pi 2 - which is a B+ ++  ...
714
 *                ... and the Pi 0 - which is an A+ ...
715
 *
716
 *        The main difference between the revision 1 and 2 system that I use here
717
 *        is the mapping of the GPIO pins. From revision 2, the Pi Foundation changed
718
 *        3 GPIO pins on the (original) 26-way header - BCM_GPIO 22 was dropped and
719
 *        replaced with 27, and 0 + 1 - I2C bus 0 was changed to 2 + 3; I2C bus 1.
720
 *
721
 *        Additionally, here we set the piModel2 flag too. This is again, nothing to
722
 *        do with the actual model, but the major version numbers - the GPIO base
723
 *        hardware address changed at model 2 and above (not the Zero though)
724
 *
725
 *********************************************************************************
726
 */
727

    
728
static void piGpioLayoutOops (const char *why)
729
{
730
  fprintf (stderr, "Oops: Unable to determine board revision from /proc/cpuinfo\n") ;
731
  fprintf (stderr, " -> %s\n", why) ;
732
  fprintf (stderr, " ->  You'd best google the error to find out why.\n") ;
733
//fprintf (stderr, " ->  http://www.raspberrypi.org/phpBB3/viewtopic.php?p=184410#p184410\n") ;
734
  exit (EXIT_FAILURE) ;
735
}
736

    
737
int piGpioLayout (void)
738
{
739
  FILE *cpuFd ;
740
  char line [120] ;
741
  char *c ;
742
  static int  gpioLayout = -1 ;
743

    
744
  if (gpioLayout != -1)        // No point checking twice
745
    return gpioLayout ;
746

    
747
  if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
748
    piGpioLayoutOops ("Unable to open /proc/cpuinfo") ;
749

    
750
// Start by looking for the Architecture to make sure we're really running
751
//        on a Pi. I'm getting fed-up with people whinging at me because
752
//        they can't get it to work on weirdFruitPi boards...
753

    
754
  while (fgets (line, 120, cpuFd) != NULL)
755
    if (strncmp (line, "Hardware", 8) == 0)
756
      break ;
757

    
758
  if (strncmp (line, "Hardware", 8) != 0)
759
    piGpioLayoutOops ("No \"Hardware\" line") ;
760

    
761
  if (wiringPiDebug)
762
    printf ("piGpioLayout: Hardware: %s\n", line) ;
763

    
764
// See if it's BCM2708 or BCM2709 or the new BCM2835.
765

    
766
// OK. As of Kernel 4.8,  we have BCM2835 only, regardless of model.
767
//        However I still want to check because it will trap the cheapskates and rip-
768
//        off merchants who want to use wiringPi on non-Raspberry Pi platforms - which
769
//        I do not support so don't email me your bleating whinges about anything
770
//        other than a genuine Raspberry Pi.
771

    
772
#ifdef        DONT_CARE_ANYMORE
773
  if (! (strstr (line, "BCM2708") || strstr (line, "BCM2709") || strstr (line, "BCM2835")))
774
  {
775
    fprintf (stderr, "Unable to determine hardware version. I see: %s,\n", line) ;
776
    fprintf (stderr, " - expecting BCM2708, BCM2709 or BCM2835.\n") ;
777
    fprintf (stderr, "If this is a genuine Raspberry Pi then please report this\n") ;
778
    fprintf (stderr, "to projects@drogon.net. If this is not a Raspberry Pi then you\n") ;
779
    fprintf (stderr, "are on your own as wiringPi is designed to support the\n") ;
780
    fprintf (stderr, "Raspberry Pi ONLY.\n") ;
781
    exit (EXIT_FAILURE) ;
782
  }
783
#endif
784

    
785
// Actually... That has caused me more than 10,000 emails so-far. Mosty by
786
//        people who think they know better by creating a statically linked
787
//        version that will not run with a new 4.9 kernel. I utterly hate and
788
//        despise those people.
789
//
790
//        I also get bleats from people running other than Raspbian with another
791
//        distros compiled kernel rather than a foundation compiled kernel, so
792
//        this might actually help them. It might not - I only have the capacity
793
//        to support Raspbian.
794
//
795
//        However, I've decided to leave this check out and rely purely on the
796
//        Revision: line for now. It will not work on a non-pi hardware or weird
797
//        kernels that don't give you a suitable revision line.
798

    
799
// So - we're Probably on a Raspberry Pi. Check the revision field for the real
800
//        hardware type
801
//        In-future, I ought to use the device tree as there are now Pi entries in
802
//        /proc/device-tree/ ...
803
//        but I'll leave that for the next revision. Or the next.
804

    
805
// Isolate the Revision line
806

    
807
  rewind (cpuFd) ;
808
  while (fgets (line, 120, cpuFd) != NULL)
809
    if (strncmp (line, "Revision", 8) == 0)
810
      break ;
811

    
812
  fclose (cpuFd) ;
813

    
814
  if (strncmp (line, "Revision", 8) != 0)
815
    piGpioLayoutOops ("No \"Revision\" line") ;
816

    
817
// Chomp trailing CR/NL
818

    
819
  for (c = &line [strlen (line) - 1] ; (*c == '\n') || (*c == '\r') ; --c)
820
    *c = 0 ;
821
  
822
  if (wiringPiDebug)
823
    printf ("piGpioLayout: Revision string: %s\n", line) ;
824

    
825
// Scan to the first character of the revision number
826

    
827
  for (c = line ; *c ; ++c)
828
    if (*c == ':')
829
      break ;
830

    
831
  if (*c != ':')
832
    piGpioLayoutOops ("Bogus \"Revision\" line (no colon)") ;
833

    
834
// Chomp spaces
835

    
836
  ++c ;
837
  while (isspace (*c))
838
    ++c ;
839

    
840
  if (!isxdigit (*c))
841
    piGpioLayoutOops ("Bogus \"Revision\" line (no hex digit at start of revision)") ;
842

    
843
// Make sure its long enough
844

    
845
  if (strlen (c) < 4)
846
    piGpioLayoutOops ("Bogus revision line (too small)") ;
847

    
848
// Isolate  last 4 characters: (in-case of overvolting or new encoding scheme)
849

    
850
  c = c + strlen (c) - 4 ;
851

    
852
  if (wiringPiDebug)
853
    printf ("piGpioLayout: last4Chars are: \"%s\"\n", c) ;
854

    
855
  if ( (strcmp (c, "0002") == 0) || (strcmp (c, "0003") == 0))
856
    gpioLayout = 1 ;
857
  else
858
    gpioLayout = 2 ;        // Covers everything else from the B revision 2 to the B+, the Pi v2, v3, zero and CM's.
859

    
860
  if (wiringPiDebug)
861
    printf ("piGpioLayoutOops: Returning revision: %d\n", gpioLayout) ;
862

    
863
  return gpioLayout ;
864
}
865

    
866
/*
867
 * piBoardRev:
868
 *        Deprecated, but does the same as piGpioLayout
869
 *********************************************************************************
870
 */
871

    
872
int piBoardRev (void)
873
{
874
  return piGpioLayout () ;
875
}
876

    
877

    
878

    
879
/*
880
 * piBoardId:
881
 *        Return the real details of the board we have.
882
 *
883
 *        This is undocumented and really only intended for the GPIO command.
884
 *        Use at your own risk!
885
 *
886
 *        Seems there are some boards with 0000 in them (mistake in manufacture)
887
 *        So the distinction between boards that I can see is:
888
 *
889
 *                0000 - Error
890
 *                0001 - Not used 
891
 *
892
 *        Original Pi boards:
893
 *                0002 - Model B,  Rev 1,   256MB, Egoman
894
 *                0003 - Model B,  Rev 1.1, 256MB, Egoman, Fuses/D14 removed.
895
 *
896
 *        Newer Pi's with remapped GPIO:
897
 *                0004 - Model B,  Rev 1.2, 256MB, Sony
898
 *                0005 - Model B,  Rev 1.2, 256MB, Egoman
899
 *                0006 - Model B,  Rev 1.2, 256MB, Egoman
900
 *
901
 *                0007 - Model A,  Rev 1.2, 256MB, Egoman
902
 *                0008 - Model A,  Rev 1.2, 256MB, Sony
903
 *                0009 - Model A,  Rev 1.2, 256MB, Egoman
904
 *
905
 *                000d - Model B,  Rev 1.2, 512MB, Egoman        (Red Pi, Blue Pi?)
906
 *                000e - Model B,  Rev 1.2, 512MB, Sony
907
 *                000f - Model B,  Rev 1.2, 512MB, Egoman
908
 *
909
 *                0010 - Model B+, Rev 1.2, 512MB, Sony
910
 *                0013 - Model B+  Rev 1.2, 512MB, Embest
911
 *                0016 - Model B+  Rev 1.2, 512MB, Sony
912
 *                0019 - Model B+  Rev 1.2, 512MB, Egoman
913
 *
914
 *                0011 - Pi CM,    Rev 1.1, 512MB, Sony
915
 *                0014 - Pi CM,    Rev 1.1, 512MB, Embest
916
 *                0017 - Pi CM,    Rev 1.1, 512MB, Sony
917
 *                001a - Pi CM,    Rev 1.1, 512MB, Egoman
918
 *
919
 *                0012 - Model A+  Rev 1.1, 256MB, Sony
920
 *                0015 - Model A+  Rev 1.1, 512MB, Embest
921
 *                0018 - Model A+  Rev 1.1, 256MB, Sony
922
 *                001b - Model A+  Rev 1.1, 256MB, Egoman
923
 *
924
 *        A small thorn is the olde style overvolting - that will add in
925
 *                1000000
926
 *
927
 *        The Pi compute module has an revision of 0011 or 0014 - since we only
928
 *        check the last digit, then it's 1, therefore it'll default to not 2 or
929
 *        3 for a        Rev 1, so will appear as a Rev 2. This is fine for the most part, but
930
 *        we'll properly detect the Compute Module later and adjust accordingly.
931
 *
932
 * And then things changed with the introduction of the v2...
933
 *
934
 * For Pi v2 and subsequent models - e.g. the Zero:
935
 *
936
 *   [USER:8] [NEW:1] [MEMSIZE:3] [MANUFACTURER:4] [PROCESSOR:4] [TYPE:8] [REV:4]
937
 *   NEW          23: will be 1 for the new scheme, 0 for the old scheme
938
 *   MEMSIZE      20: 0=256M 1=512M 2=1G
939
 *   MANUFACTURER 16: 0=SONY 1=EGOMAN 2=EMBEST
940
 *   PROCESSOR    12: 0=2835 1=2836
941
 *   TYPE         04: 0=MODELA 1=MODELB 2=MODELA+ 3=MODELB+ 4=Pi2 MODEL B 5=ALPHA 6=CM
942
 *   REV          00: 0=REV0 1=REV1 2=REV2
943
 *********************************************************************************
944
 */
945

    
946
void piBoardId (int *model, int *rev, int *mem, int *maker, int *warranty)
947
{
948
  FILE *cpuFd ;
949
  char line [120] ;
950
  char *c ;
951
  unsigned int revision ;
952
  int bRev, bType, bProc, bMfg, bMem, bWarranty ;
953

    
954
//        Will deal with the properly later on - for now, lets just get it going...
955
//  unsigned int modelNum ;
956

    
957
  (void)piGpioLayout () ;        // Call this first to make sure all's OK. Don't care about the result.
958

    
959
  if ((cpuFd = fopen ("/proc/cpuinfo", "r")) == NULL)
960
    piGpioLayoutOops ("Unable to open /proc/cpuinfo") ;
961

    
962
  while (fgets (line, 120, cpuFd) != NULL)
963
    if (strncmp (line, "Revision", 8) == 0)
964
      break ;
965

    
966
  fclose (cpuFd) ;
967

    
968
  if (strncmp (line, "Revision", 8) != 0)
969
    piGpioLayoutOops ("No \"Revision\" line") ;
970

    
971
// Chomp trailing CR/NL
972

    
973
  for (c = &line [strlen (line) - 1] ; (*c == '\n') || (*c == '\r') ; --c)
974
    *c = 0 ;
975
  
976
  if (wiringPiDebug)
977
    printf ("piBoardId: Revision string: %s\n", line) ;
978

    
979
// Need to work out if it's using the new or old encoding scheme:
980

    
981
// Scan to the first character of the revision number
982

    
983
  for (c = line ; *c ; ++c)
984
    if (*c == ':')
985
      break ;
986

    
987
  if (*c != ':')
988
    piGpioLayoutOops ("Bogus \"Revision\" line (no colon)") ;
989

    
990
// Chomp spaces
991

    
992
  ++c ;
993
  while (isspace (*c))
994
    ++c ;
995

    
996
  if (!isxdigit (*c))
997
    piGpioLayoutOops ("Bogus \"Revision\" line (no hex digit at start of revision)") ;
998

    
999
  revision = (unsigned int)strtol (c, NULL, 16) ; // Hex number with no leading 0x
1000

    
1001
// Check for new way:
1002

    
1003
  if ((revision &  (1 << 23)) != 0)        // New way
1004
  {
1005
    if (wiringPiDebug)
1006
      printf ("piBoardId: New Way: revision is: %08X\n", revision) ;
1007

    
1008
    bRev      = (revision & (0x0F <<  0)) >>  0 ;
1009
    bType     = (revision & (0xFF <<  4)) >>  4 ;
1010
    bProc     = (revision & (0x0F << 12)) >> 12 ;        // Not used for now.
1011
    bMfg      = (revision & (0x0F << 16)) >> 16 ;
1012
    bMem      = (revision & (0x07 << 20)) >> 20 ;
1013
    bWarranty = (revision & (0x03 << 24)) != 0 ;
1014
    
1015
    *model    = bType ;
1016
    *rev      = bRev ;
1017
    *mem      = bMem ;
1018
    *maker    = bMfg  ;
1019
    *warranty = bWarranty ;
1020

    
1021
    if (wiringPiDebug)
1022
      printf ("piBoardId: rev: %d, type: %d, proc: %d, mfg: %d, mem: %d, warranty: %d\n",
1023
                bRev, bType, bProc, bMfg, bMem, bWarranty) ;
1024
  }
1025
  else                                        // Old way
1026
  {
1027
    if (wiringPiDebug)
1028
      printf ("piBoardId: Old Way: revision is: %s\n", c) ;
1029

    
1030
    if (!isdigit (*c))
1031
      piGpioLayoutOops ("Bogus \"Revision\" line (no digit at start of revision)") ;
1032

    
1033
// Make sure its long enough
1034

    
1035
    if (strlen (c) < 4)
1036
      piGpioLayoutOops ("Bogus \"Revision\" line (not long enough)") ;
1037

    
1038
// If longer than 4, we'll assume it's been overvolted
1039

    
1040
    *warranty = strlen (c) > 4 ;
1041
  
1042
// Extract last 4 characters:
1043

    
1044
    c = c + strlen (c) - 4 ;
1045

    
1046
// Fill out the replys as appropriate
1047

    
1048
    /**/ if (strcmp (c, "0002") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1   ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1049
    else if (strcmp (c, "0003") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1050

    
1051
    else if (strcmp (c, "0004") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_SONY    ; }
1052
    else if (strcmp (c, "0005") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1053
    else if (strcmp (c, "0006") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1054

    
1055
    else if (strcmp (c, "0007") == 0) { *model = PI_MODEL_A  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1056
    else if (strcmp (c, "0008") == 0) { *model = PI_MODEL_A  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_SONY ;  ; }
1057
    else if (strcmp (c, "0009") == 0) { *model = PI_MODEL_A  ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1058

    
1059
    else if (strcmp (c, "000d") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN  ; }
1060
    else if (strcmp (c, "000e") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY    ; }
1061
    else if (strcmp (c, "000f") == 0) { *model = PI_MODEL_B  ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN  ; }
1062

    
1063
    else if (strcmp (c, "0010") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY    ; }
1064
    else if (strcmp (c, "0013") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EMBEST  ; }
1065
    else if (strcmp (c, "0016") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY    ; }
1066
    else if (strcmp (c, "0019") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN  ; }
1067

    
1068
    else if (strcmp (c, "0011") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_SONY    ; }
1069
    else if (strcmp (c, "0014") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EMBEST  ; }
1070
    else if (strcmp (c, "0017") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_SONY    ; }
1071
    else if (strcmp (c, "001a") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN  ; }
1072

    
1073
    else if (strcmp (c, "0012") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_SONY    ; }
1074
    else if (strcmp (c, "0015") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EMBEST  ; }
1075
    else if (strcmp (c, "0018") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_SONY    ; }
1076
    else if (strcmp (c, "001b") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN  ; }
1077

    
1078
    else                              { *model = 0           ; *rev = 0              ; *mem =   0 ; *maker = 0 ;               }
1079
  }
1080
}
1081
 
1082

    
1083

    
1084
/*
1085
 * wpiPinToGpio:
1086
 *        Translate a wiringPi Pin number to native GPIO pin number.
1087
 *        Provided for external support.
1088
 *********************************************************************************
1089
 */
1090

    
1091
int wpiPinToGpio (int wpiPin)
1092
{
1093
  return pinToGpio [wpiPin & 63] ;
1094
}
1095

    
1096

    
1097
/*
1098
 * physPinToGpio:
1099
 *        Translate a physical Pin number to native GPIO pin number.
1100
 *        Provided for external support.
1101
 *********************************************************************************
1102
 */
1103

    
1104
int physPinToGpio (int physPin)
1105
{
1106
  return physToGpio [physPin & 63] ;
1107
}
1108

    
1109

    
1110
/*
1111
 * setPadDrive:
1112
 *        Set the PAD driver value
1113
 *********************************************************************************
1114
 */
1115

    
1116
void setPadDrive (int group, int value)
1117
{
1118
  uint32_t wrVal ;
1119

    
1120
  if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
1121
  {
1122
    if ((group < 0) || (group > 2))
1123
      return ;
1124

    
1125
    wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
1126
    *(pads + group + 11) = wrVal ;
1127

    
1128
    if (wiringPiDebug)
1129
    {
1130
      printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
1131
      printf ("Read : %08X\n", *(pads + group + 11)) ;
1132
    }
1133
  }
1134
}
1135

    
1136

    
1137
/*
1138
 * getAlt:
1139
 *        Returns the ALT bits for a given port. Only really of-use
1140
 *        for the gpio readall command (I think)
1141
 *********************************************************************************
1142
 */
1143

    
1144
int getAlt (int pin)
1145
{
1146
  int fSel, shift, alt ;
1147

    
1148
  pin &= 63 ;
1149

    
1150
  /**/ if (wiringPiMode == WPI_MODE_PINS)
1151
    pin = pinToGpio [pin] ;
1152
  else if (wiringPiMode == WPI_MODE_PHYS)
1153
    pin = physToGpio [pin] ;
1154
  else if (wiringPiMode != WPI_MODE_GPIO)
1155
    return 0 ;
1156

    
1157
  fSel    = gpioToGPFSEL [pin] ;
1158
  shift   = gpioToShift  [pin] ;
1159

    
1160
  alt = (*(gpio + fSel) >> shift) & 7 ;
1161

    
1162
  return alt ;
1163
}
1164

    
1165

    
1166
/*
1167
 * pwmSetMode:
1168
 *        Select the native "balanced" mode, or standard mark:space mode
1169
 *********************************************************************************
1170
 */
1171

    
1172
void pwmSetMode (int mode)
1173
{
1174
  if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
1175
  {
1176
    if (mode == PWM_MODE_MS)
1177
      *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
1178
    else
1179
      *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
1180
  }
1181
}
1182

    
1183

    
1184
/*
1185
 * pwmSetRange:
1186
 *        Set the PWM range register. We set both range registers to the same
1187
 *        value. If you want different in your own code, then write your own.
1188
 *********************************************************************************
1189
 */
1190

    
1191
void pwmSetRange (unsigned int range)
1192
{
1193
  if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
1194
  {
1195
    *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
1196
    *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
1197
  }
1198
}
1199

    
1200

    
1201
/*
1202
 * pwmSetClock:
1203
 *        Set/Change the PWM clock. Originally my code, but changed
1204
 *        (for the better!) by Chris Hall, <chris@kchall.plus.com>
1205
 *        after further study of the manual and testing with a 'scope
1206
 *********************************************************************************
1207
 */
1208

    
1209
void pwmSetClock (int divisor)
1210
{
1211
  uint32_t pwm_control ;
1212
  divisor &= 4095 ;
1213

    
1214
  if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
1215
  {
1216
    if (wiringPiDebug)
1217
      printf ("Setting to: %d. Current: 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
1218

    
1219
    pwm_control = *(pwm + PWM_CONTROL) ;                // preserve PWM_CONTROL
1220

    
1221
// We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
1222
// stays high.
1223

    
1224
    *(pwm + PWM_CONTROL) = 0 ;                                // Stop PWM
1225

    
1226
// Stop PWM clock before changing divisor. The delay after this does need to
1227
// this big (95uS occasionally fails, 100uS OK), it's almost as though the BUSY
1228
// flag is not working properly in balanced mode. Without the delay when DIV is
1229
// adjusted the clock sometimes switches to very slow, once slow further DIV
1230
// adjustments do nothing and it's difficult to get out of this mode.
1231

    
1232
    *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ;        // Stop PWM Clock
1233
      delayMicroseconds (110) ;                        // prevents clock going sloooow
1234

    
1235
    while ((*(clk + PWMCLK_CNTL) & 0x80) != 0)        // Wait for clock to be !BUSY
1236
      delayMicroseconds (1) ;
1237

    
1238
    *(clk + PWMCLK_DIV)  = BCM_PASSWORD | (divisor << 12) ;
1239

    
1240
    *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ;        // Start PWM clock
1241
    *(pwm + PWM_CONTROL) = pwm_control ;                // restore PWM_CONTROL
1242

    
1243
    if (wiringPiDebug)
1244
      printf ("Set     to: %d. Now    : 0x%08X\n", divisor, *(clk + PWMCLK_DIV)) ;
1245
  }
1246
}
1247

    
1248

    
1249
/*
1250
 * gpioClockSet:
1251
 *        Set the frequency on a GPIO clock pin
1252
 *********************************************************************************
1253
 */
1254

    
1255
void gpioClockSet (int pin, int freq)
1256
{
1257
  int divi, divr, divf ;
1258

    
1259
  pin &= 63 ;
1260

    
1261
  /**/ if (wiringPiMode == WPI_MODE_PINS)
1262
    pin = pinToGpio [pin] ;
1263
  else if (wiringPiMode == WPI_MODE_PHYS)
1264
    pin = physToGpio [pin] ;
1265
  else if (wiringPiMode != WPI_MODE_GPIO)
1266
    return ;
1267
  
1268
  divi = 19200000 / freq ;
1269
  divr = 19200000 % freq ;
1270
  divf = (int)((double)divr * 4096.0 / 19200000.0) ;
1271

    
1272
  if (divi > 4095)
1273
    divi = 4095 ;
1274

    
1275
  *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | GPIO_CLOCK_SOURCE ;                // Stop GPIO Clock
1276
  while ((*(clk + gpioToClkCon [pin]) & 0x80) != 0)                                // ... and wait
1277
    ;
1278

    
1279
  *(clk + gpioToClkDiv [pin]) = BCM_PASSWORD | (divi << 12) | divf ;                // Set dividers
1280
  *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | 0x10 | GPIO_CLOCK_SOURCE ;        // Start Clock
1281
}
1282

    
1283

    
1284
/*
1285
 * wiringPiFindNode:
1286
 *      Locate our device node
1287
 *********************************************************************************
1288
 */
1289

    
1290
struct wiringPiNodeStruct *wiringPiFindNode (int pin)
1291
{
1292
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1293

    
1294
  while (node != NULL)
1295
    if ((pin >= node->pinBase) && (pin <= node->pinMax))
1296
      return node ;
1297
    else
1298
      node = node->next ;
1299

    
1300
  return NULL ;
1301
}
1302

    
1303

    
1304
/*
1305
 * wiringPiNewNode:
1306
 *        Create a new GPIO node into the wiringPi handling system
1307
 *********************************************************************************
1308
 */
1309

    
1310
static         void pinModeDummy             (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int mode)  { return ; }
1311
static         void pullUpDnControlDummy     (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int pud)   { return ; }
1312
static unsigned int digitalRead8Dummy        (UNU struct wiringPiNodeStruct *node, UNU int UNU pin)            { return 0 ; }
1313
static         void digitalWrite8Dummy       (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
1314
static          int digitalReadDummy         (UNU struct wiringPiNodeStruct *node, UNU int UNU pin)            { return LOW ; }
1315
static         void digitalWriteDummy        (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
1316
static         void pwmWriteDummy            (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
1317
static          int analogReadDummy          (UNU struct wiringPiNodeStruct *node, UNU int pin)            { return 0 ; }
1318
static         void analogWriteDummy         (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
1319

    
1320
struct wiringPiNodeStruct *wiringPiNewNode (int pinBase, int numPins)
1321
{
1322
  int    pin ;
1323
  struct wiringPiNodeStruct *node ;
1324

    
1325
// Minimum pin base is 64
1326

    
1327
  if (pinBase < 64)
1328
    (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: pinBase of %d is < 64\n", pinBase) ;
1329

    
1330
// Check all pins in-case there is overlap:
1331

    
1332
  for (pin = pinBase ; pin < (pinBase + numPins) ; ++pin)
1333
    if (wiringPiFindNode (pin) != NULL)
1334
      (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Pin %d overlaps with existing definition\n", pin) ;
1335

    
1336
  node = (struct wiringPiNodeStruct *)calloc (sizeof (struct wiringPiNodeStruct), 1) ;        // calloc zeros
1337
  if (node == NULL)
1338
    (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Unable to allocate memory: %s\n", strerror (errno)) ;
1339

    
1340
  node->pinBase          = pinBase ;
1341
  node->pinMax           = pinBase + numPins - 1 ;
1342
  node->pinMode          = pinModeDummy ;
1343
  node->pullUpDnControl  = pullUpDnControlDummy ;
1344
  node->digitalRead      = digitalReadDummy ;
1345
//node->digitalRead8     = digitalRead8Dummy ;
1346
  node->digitalWrite     = digitalWriteDummy ;
1347
//node->digitalWrite8    = digitalWrite8Dummy ;
1348
  node->pwmWrite         = pwmWriteDummy ;
1349
  node->analogRead       = analogReadDummy ;
1350
  node->analogWrite      = analogWriteDummy ;
1351
  node->next             = wiringPiNodes ;
1352
  wiringPiNodes          = node ;
1353

    
1354
  return node ;
1355
}
1356

    
1357

    
1358
#ifdef notYetReady
1359
/*
1360
 * pinED01:
1361
 * pinED10:
1362
 *        Enables edge-detect mode on a pin - from a 0 to a 1 or 1 to 0
1363
 *        Pin must already be in input mode with appropriate pull up/downs set.
1364
 *********************************************************************************
1365
 */
1366

    
1367
void pinEnableED01Pi (int pin)
1368
{
1369
  pin = pinToGpio [pin & 63] ;
1370
}
1371
#endif
1372

    
1373

    
1374
/*
1375
 *********************************************************************************
1376
 * Core Functions
1377
 *********************************************************************************
1378
 */
1379

    
1380
/*
1381
 * pinModeAlt:
1382
 *        This is an un-documented special to let you set any pin to any mode
1383
 *********************************************************************************
1384
 */
1385

    
1386
void pinModeAlt (int pin, int mode)
1387
{
1388
  int fSel, shift ;
1389

    
1390
  setupCheck ("pinModeAlt") ;
1391

    
1392
  if ((pin & PI_GPIO_MASK) == 0)                // On-board pin
1393
  {
1394
    /**/ if (wiringPiMode == WPI_MODE_PINS)
1395
      pin = pinToGpio [pin] ;
1396
    else if (wiringPiMode == WPI_MODE_PHYS)
1397
      pin = physToGpio [pin] ;
1398
    else if (wiringPiMode != WPI_MODE_GPIO)
1399
      return ;
1400

    
1401
    fSel  = gpioToGPFSEL [pin] ;
1402
    shift = gpioToShift  [pin] ;
1403

    
1404
    *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | ((mode & 0x7) << shift) ;
1405
  }
1406
}
1407

    
1408

    
1409
/*
1410
 * pinMode:
1411
 *        Sets the mode of a pin to be input, output or PWM output
1412
 *********************************************************************************
1413
 */
1414

    
1415
void pinMode (int pin, int mode)
1416
{
1417
  int    fSel, shift, alt ;
1418
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1419
  int origPin = pin ;
1420

    
1421
  setupCheck ("pinMode") ;
1422

    
1423
  if ((pin & PI_GPIO_MASK) == 0)                // On-board pin
1424
  {
1425
    /**/ if (wiringPiMode == WPI_MODE_PINS)
1426
      pin = pinToGpio [pin] ;
1427
    else if (wiringPiMode == WPI_MODE_PHYS)
1428
      pin = physToGpio [pin] ;
1429
    else if (wiringPiMode != WPI_MODE_GPIO)
1430
      return ;
1431

    
1432
    softPwmStop  (origPin) ;
1433
    softToneStop (origPin) ;
1434

    
1435
    fSel    = gpioToGPFSEL [pin] ;
1436
    shift   = gpioToShift  [pin] ;
1437

    
1438
    /**/ if (mode == INPUT)
1439
      *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
1440
    else if (mode == OUTPUT)
1441
      *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
1442
    else if (mode == SOFT_PWM_OUTPUT)
1443
      softPwmCreate (origPin, 0, 100) ;
1444
    else if (mode == SOFT_TONE_OUTPUT)
1445
      softToneCreate (origPin) ;
1446
    else if (mode == PWM_TONE_OUTPUT)
1447
    {
1448
      pinMode (origPin, PWM_OUTPUT) ;        // Call myself to enable PWM mode
1449
      pwmSetMode (PWM_MODE_MS) ;
1450
    }
1451
    else if (mode == PWM_OUTPUT)
1452
    {
1453
      if ((alt = gpioToPwmALT [pin]) == 0)        // Not a hardware capable PWM pin
1454
        return ;
1455

    
1456
      usingGpioMemCheck ("pinMode PWM") ;
1457

    
1458
// Set pin to PWM mode
1459

    
1460
      *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
1461
      delayMicroseconds (110) ;                // See comments in pwmSetClockWPi
1462

    
1463
      pwmSetMode  (PWM_MODE_BAL) ;        // Pi default mode
1464
      pwmSetRange (1024) ;                // Default range of 1024
1465
      pwmSetClock (32) ;                // 19.2 / 32 = 600KHz - Also starts the PWM
1466
    }
1467
    else if (mode == GPIO_CLOCK)
1468
    {
1469
      if ((alt = gpioToGpClkALT0 [pin]) == 0)        // Not a GPIO_CLOCK pin
1470
        return ;
1471

    
1472
      usingGpioMemCheck ("pinMode CLOCK") ;
1473

    
1474
// Set pin to GPIO_CLOCK mode and set the clock frequency to 100KHz
1475

    
1476
      *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
1477
      delayMicroseconds (110) ;
1478
      gpioClockSet      (pin, 100000) ;
1479
    }
1480
  }
1481
  else
1482
  {
1483
    if ((node = wiringPiFindNode (pin)) != NULL)
1484
      node->pinMode (node, pin, mode) ;
1485
    return ;
1486
  }
1487
}
1488

    
1489

    
1490
/*
1491
 * pullUpDownCtrl:
1492
 *        Control the internal pull-up/down resistors on a GPIO pin.
1493
 *********************************************************************************
1494
 */
1495

    
1496
void pullUpDnControl (int pin, int pud)
1497
{
1498
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1499

    
1500
  setupCheck ("pullUpDnControl") ;
1501

    
1502
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1503
  {
1504
    /**/ if (wiringPiMode == WPI_MODE_PINS)
1505
      pin = pinToGpio [pin] ;
1506
    else if (wiringPiMode == WPI_MODE_PHYS)
1507
      pin = physToGpio [pin] ;
1508
    else if (wiringPiMode != WPI_MODE_GPIO)
1509
      return ;
1510

    
1511
    *(gpio + GPPUD)              = pud & 3 ;                delayMicroseconds (5) ;
1512
    *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ;        delayMicroseconds (5) ;
1513
    
1514
    *(gpio + GPPUD)              = 0 ;                        delayMicroseconds (5) ;
1515
    *(gpio + gpioToPUDCLK [pin]) = 0 ;                        delayMicroseconds (5) ;
1516
  }
1517
  else                                                // Extension module
1518
  {
1519
    if ((node = wiringPiFindNode (pin)) != NULL)
1520
      node->pullUpDnControl (node, pin, pud) ;
1521
    return ;
1522
  }
1523
}
1524

    
1525

    
1526
/*
1527
 * digitalRead:
1528
 *        Read the value of a given Pin, returning HIGH or LOW
1529
 *********************************************************************************
1530
 */
1531

    
1532
int digitalRead (int pin)
1533
{
1534
  char c ;
1535
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1536

    
1537
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1538
  {
1539
    /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)        // Sys mode
1540
    {
1541
      if (sysFds [pin] == -1)
1542
        return LOW ;
1543

    
1544
      lseek  (sysFds [pin], 0L, SEEK_SET) ;
1545
      read   (sysFds [pin], &c, 1) ;
1546
      return (c == '0') ? LOW : HIGH ;
1547
    }
1548
    else if (wiringPiMode == WPI_MODE_PINS)
1549
      pin = pinToGpio [pin] ;
1550
    else if (wiringPiMode == WPI_MODE_PHYS)
1551
      pin = physToGpio [pin] ;
1552
    else if (wiringPiMode != WPI_MODE_GPIO)
1553
      return LOW ;
1554

    
1555
    if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
1556
      return HIGH ;
1557
    else
1558
      return LOW ;
1559
  }
1560
  else
1561
  {
1562
    if ((node = wiringPiFindNode (pin)) == NULL)
1563
      return LOW ;
1564
    return node->digitalRead (node, pin) ;
1565
  }
1566
}
1567

    
1568

    
1569
/*
1570
 * digitalRead8:
1571
 *        Read 8-bits (a byte) from given start pin.
1572
 *********************************************************************************
1573

1574
unsigned int digitalRead8 (int pin)
1575
{
1576
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1577

1578
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1579
    return 0 ;
1580
  else
1581
  {
1582
    if ((node = wiringPiFindNode (pin)) == NULL)
1583
      return LOW ;
1584
    return node->digitalRead8 (node, pin) ;
1585
  }
1586
}
1587
 */
1588

    
1589

    
1590
/*
1591
 * digitalWrite:
1592
 *        Set an output bit
1593
 *********************************************************************************
1594
 */
1595

    
1596
void digitalWrite (int pin, int value)
1597
{
1598
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1599

    
1600
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1601
  {
1602
    /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)        // Sys mode
1603
    {
1604
      if (sysFds [pin] != -1)
1605
      {
1606
        if (value == LOW)
1607
          write (sysFds [pin], "0\n", 2) ;
1608
        else
1609
          write (sysFds [pin], "1\n", 2) ;
1610
      }
1611
      return ;
1612
    }
1613
    else if (wiringPiMode == WPI_MODE_PINS)
1614
      pin = pinToGpio [pin] ;
1615
    else if (wiringPiMode == WPI_MODE_PHYS)
1616
      pin = physToGpio [pin] ;
1617
    else if (wiringPiMode != WPI_MODE_GPIO)
1618
      return ;
1619

    
1620
    if (value == LOW)
1621
      *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
1622
    else
1623
      *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
1624
  }
1625
  else
1626
  {
1627
    if ((node = wiringPiFindNode (pin)) != NULL)
1628
      node->digitalWrite (node, pin, value) ;
1629
  }
1630
}
1631

    
1632

    
1633
/*
1634
 * digitalWrite8:
1635
 *        Set an output 8-bit byte on the device from the given pin number
1636
 *********************************************************************************
1637

1638
void digitalWrite8 (int pin, int value)
1639
{
1640
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1641

1642
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1643
    return ;
1644
  else
1645
  {
1646
    if ((node = wiringPiFindNode (pin)) != NULL)
1647
      node->digitalWrite8 (node, pin, value) ;
1648
  }
1649
}
1650
 */
1651

    
1652

    
1653
/*
1654
 * pwmWrite:
1655
 *        Set an output PWM value
1656
 *********************************************************************************
1657
 */
1658

    
1659
void pwmWrite (int pin, int value)
1660
{
1661
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1662

    
1663
  setupCheck ("pwmWrite") ;
1664

    
1665
  if ((pin & PI_GPIO_MASK) == 0)                // On-Board Pin
1666
  {
1667
    /**/ if (wiringPiMode == WPI_MODE_PINS)
1668
      pin = pinToGpio [pin] ;
1669
    else if (wiringPiMode == WPI_MODE_PHYS)
1670
      pin = physToGpio [pin] ;
1671
    else if (wiringPiMode != WPI_MODE_GPIO)
1672
      return ;
1673

    
1674
    usingGpioMemCheck ("pwmWrite") ;
1675
    *(pwm + gpioToPwmPort [pin]) = value ;
1676
  }
1677
  else
1678
  {
1679
    if ((node = wiringPiFindNode (pin)) != NULL)
1680
      node->pwmWrite (node, pin, value) ;
1681
  }
1682
}
1683

    
1684

    
1685
/*
1686
 * analogRead:
1687
 *        Read the analog value of a given Pin. 
1688
 *        There is no on-board Pi analog hardware,
1689
 *        so this needs to go to a new node.
1690
 *********************************************************************************
1691
 */
1692

    
1693
int analogRead (int pin)
1694
{
1695
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1696

    
1697
  if ((node = wiringPiFindNode (pin)) == NULL)
1698
    return 0 ;
1699
  else
1700
    return node->analogRead (node, pin) ;
1701
}
1702

    
1703

    
1704
/*
1705
 * analogWrite:
1706
 *        Write the analog value to the given Pin. 
1707
 *        There is no on-board Pi analog hardware,
1708
 *        so this needs to go to a new node.
1709
 *********************************************************************************
1710
 */
1711

    
1712
void analogWrite (int pin, int value)
1713
{
1714
  struct wiringPiNodeStruct *node = wiringPiNodes ;
1715

    
1716
  if ((node = wiringPiFindNode (pin)) == NULL)
1717
    return ;
1718

    
1719
  node->analogWrite (node, pin, value) ;
1720
}
1721

    
1722

    
1723
/*
1724
 * pwmToneWrite:
1725
 *        Pi Specific.
1726
 *      Output the given frequency on the Pi's PWM pin
1727
 *********************************************************************************
1728
 */
1729

    
1730
void pwmToneWrite (int pin, int freq)
1731
{
1732
  int range ;
1733

    
1734
  setupCheck ("pwmToneWrite") ;
1735

    
1736
  if (freq == 0)
1737
    pwmWrite (pin, 0) ;             // Off
1738
  else
1739
  {
1740
    range = 600000 / freq ;
1741
    pwmSetRange (range) ;
1742
    pwmWrite    (pin, freq / 2) ;
1743
  }
1744
}
1745

    
1746

    
1747

    
1748
/*
1749
 * digitalWriteByte:
1750
 * digitalReadByte:
1751
 *        Pi Specific
1752
 *        Write an 8-bit byte to the first 8 GPIO pins - try to do it as
1753
 *        fast as possible.
1754
 *        However it still needs 2 operations to set the bits, so any external
1755
 *        hardware must not rely on seeing a change as there will be a change 
1756
 *        to set the outputs bits to zero, then another change to set the 1's
1757
 *        Reading is just bit fiddling.
1758
 *        These are wiringPi pin numbers 0..7, or BCM_GPIO pin numbers
1759
 *        17, 18, 22, 23, 24, 24, 4 on a Pi v1 rev 0-3
1760
 *        17, 18, 27, 23, 24, 24, 4 on a Pi v1 rev 3 onwards or B+, 2, 3, zero
1761
 *********************************************************************************
1762
 */
1763

    
1764
void digitalWriteByte (const int value)
1765
{
1766
  uint32_t pinSet = 0 ;
1767
  uint32_t pinClr = 0 ;
1768
  int mask = 1 ;
1769
  int pin ;
1770

    
1771
  /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)
1772
  {
1773
    for (pin = 0 ; pin < 8 ; ++pin)
1774
    {
1775
      digitalWrite (pinToGpio [pin], value & mask) ;
1776
      mask <<= 1 ;
1777
    }
1778
    return ;
1779
  }
1780
  else
1781
  {
1782
    for (pin = 0 ; pin < 8 ; ++pin)
1783
    {
1784
      if ((value & mask) == 0)
1785
        pinClr |= (1 << pinToGpio [pin]) ;
1786
      else
1787
        pinSet |= (1 << pinToGpio [pin]) ;
1788

    
1789
      mask <<= 1 ;
1790
    }
1791

    
1792
    *(gpio + gpioToGPCLR [0]) = pinClr ;
1793
    *(gpio + gpioToGPSET [0]) = pinSet ;
1794
  }
1795
}
1796

    
1797
unsigned int digitalReadByte (void)
1798
{
1799
  int pin, x ;
1800
  uint32_t raw ;
1801
  uint32_t data = 0 ;
1802

    
1803
  /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)
1804
  {
1805
    for (pin = 0 ; pin < 8 ; ++pin)
1806
    {
1807
      x = digitalRead (pinToGpio [pin]) ;
1808
      data = (data << 1) | x ;
1809
    }
1810
  }
1811
  else 
1812
  {
1813
    raw = *(gpio + gpioToGPLEV [0]) ; // First bank for these pins
1814
    for (pin = 0 ; pin < 8 ; ++pin)
1815
    {
1816
      x = pinToGpio [pin] ;
1817
      data = (data << 1) | (((raw & (1 << x)) == 0) ? 0 : 1) ;
1818
    }
1819
  }
1820
  return data ;
1821
}
1822

    
1823

    
1824
/*
1825
 * digitalWriteByte2:
1826
 * digitalReadByte2:
1827
 *        Pi Specific
1828
 *        Write an 8-bit byte to the second set of 8 GPIO pins. This is marginally
1829
 *        faster than the first lot as these are consecutive BCM_GPIO pin numbers.
1830
 *        However they overlap with the original read/write bytes.
1831
 *********************************************************************************
1832
 */
1833

    
1834
void digitalWriteByte2 (const int value)
1835
{
1836
  register int mask = 1 ;
1837
  register int pin ;
1838

    
1839
  /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)
1840
  {
1841
    for (pin = 20 ; pin < 28 ; ++pin)
1842
    {
1843
      digitalWrite (pin, value & mask) ;
1844
      mask <<= 1 ;
1845
    }
1846
    return ;
1847
  }
1848
  else
1849
  {
1850
    *(gpio + gpioToGPCLR [0]) = (~value & 0xFF) << 20 ; // 0x0FF00000; ILJ > CHANGE: Old causes glitch
1851
    *(gpio + gpioToGPSET [0]) = ( value & 0xFF) << 20 ;
1852
  }
1853
}
1854

    
1855
unsigned int digitalReadByte2 (void)
1856
{
1857
  int pin, x ;
1858
  uint32_t data = 0 ;
1859

    
1860
  /**/ if (wiringPiMode == WPI_MODE_GPIO_SYS)
1861
  {
1862
    for (pin = 20 ; pin < 28 ; ++pin)
1863
    {
1864
      x = digitalRead (pin) ;
1865
      data = (data << 1) | x ;
1866
    }
1867
  }
1868
  else 
1869
    data = ((*(gpio + gpioToGPLEV [0])) >> 20) & 0xFF ; // First bank for these pins
1870

    
1871
  return data ;
1872
}
1873

    
1874

    
1875
/*
1876
 * waitForInterrupt:
1877
 *        Pi Specific.
1878
 *        Wait for Interrupt on a GPIO pin.
1879
 *        This is actually done via the /sys/class/gpio interface regardless of
1880
 *        the wiringPi access mode in-use. Maybe sometime it might get a better
1881
 *        way for a bit more efficiency.
1882
 *********************************************************************************
1883
 */
1884

    
1885
int waitForInterrupt (int pin, int mS)
1886
{
1887
  int fd, x ;
1888
  uint8_t c ;
1889
  struct pollfd polls ;
1890

    
1891
  /**/ if (wiringPiMode == WPI_MODE_PINS)
1892
    pin = pinToGpio [pin] ;
1893
  else if (wiringPiMode == WPI_MODE_PHYS)
1894
    pin = physToGpio [pin] ;
1895

    
1896
  if ((fd = sysFds [pin]) == -1)
1897
    return -2 ;
1898

    
1899
// Setup poll structure
1900

    
1901
  polls.fd     = fd ;
1902
  polls.events = POLLPRI | POLLERR ;
1903

    
1904
// Wait for it ...
1905

    
1906
  x = poll (&polls, 1, mS) ;
1907

    
1908
// If no error, do a dummy read to clear the interrupt
1909
//        A one character read appars to be enough.
1910

    
1911
  if (x > 0)
1912
  {
1913
    lseek (fd, 0, SEEK_SET) ;        // Rewind
1914
    (void)read (fd, &c, 1) ;        // Read & clear
1915
  }
1916

    
1917
  return x ;
1918
}
1919

    
1920

    
1921
/*
1922
 * interruptHandler:
1923
 *        This is a thread and gets started to wait for the interrupt we're
1924
 *        hoping to catch. It will call the user-function when the interrupt
1925
 *        fires.
1926
 *********************************************************************************
1927
 */
1928

    
1929
static void *interruptHandler (UNU void *arg)
1930
{
1931
  int myPin ;
1932

    
1933
  (void)piHiPri (55) ;        // Only effective if we run as root
1934

    
1935
  myPin   = pinPass ;
1936
  pinPass = -1 ;
1937

    
1938
  for (;;)
1939
    if (waitForInterrupt (myPin, -1) > 0)
1940
      isrFunctions [myPin] () ;
1941

    
1942
  return NULL ;
1943
}
1944

    
1945

    
1946
/*
1947
 * wiringPiISR:
1948
 *        Pi Specific.
1949
 *        Take the details and create an interrupt handler that will do a call-
1950
 *        back to the user supplied function.
1951
 *********************************************************************************
1952
 */
1953

    
1954
int wiringPiISR (int pin, int mode, void (*function)(void))
1955
{
1956
  pthread_t threadId ;
1957
  const char *modeS ;
1958
  char fName   [64] ;
1959
  char  pinS [8] ;
1960
  pid_t pid ;
1961
  int   count, i ;
1962
  char  c ;
1963
  int   bcmGpioPin ;
1964

    
1965
  if ((pin < 0) || (pin > 63))
1966
    return wiringPiFailure (WPI_FATAL, "wiringPiISR: pin must be 0-63 (%d)\n", pin) ;
1967

    
1968
  /**/ if (wiringPiMode == WPI_MODE_UNINITIALISED)
1969
    return wiringPiFailure (WPI_FATAL, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
1970
  else if (wiringPiMode == WPI_MODE_PINS)
1971
    bcmGpioPin = pinToGpio [pin] ;
1972
  else if (wiringPiMode == WPI_MODE_PHYS)
1973
    bcmGpioPin = physToGpio [pin] ;
1974
  else
1975
    bcmGpioPin = pin ;
1976

    
1977
// Now export the pin and set the right edge
1978
//        We're going to use the gpio program to do this, so it assumes
1979
//        a full installation of wiringPi. It's a bit 'clunky', but it
1980
//        is a way that will work when we're running in "Sys" mode, as
1981
//        a non-root user. (without sudo)
1982

    
1983
  if (mode != INT_EDGE_SETUP)
1984
  {
1985
    /**/ if (mode == INT_EDGE_FALLING)
1986
      modeS = "falling" ;
1987
    else if (mode == INT_EDGE_RISING)
1988
      modeS = "rising" ;
1989
    else
1990
      modeS = "both" ;
1991

    
1992
    sprintf (pinS, "%d", bcmGpioPin) ;
1993

    
1994
    if ((pid = fork ()) < 0)        // Fail
1995
      return wiringPiFailure (WPI_FATAL, "wiringPiISR: fork failed: %s\n", strerror (errno)) ;
1996

    
1997
    if (pid == 0)        // Child, exec
1998
    {
1999
      /**/ if (access ("/usr/local/bin/gpio", X_OK) == 0)
2000
      {
2001
        execl ("/usr/local/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
2002
        return wiringPiFailure (WPI_FATAL, "wiringPiISR: execl failed: %s\n", strerror (errno)) ;
2003
      }
2004
      else if (access ("/usr/bin/gpio", X_OK) == 0)
2005
      {
2006
        execl ("/usr/bin/gpio", "gpio", "edge", pinS, modeS, (char *)NULL) ;
2007
        return wiringPiFailure (WPI_FATAL, "wiringPiISR: execl failed: %s\n", strerror (errno)) ;
2008
      }
2009
      else
2010
        return wiringPiFailure (WPI_FATAL, "wiringPiISR: Can't find gpio program\n") ;
2011
    }
2012
    else                // Parent, wait
2013
      wait (NULL) ;
2014
  }
2015

    
2016
// Now pre-open the /sys/class node - but it may already be open if
2017
//        we are in Sys mode...
2018

    
2019
  if (sysFds [bcmGpioPin] == -1)
2020
  {
2021
    sprintf (fName, "/sys/class/gpio/gpio%d/value", bcmGpioPin) ;
2022
    if ((sysFds [bcmGpioPin] = open (fName, O_RDWR)) < 0)
2023
      return wiringPiFailure (WPI_FATAL, "wiringPiISR: unable to open %s: %s\n", fName, strerror (errno)) ;
2024
  }
2025

    
2026
// Clear any initial pending interrupt
2027

    
2028
  ioctl (sysFds [bcmGpioPin], FIONREAD, &count) ;
2029
  for (i = 0 ; i < count ; ++i)
2030
    read (sysFds [bcmGpioPin], &c, 1) ;
2031

    
2032
  isrFunctions [pin] = function ;
2033

    
2034
  pthread_mutex_lock (&pinMutex) ;
2035
    pinPass = pin ;
2036
    pthread_create (&threadId, NULL, interruptHandler, NULL) ;
2037
    while (pinPass != -1)
2038
      delay (1) ;
2039
  pthread_mutex_unlock (&pinMutex) ;
2040

    
2041
  return 0 ;
2042
}
2043

    
2044

    
2045
/*
2046
 * initialiseEpoch:
2047
 *        Initialise our start-of-time variable to be the current unix
2048
 *        time in milliseconds and microseconds.
2049
 *********************************************************************************
2050
 */
2051

    
2052
static void initialiseEpoch (void)
2053
{
2054
#ifdef        OLD_WAY
2055
  struct timeval tv ;
2056

    
2057
  gettimeofday (&tv, NULL) ;
2058
  epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000    + (uint64_t)(tv.tv_usec / 1000) ;
2059
  epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
2060
#else
2061
  struct timespec ts ;
2062

    
2063
  clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
2064
  epochMilli = (uint64_t)ts.tv_sec * (uint64_t)1000    + (uint64_t)(ts.tv_nsec / 1000000L) ;
2065
  epochMicro = (uint64_t)ts.tv_sec * (uint64_t)1000000 + (uint64_t)(ts.tv_nsec /    1000L) ;
2066
#endif
2067
}
2068

    
2069

    
2070
/*
2071
 * delay:
2072
 *        Wait for some number of milliseconds
2073
 *********************************************************************************
2074
 */
2075

    
2076
void delay (unsigned int howLong)
2077
{
2078
  struct timespec sleeper, dummy ;
2079

    
2080
  sleeper.tv_sec  = (time_t)(howLong / 1000) ;
2081
  sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
2082

    
2083
  nanosleep (&sleeper, &dummy) ;
2084
}
2085

    
2086

    
2087
/*
2088
 * delayMicroseconds:
2089
 *        This is somewhat intersting. It seems that on the Pi, a single call
2090
 *        to nanosleep takes some 80 to 130 microseconds anyway, so while
2091
 *        obeying the standards (may take longer), it's not always what we
2092
 *        want!
2093
 *
2094
 *        So what I'll do now is if the delay is less than 100uS we'll do it
2095
 *        in a hard loop, watching a built-in counter on the ARM chip. This is
2096
 *        somewhat sub-optimal in that it uses 100% CPU, something not an issue
2097
 *        in a microcontroller, but under a multi-tasking, multi-user OS, it's
2098
 *        wastefull, however we've no real choice )-:
2099
 *
2100
 *      Plan B: It seems all might not be well with that plan, so changing it
2101
 *      to use gettimeofday () and poll on that instead...
2102
 *********************************************************************************
2103
 */
2104

    
2105
void delayMicrosecondsHard (unsigned int howLong)
2106
{
2107
  struct timeval tNow, tLong, tEnd ;
2108

    
2109
  gettimeofday (&tNow, NULL) ;
2110
  tLong.tv_sec  = howLong / 1000000 ;
2111
  tLong.tv_usec = howLong % 1000000 ;
2112
  timeradd (&tNow, &tLong, &tEnd) ;
2113

    
2114
  while (timercmp (&tNow, &tEnd, <))
2115
    gettimeofday (&tNow, NULL) ;
2116
}
2117

    
2118
void delayMicroseconds (unsigned int howLong)
2119
{
2120
  struct timespec sleeper ;
2121
  unsigned int uSecs = howLong % 1000000 ;
2122
  unsigned int wSecs = howLong / 1000000 ;
2123

    
2124
  /**/ if (howLong ==   0)
2125
    return ;
2126
  else if (howLong  < 100)
2127
    delayMicrosecondsHard (howLong) ;
2128
  else
2129
  {
2130
    sleeper.tv_sec  = wSecs ;
2131
    sleeper.tv_nsec = (long)(uSecs * 1000L) ;
2132
    nanosleep (&sleeper, NULL) ;
2133
  }
2134
}
2135

    
2136

    
2137
/*
2138
 * millis:
2139
 *        Return a number of milliseconds as an unsigned int.
2140
 *        Wraps at 49 days.
2141
 *********************************************************************************
2142
 */
2143

    
2144
unsigned int millis (void)
2145
{
2146
  uint64_t now ;
2147

    
2148
#ifdef        OLD_WAY
2149
  struct timeval tv ;
2150

    
2151
  gettimeofday (&tv, NULL) ;
2152
  now  = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
2153

    
2154
#else
2155
  struct  timespec ts ;
2156

    
2157
  clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
2158
  now  = (uint64_t)ts.tv_sec * (uint64_t)1000 + (uint64_t)(ts.tv_nsec / 1000000L) ;
2159
#endif
2160

    
2161
  return (uint32_t)(now - epochMilli) ;
2162
}
2163

    
2164

    
2165
/*
2166
 * micros:
2167
 *        Return a number of microseconds as an unsigned int.
2168
 *        Wraps after 71 minutes.
2169
 *********************************************************************************
2170
 */
2171

    
2172
unsigned int micros (void)
2173
{
2174
  uint64_t now ;
2175
#ifdef        OLD_WAY
2176
  struct timeval tv ;
2177

    
2178
  gettimeofday (&tv, NULL) ;
2179
  now  = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
2180
#else
2181
  struct  timespec ts ;
2182

    
2183
  clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
2184
  now  = (uint64_t)ts.tv_sec * (uint64_t)1000000 + (uint64_t)(ts.tv_nsec / 1000) ;
2185
#endif
2186

    
2187

    
2188
  return (uint32_t)(now - epochMicro) ;
2189
}
2190

    
2191
/*
2192
 * wiringPiVersion:
2193
 *        Return our current version number
2194
 *********************************************************************************
2195
 */
2196

    
2197
void wiringPiVersion (int *major, int *minor)
2198
{
2199
  *major = VERSION_MAJOR ;
2200
  *minor = VERSION_MINOR ;
2201
}
2202

    
2203

    
2204
/*
2205
 * wiringPiSetup:
2206
 *        Must be called once at the start of your program execution.
2207
 *
2208
 * Default setup: Initialises the system into wiringPi Pin mode and uses the
2209
 *        memory mapped hardware directly.
2210
 *
2211
 * Changed now to revert to "gpio" mode if we're running on a Compute Module.
2212
 *********************************************************************************
2213
 */
2214

    
2215
int wiringPiSetup (void)
2216
{
2217
  int   fd ;
2218
  int   model, rev, mem, maker, overVolted ;
2219

    
2220
// It's actually a fatal error to call any of the wiringPiSetup routines more than once,
2221
//        (you run out of file handles!) but I'm fed-up with the useless twats who email
2222
//        me bleating that there is a bug in my code, so screw-em.
2223

    
2224
  if (wiringPiSetuped)
2225
    return 0 ;
2226

    
2227
  wiringPiSetuped = TRUE ;
2228

    
2229
  if (getenv (ENV_DEBUG) != NULL)
2230
    wiringPiDebug = TRUE ;
2231

    
2232
  if (getenv (ENV_CODES) != NULL)
2233
    wiringPiReturnCodes = TRUE ;
2234

    
2235
  if (wiringPiDebug)
2236
    printf ("wiringPi: wiringPiSetup called\n") ;
2237

    
2238
// Get the board ID information. We're not really using the information here,
2239
//        but it will give us information like the GPIO layout scheme (2 variants
2240
//        on the older 26-pin Pi's) and the GPIO peripheral base address.
2241
//        and if we're running on a compute module, then wiringPi pin numbers
2242
//        don't really many anything, so force native BCM mode anyway.
2243

    
2244
  piBoardId (&model, &rev, &mem, &maker, &overVolted) ;
2245

    
2246
  if ((model == PI_MODEL_CM) || (model == PI_MODEL_CM3) || (model == PI_MODEL_CM3P))
2247
    wiringPiMode = WPI_MODE_GPIO ;
2248
  else
2249
    wiringPiMode = WPI_MODE_PINS ;
2250

    
2251
  /**/ if (piGpioLayout () == 1)        // A, B, Rev 1, 1.1
2252
  {
2253
     pinToGpio =  pinToGpioR1 ;
2254
    physToGpio = physToGpioR1 ;
2255
  }
2256
  else                                         // A2, B2, A+, B+, CM, Pi2, Pi3, Zero
2257
  {
2258
     pinToGpio =  pinToGpioR2 ;
2259
    physToGpio = physToGpioR2 ;
2260
  }
2261

    
2262
// ...
2263

    
2264
  switch (model)
2265
  {
2266
    case PI_MODEL_A:        case PI_MODEL_B:
2267
    case PI_MODEL_AP:        case PI_MODEL_BP:
2268
    case PI_ALPHA:        case PI_MODEL_CM:
2269
    case PI_MODEL_ZERO:        case PI_MODEL_ZERO_W:
2270
      piGpioBase = GPIO_PERI_BASE_OLD ;
2271
      break ;
2272

    
2273
    default:
2274
      piGpioBase = GPIO_PERI_BASE_NEW ;
2275
      break ;
2276
  }
2277

    
2278
// Open the master /dev/ memory control device
2279
// Device strategy: December 2016:
2280
//        Try /dev/mem. If that fails, then 
2281
//        try /dev/gpiomem. If that fails then game over.
2282

    
2283
  if ((fd = open ("/dev/mem", O_RDWR | O_SYNC | O_CLOEXEC)) < 0)
2284
  {
2285
    if ((fd = open ("/dev/gpiomem", O_RDWR | O_SYNC | O_CLOEXEC) ) >= 0)        // We're using gpiomem
2286
    {
2287
      piGpioBase   = 0 ;
2288
      usingGpioMem = TRUE ;
2289
    }
2290
    else
2291
      return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: Unable to open /dev/mem or /dev/gpiomem: %s.\n"
2292
        "  Aborting your program because if it can not access the GPIO\n"
2293
        "  hardware then it most certianly won't work\n"
2294
        "  Try running with sudo?\n", strerror (errno)) ;
2295
  }
2296

    
2297
// Set the offsets into the memory interface.
2298

    
2299
  GPIO_PADS           = piGpioBase + 0x00100000 ;
2300
  GPIO_CLOCK_BASE = piGpioBase + 0x00101000 ;
2301
  GPIO_BASE          = piGpioBase + 0x00200000 ;
2302
  GPIO_TIMER          = piGpioBase + 0x0000B000 ;
2303
  GPIO_PWM          = piGpioBase + 0x0020C000 ;
2304

    
2305
// Map the individual hardware components
2306

    
2307
//        GPIO:
2308

    
2309
  gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
2310
  if (gpio == MAP_FAILED)
2311
    return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (GPIO) failed: %s\n", strerror (errno)) ;
2312

    
2313
//        PWM
2314

    
2315
  pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
2316
  if (pwm == MAP_FAILED)
2317
    return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PWM) failed: %s\n", strerror (errno)) ;
2318
 
2319
//        Clock control (needed for PWM)
2320

    
2321
  clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_CLOCK_BASE) ;
2322
  if (clk == MAP_FAILED)
2323
    return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (CLOCK) failed: %s\n", strerror (errno)) ;
2324
 
2325
//        The drive pads
2326

    
2327
  pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
2328
  if (pads == MAP_FAILED)
2329
    return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PADS) failed: %s\n", strerror (errno)) ;
2330

    
2331
//        The system timer
2332

    
2333
  timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
2334
  if (timer == MAP_FAILED)
2335
    return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (TIMER) failed: %s\n", strerror (errno)) ;
2336

    
2337
// Set the timer to free-running, 1MHz.
2338
//        0xF9 is 249, the timer divide is base clock / (divide+1)
2339
//        so base clock is 250MHz / 250 = 1MHz.
2340

    
2341
  *(timer + TIMER_CONTROL) = 0x0000280 ;
2342
  *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
2343
  timerIrqRaw = timer + TIMER_IRQ_RAW ;
2344

    
2345
// Export the base addresses for any external software that might need them
2346

    
2347
  _wiringPiGpio  = gpio ;
2348
  _wiringPiPwm   = pwm ;
2349
  _wiringPiClk   = clk ;
2350
  _wiringPiPads  = pads ;
2351
  _wiringPiTimer = timer ;
2352

    
2353
  initialiseEpoch () ;
2354

    
2355
  return 0 ;
2356
}
2357

    
2358

    
2359
/*
2360
 * wiringPiSetupGpio:
2361
 *        Must be called once at the start of your program execution.
2362
 *
2363
 * GPIO setup: Initialises the system into GPIO Pin mode and uses the
2364
 *        memory mapped hardware directly.
2365
 *********************************************************************************
2366
 */
2367

    
2368
int wiringPiSetupGpio (void)
2369
{
2370
  (void)wiringPiSetup () ;
2371

    
2372
  if (wiringPiDebug)
2373
    printf ("wiringPi: wiringPiSetupGpio called\n") ;
2374

    
2375
  wiringPiMode = WPI_MODE_GPIO ;
2376

    
2377
  return 0 ;
2378
}
2379

    
2380

    
2381
/*
2382
 * wiringPiSetupPhys:
2383
 *        Must be called once at the start of your program execution.
2384
 *
2385
 * Phys setup: Initialises the system into Physical Pin mode and uses the
2386
 *        memory mapped hardware directly.
2387
 *********************************************************************************
2388
 */
2389

    
2390
int wiringPiSetupPhys (void)
2391
{
2392
  (void)wiringPiSetup () ;
2393

    
2394
  if (wiringPiDebug)
2395
    printf ("wiringPi: wiringPiSetupPhys called\n") ;
2396

    
2397
  wiringPiMode = WPI_MODE_PHYS ;
2398

    
2399
  return 0 ;
2400
}
2401

    
2402

    
2403
/*
2404
 * wiringPiSetupSys:
2405
 *        Must be called once at the start of your program execution.
2406
 *
2407
 * Initialisation (again), however this time we are using the /sys/class/gpio
2408
 *        interface to the GPIO systems - slightly slower, but always usable as
2409
 *        a non-root user, assuming the devices are already exported and setup correctly.
2410
 */
2411

    
2412
int wiringPiSetupSys (void)
2413
{
2414
  int pin ;
2415
  char fName [128] ;
2416

    
2417
  if (wiringPiSetuped)
2418
    return 0 ;
2419

    
2420
  wiringPiSetuped = TRUE ;
2421

    
2422
  if (getenv (ENV_DEBUG) != NULL)
2423
    wiringPiDebug = TRUE ;
2424

    
2425
  if (getenv (ENV_CODES) != NULL)
2426
    wiringPiReturnCodes = TRUE ;
2427

    
2428
  if (wiringPiDebug)
2429
    printf ("wiringPi: wiringPiSetupSys called\n") ;
2430

    
2431
  if (piGpioLayout () == 1)
2432
  {
2433
     pinToGpio =  pinToGpioR1 ;
2434
    physToGpio = physToGpioR1 ;
2435
  }
2436
  else
2437
  {
2438
     pinToGpio =  pinToGpioR2 ;
2439
    physToGpio = physToGpioR2 ;
2440
  }
2441

    
2442
// Open and scan the directory, looking for exported GPIOs, and pre-open
2443
//        the 'value' interface to speed things up for later
2444
  
2445
  for (pin = 0 ; pin < 64 ; ++pin)
2446
  {
2447
    sprintf (fName, "/sys/class/gpio/gpio%d/value", pin) ;
2448
    sysFds [pin] = open (fName, O_RDWR) ;
2449
  }
2450

    
2451
  initialiseEpoch () ;
2452

    
2453
  wiringPiMode = WPI_MODE_GPIO_SYS ;
2454

    
2455
  return 0 ;
2456
}