Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

2364 linhas
68 KiB

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