You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

3331 lines
100 KiB

  1. /*
  2. * wiringPi:
  3. * Arduino look-a-like Wiring library for the Raspberry Pi
  4. * Copyright (c) 2012-2024 Gordon Henderson and contributors
  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/WiringPi/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. // 19 Jul 2012:
  31. // Moved to the LGPL
  32. // Added an abstraction layer to the main routines to save a tiny
  33. // bit of run-time and make the clode a little cleaner (if a little
  34. // larger)
  35. // Added waitForInterrupt code
  36. // Added piHiPri code
  37. //
  38. // 9 Jul 2012:
  39. // Added in support to use the /sys/class/gpio interface.
  40. // 2 Jul 2012:
  41. // Fixed a few more bugs to do with range-checking when in GPIO mode.
  42. // 11 Jun 2012:
  43. // Fixed some typos.
  44. // Added c++ support for the .h file
  45. // Added a new function to allow for using my "pin" numbers, or native
  46. // GPIO pin numbers.
  47. // Removed my busy-loop delay and replaced it with a call to delayMicroseconds
  48. //
  49. // 02 May 2012:
  50. // Added in the 2 UART pins
  51. // Change maxPins to numPins to more accurately reflect purpose
  52. #include <stdio.h>
  53. #include <stdarg.h>
  54. #include <stdint.h>
  55. #include <stdlib.h>
  56. #include <ctype.h>
  57. #include <poll.h>
  58. #include <unistd.h>
  59. #include <errno.h>
  60. #include <string.h>
  61. #include <time.h>
  62. #include <fcntl.h>
  63. #include <pthread.h>
  64. #include <sys/time.h>
  65. #include <sys/mman.h>
  66. #include <sys/stat.h>
  67. #include <sys/wait.h>
  68. #include <sys/ioctl.h>
  69. #include <asm/ioctl.h>
  70. #include <byteswap.h>
  71. #include <sys/utsname.h>
  72. #include <linux/gpio.h>
  73. #include "softPwm.h"
  74. #include "softTone.h"
  75. #include "wiringPi.h"
  76. #include "../version.h"
  77. #include "wiringPiLegacy.h"
  78. // Environment Variables
  79. #define ENV_DEBUG "WIRINGPI_DEBUG"
  80. #define ENV_CODES "WIRINGPI_CODES"
  81. #define ENV_GPIOMEM "WIRINGPI_GPIOMEM"
  82. // Extend wiringPi with other pin-based devices and keep track of
  83. // them in this structure
  84. struct wiringPiNodeStruct *wiringPiNodes = NULL ;
  85. // BCM Magic
  86. #define BCM_PASSWORD 0x5A000000
  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 //0
  106. #define FSEL_OUTP 0b001 //1
  107. #define FSEL_ALT0 0b100 //4
  108. #define FSEL_ALT1 0b101 //5
  109. #define FSEL_ALT2 0b110 //6
  110. #define FSEL_ALT3 0b111 //7
  111. #define FSEL_ALT4 0b011 //3
  112. #define FSEL_ALT5 0b010 //2
  113. //RP1 defines
  114. #define FSEL_ALT6 8
  115. #define FSEL_ALT7 9
  116. #define FSEL_ALT8 10
  117. #define FSEL_ALT9 11
  118. //RP1 chip (@Pi5) - 3.1.1. Function select
  119. #define RP1_FSEL_ALT0 0x00
  120. #define RP1_FSEL_GPIO 0x05 //SYS_RIO
  121. #define RP1_FSEL_NONE 0x09
  122. #define RP1_FSEL_NONE_HW 0x1f //default, mask
  123. //RP1 chip (@Pi5) RIO address
  124. const unsigned int RP1_RIO_OUT = 0x0000;
  125. const unsigned int RP1_RIO_OE = (0x0004/4);
  126. const unsigned int RP1_RIO_IN = (0x0008/4);
  127. //RP1 chip (@Pi5) RIO offset for set/clear value
  128. const unsigned int RP1_SET_OFFSET = (0x2000/4);
  129. const unsigned int RP1_CLR_OFFSET = (0x3000/4);
  130. //RP1 chip (@Pi5) PDE/PDU pull-up/-down enable
  131. const unsigned int RP1_PUD_UP = (1<<3);
  132. const unsigned int RP1_PUD_DOWN = (1<<2);
  133. const unsigned int RP1_INV_PUD_MASK = ~(RP1_PUD_UP | RP1_PUD_DOWN); //~0x0C
  134. //RP1 chip (@Pi5) pin level, status register
  135. const unsigned int RP1_STATUS_LEVEL_LOW = 0x00400000;
  136. const unsigned int RP1_STATUS_LEVEL_HIGH = 0x00800000;
  137. const unsigned int RP1_STATUS_LEVEL_MASK = 0x00C00000;
  138. const unsigned int RP1_DEBOUNCE_DEFAULT_VALUE = 4;
  139. const unsigned int RP1_DEBOUNCE_MASK = 0x7f;
  140. const unsigned int RP1_DEBOUNCE_DEFAULT = (RP1_DEBOUNCE_DEFAULT_VALUE << 5);
  141. const unsigned int RP1_IRQRESET = 0x10000000; //CTRL Bit 28
  142. const unsigned int RP1_PAD_DEFAULT_0TO8 = (0x0B | 0x70); //Slewfast, Schmitt, PullUp, | 12mA, Input enable
  143. const unsigned int RP1_PAD_DEFAULT_FROM9 = (0x07 | 0x70); //Slewfast, Schmitt, PullDown, | 12mA, Input enable
  144. const unsigned int RP1_PAD_IC_DEFAULT_0TO8 = 0x9A; //pull-up, Schmitt
  145. const unsigned int RP1_PAD_IC_DEFAULT_FROM9 = 0x96; //pull-down, Schmitt
  146. const unsigned int RP1_PAD_DRIVE_MASK = 0x00000030;
  147. const unsigned int RP1_INV_PAD_DRIVE_MASK = ~(RP1_PAD_DRIVE_MASK);
  148. const unsigned int RP1_PWM0_GLOBAL_CTRL = 0;
  149. const unsigned int RP1_PWM0_FIFO_CTRL = 1;
  150. const unsigned int RP1_PWM0_COMMON_RANGE= 2;
  151. const unsigned int RP1_PWM0_COMMON_DUTY = 3;
  152. const unsigned int RP1_PWM0_DUTY_FIFO = 4;
  153. const unsigned int RP1_PWM0_CHAN_START = 5;
  154. //offset channel
  155. const unsigned int RP1_PWM0_CHAN_CTRL = 0;
  156. const unsigned int RP1_PWM0_CHAN_RANGE = 1;
  157. const unsigned int RP1_PWM0_CHAN_PHASE = 2;
  158. const unsigned int RP1_PWM0_CHAN_DUTY = 3;
  159. const unsigned int RP1_PWM0_CHAN_OFFSET= 4;
  160. const unsigned int RP1_PWM0_CHAN0_RANGE = RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*0+RP1_PWM0_CHAN_RANGE;
  161. const unsigned int RP1_PWM0_CHAN1_RANGE = RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*1+RP1_PWM0_CHAN_RANGE;
  162. const unsigned int RP1_PWM0_CHAN2_RANGE = RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*2+RP1_PWM0_CHAN_RANGE;
  163. const unsigned int RP1_PWM0_CHAN3_RANGE = RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*3+RP1_PWM0_CHAN_RANGE;
  164. const unsigned int RP1_PWM_CTRL_SETUPDATE = 0x80000000; // Bit 32
  165. const unsigned int RP1_PWM_TRAIL_EDGE_MS = 0x1;
  166. const unsigned int RP1_PWM_FIFO_POP_MASK = 0x100; // Bit 8
  167. const unsigned int RP1_CLK_PWM0_CTRL_DISABLE_MAGIC = 0x10000000; // Default after boot
  168. const unsigned int RP1_CLK_PWM0_CTRL_ENABLE_MAGIC = 0x11000840; // Reverse engineered, because of missing documentation, don't known meaning of of bits
  169. const unsigned int CLK_PWM0_CTRL = (0x00074/4);
  170. const unsigned int CLK_PWM0_DIV_INT = (0x00078/4);
  171. const unsigned int CLK_PWM0_DIV_FRAC = (0x0007C/4);
  172. const unsigned int CLK_PWM0_SEL = (0x00080/4);
  173. //RP1 chip (@Pi5) address
  174. const unsigned long long RP1_64_BASE_Addr = 0x1f000d0000;
  175. const unsigned int RP1_BASE_Addr = 0x40000000;
  176. const unsigned int RP1_CLOCK_Addr = 0x40018000; // Adress is not mapped to gpiomem device, lower than RP1_IO0_Addr
  177. const unsigned int RP1_PWM0_Addr = 0x40098000; // Adress is not mapped to gpiomem device, lower than RP1_IO0_Addr
  178. const unsigned int RP1_IO0_Addr = 0x400d0000;
  179. const unsigned int RP1_SYS_RIO0_Addr = 0x400e0000;
  180. const unsigned int RP1_PADS0_Addr = 0x400f0000;
  181. // Access from ARM Running Linux
  182. // Taken from Gert/Doms code. Some of this is not in the manual
  183. // that I can find )-:
  184. //
  185. // Updates in September 2015 - all now static variables (and apologies for the caps)
  186. // due to the Pi v2, v3, etc. and the new /dev/gpiomem interface
  187. const char* gpiomem_global = "/dev/mem";
  188. const char* gpiomem_BCM = "/dev/gpiomem";
  189. const char* gpiomem_RP1 = "/dev/gpiomem0";
  190. const int gpiomem_RP1_Size = 0x00030000;
  191. // PCIe Memory access, static define - maybe needed to detect in future
  192. //dmesg: rp1 0000:01:00.0: bar1 len 0x400000, start 0x1f00000000, end 0x1f003fffff, flags, 0x40200
  193. const char* pciemem_RP1_path = "/sys/bus/pci/devices/0000:01:00.0";
  194. const char* pciemem_RP1 = "/sys/bus/pci/devices/0000:01:00.0/resource1";
  195. const int pciemem_RP1_Size = 0x00400000;
  196. const unsigned short pciemem_RP1_Ventor= 0x1de4;
  197. const unsigned short pciemem_RP1_Device= 0x0001;
  198. static volatile unsigned int GPIO_PADS ;
  199. static volatile unsigned int GPIO_CLOCK_ADR ;
  200. static volatile unsigned int GPIO_BASE ;
  201. static volatile unsigned int GPIO_TIMER ;
  202. static volatile unsigned int GPIO_PWM ;
  203. static volatile unsigned int GPIO_RIO ;
  204. #define PAGE_SIZE (4*1024)
  205. #define BLOCK_SIZE (4*1024)
  206. static unsigned int usingGpioMem = FALSE ;
  207. static int wiringPiSetuped = FALSE ;
  208. // PWM
  209. // Word offsets into the PWM control region
  210. #define PWM_CONTROL 0
  211. #define PWM_STATUS 1
  212. #define PWM0_RANGE 4
  213. #define PWM0_DATA 5
  214. #define PWM1_RANGE 8
  215. #define PWM1_DATA 9
  216. // Clock regsiter offsets
  217. #define PWMCLK_CNTL 40
  218. #define PWMCLK_DIV 41
  219. #define PWM0_MS_MODE 0x0080 // Run in MS mode
  220. #define PWM0_USEFIFO 0x0020 // Data from FIFO
  221. #define PWM0_REVPOLAR 0x0010 // Reverse polarity
  222. #define PWM0_OFFSTATE 0x0008 // Ouput Off state
  223. #define PWM0_REPEATFF 0x0004 // Repeat last value if FIFO empty
  224. #define PWM0_SERIAL 0x0002 // Run in serial mode
  225. #define PWM0_ENABLE 0x0001 // Channel Enable
  226. #define PWM1_MS_MODE 0x8000 // Run in MS mode
  227. #define PWM1_USEFIFO 0x2000 // Data from FIFO
  228. #define PWM1_REVPOLAR 0x1000 // Reverse polarity
  229. #define PWM1_OFFSTATE 0x0800 // Ouput Off state
  230. #define PWM1_REPEATFF 0x0400 // Repeat last value if FIFO empty
  231. #define PWM1_SERIAL 0x0200 // Run in serial mode
  232. #define PWM1_ENABLE 0x0100 // Channel Enable
  233. const int PWMCLK_DIVI_MAX = 0xFFF; // 3 Byte max size for Clock devider
  234. const int OSC_FREQ_DEFAULT = 192; // x100kHz OSC
  235. const int OSC_FREQ_BCM2711 = 540; // x100kHz OSC
  236. const int OSC_FREQ_BCM2712 = 500; // x100kHz OSC - cat /sys/kernel/debug/clk/clk_summary | grep pwm0
  237. // Timer
  238. // Word offsets
  239. #define TIMER_LOAD (0x400 >> 2)
  240. #define TIMER_VALUE (0x404 >> 2)
  241. #define TIMER_CONTROL (0x408 >> 2)
  242. #define TIMER_IRQ_CLR (0x40C >> 2)
  243. #define TIMER_IRQ_RAW (0x410 >> 2)
  244. #define TIMER_IRQ_MASK (0x414 >> 2)
  245. #define TIMER_RELOAD (0x418 >> 2)
  246. #define TIMER_PRE_DIV (0x41C >> 2)
  247. #define TIMER_COUNTER (0x420 >> 2)
  248. // Locals to hold pointers to the hardware
  249. static volatile unsigned int *base ;
  250. static volatile unsigned int *gpio ;
  251. static volatile unsigned int *pwm ;
  252. static volatile unsigned int *clk ;
  253. static volatile unsigned int *pads ;
  254. static volatile unsigned int *timer ;
  255. static volatile unsigned int *timerIrqRaw ;
  256. static volatile unsigned int *rio ;
  257. // Export variables for the hardware pointers
  258. volatile unsigned int *_wiringPiBase ;
  259. volatile unsigned int *_wiringPiGpio ;
  260. volatile unsigned int *_wiringPiPwm ;
  261. volatile unsigned int *_wiringPiClk ;
  262. volatile unsigned int *_wiringPiPads ;
  263. volatile unsigned int *_wiringPiTimer ;
  264. volatile unsigned int *_wiringPiTimerIrqRaw ;
  265. volatile unsigned int *_wiringPiRio ;
  266. // Data for use with the boardId functions.
  267. // The order of entries here to correspond with the PI_MODEL_X
  268. // and PI_VERSION_X defines in wiringPi.h
  269. // Only intended for the gpio command - use at your own risk!
  270. // piGpioBase:
  271. // The base address of the GPIO memory mapped hardware IO
  272. #define GPIO_PERI_BASE_OLD 0x20000000
  273. #define GPIO_PERI_BASE_2835 0x3F000000
  274. #define GPIO_PERI_BASE_2711 0xFE000000
  275. #define GPIO_PERI_BASE_2712 0x00 //unknown - 32-bit mapped global mem access not supported for now
  276. static volatile unsigned int piGpioBase = 0 ;
  277. const char *piModelNames [24] =
  278. {
  279. "Model A", // 0
  280. "Model B", // 1
  281. "Model A+", // 2
  282. "Model B+", // 3
  283. "Pi 2", // 4
  284. "Alpha", // 5
  285. "CM", // 6
  286. "Unknown07", // 07
  287. "Pi 3", // 08
  288. "Pi Zero", // 09
  289. "CM3", // 10
  290. "Unknown11", // 11
  291. "Pi Zero-W", // 12
  292. "Pi 3B+", // 13
  293. "Pi 3A+", // 14
  294. "Unknown15", // 15
  295. "CM3+", // 16
  296. "Pi 4B", // 17
  297. "Pi Zero2-W", // 18
  298. "Pi 400", // 19
  299. "CM4", // 20
  300. "CM4S", // 21
  301. "Unknown22", // 22
  302. "Pi 5", // 23
  303. } ;
  304. const char *piProcessor [5] =
  305. {
  306. "BCM2835",
  307. "BCM2836",
  308. "BCM2837",
  309. "BCM2711",
  310. "BCM2712",
  311. } ;
  312. const char *piRevisionNames [16] =
  313. {
  314. "00",
  315. "01",
  316. "02",
  317. "03",
  318. "04",
  319. "05",
  320. "06",
  321. "07",
  322. "08",
  323. "09",
  324. "10",
  325. "11",
  326. "12",
  327. "13",
  328. "14",
  329. "15",
  330. } ;
  331. const char *piMakerNames [16] =
  332. {
  333. "Sony", // 0
  334. "Egoman", // 1
  335. "Embest", // 2
  336. "Unknown",// 3
  337. "Embest", // 4
  338. "Stadium",// 5
  339. "Unknown06", // 6
  340. "Unknown07", // 7
  341. "Unknown08", // 8
  342. "Unknown09", // 9
  343. "Unknown10", // 10
  344. "Unknown11", // 11
  345. "Unknown12", // 12
  346. "Unknown13", // 13
  347. "Unknown14", // 14
  348. "Unknown15", // 15
  349. } ;
  350. const int piMemorySize [8] =
  351. {
  352. 256, // 0
  353. 512, // 1
  354. 1024, // 2
  355. 2048, // 3
  356. 4096, // 4
  357. 8192, // 5
  358. 0, // 6
  359. 0, // 7
  360. } ;
  361. // Time for easy calculations
  362. static uint64_t epochMilli, epochMicro ;
  363. // Misc
  364. static int wiringPiMode = WPI_MODE_UNINITIALISED ;
  365. static volatile int pinPass = -1 ;
  366. static pthread_mutex_t pinMutex ;
  367. static int RaspberryPiModel = -1;
  368. static int RaspberryPiLayout = -1;
  369. // Debugging & Return codes
  370. int wiringPiDebug = FALSE ;
  371. int wiringPiReturnCodes = FALSE ;
  372. // Use /dev/gpiomem ?
  373. int wiringPiTryGpioMem = FALSE ;
  374. static unsigned int lineFlags [64] =
  375. {
  376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  380. } ;
  381. static int lineFds [64] =
  382. {
  383. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  384. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  385. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  386. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  387. } ;
  388. static int isrFds [64] =
  389. {
  390. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  391. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  392. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  393. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  394. } ;
  395. // ISR Data
  396. static int chipFd = -1;
  397. static void (*isrFunctions [64])(void) ;
  398. static pthread_t isrThreads[64];
  399. static int isrMode[64];
  400. // Doing it the Arduino way with lookup tables...
  401. // Yes, it's probably more innefficient than all the bit-twidling, but it
  402. // does tend to make it all a bit clearer. At least to me!
  403. // pinToGpio:
  404. // Take a Wiring pin (0 through X) and re-map it to the BCM_GPIO pin
  405. // Cope for 3 different board revisions here.
  406. static int *pinToGpio ;
  407. // Revision 1, 1.1:
  408. static int pinToGpioR1 [64] =
  409. {
  410. 17, 18, 21, 22, 23, 24, 25, 4, // From the Original Wiki - GPIO 0 through 7: wpi 0 - 7
  411. 0, 1, // I2C - SDA1, SCL1 wpi 8 - 9
  412. 8, 7, // SPI - CE1, CE0 wpi 10 - 11
  413. 10, 9, 11, // SPI - MOSI, MISO, SCLK wpi 12 - 14
  414. 14, 15, // UART - Tx, Rx wpi 15 - 16
  415. // Padding:
  416. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 31
  417. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 47
  418. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 63
  419. } ;
  420. // Revision 2:
  421. static int pinToGpioR2 [64] =
  422. {
  423. 17, 18, 27, 22, 23, 24, 25, 4, // From the Original Wiki - GPIO 0 through 7: wpi 0 - 7
  424. 2, 3, // I2C - SDA0, SCL0 wpi 8 - 9
  425. 8, 7, // SPI - CE1, CE0 wpi 10 - 11
  426. 10, 9, 11, // SPI - MOSI, MISO, SCLK wpi 12 - 14
  427. 14, 15, // UART - Tx, Rx wpi 15 - 16
  428. 28, 29, 30, 31, // Rev 2: New GPIOs 8 though 11 wpi 17 - 20
  429. 5, 6, 13, 19, 26, // B+ wpi 21, 22, 23, 24, 25
  430. 12, 16, 20, 21, // B+ wpi 26, 27, 28, 29
  431. 0, 1, // B+ wpi 30, 31
  432. // Padding:
  433. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 47
  434. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 63
  435. } ;
  436. // physToGpio:
  437. // Take a physical pin (1 through 26) and re-map it to the BCM_GPIO pin
  438. // Cope for 2 different board revisions here.
  439. // Also add in the P5 connector, so the P5 pins are 3,4,5,6, so 53,54,55,56
  440. static int *physToGpio ;
  441. static int physToGpioR1 [64] =
  442. {
  443. -1, // 0
  444. -1, -1, // 1, 2
  445. 0, -1,
  446. 1, -1,
  447. 4, 14,
  448. -1, 15,
  449. 17, 18,
  450. 21, -1,
  451. 22, 23,
  452. -1, 24,
  453. 10, -1,
  454. 9, 25,
  455. 11, 8,
  456. -1, 7, // 25, 26
  457. -1, -1, -1, -1, -1, // ... 31
  458. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 47
  459. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ... 63
  460. } ;
  461. static int physToGpioR2 [64] =
  462. {
  463. -1, // 0
  464. -1, -1, // 1, 2
  465. 2, -1,
  466. 3, -1,
  467. 4, 14,
  468. -1, 15,
  469. 17, 18,
  470. 27, -1,
  471. 22, 23,
  472. -1, 24,
  473. 10, -1,
  474. 9, 25,
  475. 11, 8,
  476. -1, 7, // 25, 26
  477. // B+
  478. 0, 1,
  479. 5, -1,
  480. 6, 12,
  481. 13, -1,
  482. 19, 16,
  483. 26, 20,
  484. -1, 21,
  485. // the P5 connector on the Rev 2 boards:
  486. -1, -1,
  487. -1, -1,
  488. -1, -1,
  489. -1, -1,
  490. -1, -1,
  491. 28, 29,
  492. 30, 31,
  493. -1, -1,
  494. -1, -1,
  495. -1, -1,
  496. -1, -1,
  497. } ;
  498. int piBoard() {
  499. if (RaspberryPiModel<0) { //need to detect pi model
  500. int model, rev, mem, maker, overVolted;
  501. piBoardId (&model, &rev, &mem, &maker, &overVolted);
  502. }
  503. return RaspberryPiModel<0 ? 0 : 1;
  504. }
  505. int piBoard40Pin() {
  506. if (!piBoard()){
  507. // Board not detected
  508. return -1;
  509. }
  510. switch(RaspberryPiModel){
  511. case PI_MODEL_A:
  512. case PI_MODEL_B:
  513. return 0;
  514. // PI_MODEL_CM
  515. // PI_MODEL_CM3
  516. // PI_MODEL_CM4
  517. // PI_MODEL_CM4S
  518. // ? guess yes
  519. default:
  520. return 1;
  521. }
  522. }
  523. int GetMaxPin() {
  524. return PI_MODEL_5 == RaspberryPiModel ? 27 : 63;
  525. }
  526. #define RETURN_ON_MODEL5 if (PI_MODEL_5 == RaspberryPiModel) { if (wiringPiDebug) printf("Function not supported on Pi5\n"); return; }
  527. int FailOnModel5(const char *function) {
  528. if (PI_MODEL_5 == RaspberryPiModel) {
  529. return wiringPiFailure (WPI_ALMOST, "Function '%s' not supported on Raspberry Pi 5.\n"
  530. " Unable to continue. Keep an eye of new versions at https://github.com/wiringpi/wiringpi\n", function) ;
  531. }
  532. return 0;
  533. }
  534. // gpioToGPFSEL:
  535. // Map a BCM_GPIO pin to it's Function Selection
  536. // control port. (GPFSEL 0-5)
  537. // Groups of 10 - 3 bits per Function - 30 bits per port
  538. static uint8_t gpioToGPFSEL [] =
  539. {
  540. 0,0,0,0,0,0,0,0,0,0,
  541. 1,1,1,1,1,1,1,1,1,1,
  542. 2,2,2,2,2,2,2,2,2,2,
  543. 3,3,3,3,3,3,3,3,3,3,
  544. 4,4,4,4,4,4,4,4,4,4,
  545. 5,5,5,5,5,5,5,5,5,5,
  546. } ;
  547. // gpioToShift
  548. // Define the shift up for the 3 bits per pin in each GPFSEL port
  549. static uint8_t gpioToShift [] =
  550. {
  551. 0,3,6,9,12,15,18,21,24,27,
  552. 0,3,6,9,12,15,18,21,24,27,
  553. 0,3,6,9,12,15,18,21,24,27,
  554. 0,3,6,9,12,15,18,21,24,27,
  555. 0,3,6,9,12,15,18,21,24,27,
  556. 0,3,6,9,12,15,18,21,24,27,
  557. } ;
  558. // gpioToGPSET:
  559. // (Word) offset to the GPIO Set registers for each GPIO pin
  560. static uint8_t gpioToGPSET [] =
  561. {
  562. 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,
  563. 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,
  564. } ;
  565. // gpioToGPCLR:
  566. // (Word) offset to the GPIO Clear registers for each GPIO pin
  567. static uint8_t gpioToGPCLR [] =
  568. {
  569. 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,
  570. 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,
  571. } ;
  572. // gpioToGPLEV:
  573. // (Word) offset to the GPIO Input level registers for each GPIO pin
  574. static uint8_t gpioToGPLEV [] =
  575. {
  576. 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,
  577. 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,
  578. } ;
  579. #ifdef notYetReady
  580. // gpioToEDS
  581. // (Word) offset to the Event Detect Status
  582. static uint8_t gpioToEDS [] =
  583. {
  584. 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,
  585. 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,
  586. } ;
  587. // gpioToREN
  588. // (Word) offset to the Rising edge ENable register
  589. static uint8_t gpioToREN [] =
  590. {
  591. 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,
  592. 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,
  593. } ;
  594. // gpioToFEN
  595. // (Word) offset to the Falling edgde ENable register
  596. static uint8_t gpioToFEN [] =
  597. {
  598. 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,
  599. 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,
  600. } ;
  601. #endif
  602. // GPPUD:
  603. // GPIO Pin pull up/down register
  604. #define GPPUD 37
  605. /* 2711 has a different mechanism for pin pull-up/down/enable */
  606. #define GPPUPPDN0 57 /* Pin pull-up/down for pins 15:0 */
  607. #define GPPUPPDN1 58 /* Pin pull-up/down for pins 31:16 */
  608. #define GPPUPPDN2 59 /* Pin pull-up/down for pins 47:32 */
  609. #define GPPUPPDN3 60 /* Pin pull-up/down for pins 57:48 */
  610. static volatile unsigned int piGpioPupOffset = 0 ;
  611. // gpioToPUDCLK
  612. // (Word) offset to the Pull Up Down Clock regsiter
  613. static uint8_t gpioToPUDCLK [] =
  614. {
  615. 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,
  616. 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,
  617. } ;
  618. // gpioToPwmALT
  619. // the ALT value to put a GPIO pin into PWM mode
  620. static uint8_t gpioToPwmALT [] =
  621. {
  622. 0, 0, 0, 0, 0, 0, 0, 0, // 0 -> 7
  623. 0, 0, 0, 0, FSEL_ALT0, FSEL_ALT0, 0, 0, // 8 -> 15
  624. 0, 0, FSEL_ALT5, FSEL_ALT5, 0, 0, 0, 0, // 16 -> 23
  625. 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
  626. 0, 0, 0, 0, 0, 0, 0, 0, // 32 -> 39
  627. FSEL_ALT0, FSEL_ALT0, 0, 0, 0, FSEL_ALT0, 0, 0, // 40 -> 47
  628. 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
  629. 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
  630. } ;
  631. // gpioToPwmPort
  632. // The port value to put a GPIO pin into PWM mode
  633. static uint8_t gpioToPwmPort [] =
  634. {
  635. 0, 0, 0, 0, 0, 0, 0, 0, // 0 -> 7
  636. 0, 0, 0, 0, PWM0_DATA, PWM1_DATA, 0, 0, // 8 -> 15
  637. 0, 0, PWM0_DATA, PWM1_DATA, 0, 0, 0, 0, // 16 -> 23
  638. 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
  639. 0, 0, 0, 0, 0, 0, 0, 0, // 32 -> 39
  640. PWM0_DATA, PWM1_DATA, 0, 0, 0, PWM1_DATA, 0, 0, // 40 -> 47
  641. 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
  642. 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
  643. } ;
  644. // gpioToGpClkALT:
  645. // ALT value to put a GPIO pin into GP Clock mode.
  646. // On the Pi we can really only use BCM_GPIO_4 and BCM_GPIO_21
  647. // for clocks 0 and 1 respectively, however I'll include the full
  648. // list for completeness - maybe one day...
  649. #define GPIO_CLOCK_SOURCE 1
  650. // gpioToGpClkALT0:
  651. static uint8_t gpioToGpClkALT0 [] =
  652. {
  653. 0, 0, 0, 0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0, 0, // 0 -> 7
  654. 0, 0, 0, 0, 0, 0, 0, 0, // 8 -> 15
  655. 0, 0, 0, 0, FSEL_ALT5, FSEL_ALT5, 0, 0, // 16 -> 23
  656. 0, 0, 0, 0, 0, 0, 0, 0, // 24 -> 31
  657. FSEL_ALT0, 0, FSEL_ALT0, 0, 0, 0, 0, 0, // 32 -> 39
  658. 0, 0, FSEL_ALT0, FSEL_ALT0, FSEL_ALT0, 0, 0, 0, // 40 -> 47
  659. 0, 0, 0, 0, 0, 0, 0, 0, // 48 -> 55
  660. 0, 0, 0, 0, 0, 0, 0, 0, // 56 -> 63
  661. } ;
  662. // gpioToClk:
  663. // (word) Offsets to the clock Control and Divisor register
  664. static uint8_t gpioToClkCon [] =
  665. {
  666. -1, -1, -1, -1, 28, 30, 32, -1, // 0 -> 7
  667. -1, -1, -1, -1, -1, -1, -1, -1, // 8 -> 15
  668. -1, -1, -1, -1, 28, 30, -1, -1, // 16 -> 23
  669. -1, -1, -1, -1, -1, -1, -1, -1, // 24 -> 31
  670. 28, -1, 28, -1, -1, -1, -1, -1, // 32 -> 39
  671. -1, -1, 28, 30, 28, -1, -1, -1, // 40 -> 47
  672. -1, -1, -1, -1, -1, -1, -1, -1, // 48 -> 55
  673. -1, -1, -1, -1, -1, -1, -1, -1, // 56 -> 63
  674. } ;
  675. static uint8_t gpioToClkDiv [] =
  676. {
  677. -1, -1, -1, -1, 29, 31, 33, -1, // 0 -> 7
  678. -1, -1, -1, -1, -1, -1, -1, -1, // 8 -> 15
  679. -1, -1, -1, -1, 29, 31, -1, -1, // 16 -> 23
  680. -1, -1, -1, -1, -1, -1, -1, -1, // 24 -> 31
  681. 29, -1, 29, -1, -1, -1, -1, -1, // 32 -> 39
  682. -1, -1, 29, 31, 29, -1, -1, -1, // 40 -> 47
  683. -1, -1, -1, -1, -1, -1, -1, -1, // 48 -> 55
  684. -1, -1, -1, -1, -1, -1, -1, -1, // 56 -> 63
  685. } ;
  686. /*
  687. * Functions
  688. *********************************************************************************
  689. */
  690. /*
  691. * wiringPiFailure:
  692. * Fail. Or not.
  693. *********************************************************************************
  694. */
  695. int wiringPiFailure (int fatal, const char *message, ...)
  696. {
  697. va_list argp ;
  698. char buffer [1024] ;
  699. if (!fatal && wiringPiReturnCodes)
  700. return -1 ;
  701. va_start (argp, message) ;
  702. vsnprintf (buffer, 1023, message, argp) ;
  703. va_end (argp) ;
  704. fprintf (stderr, "%s", buffer) ;
  705. exit (EXIT_FAILURE) ;
  706. return 0 ;
  707. }
  708. /*
  709. * setupCheck
  710. * Another sanity check because some users forget to call the setup
  711. * function. Mosty because they need feeding C drip by drip )-:
  712. *********************************************************************************
  713. */
  714. static void setupCheck (const char *fName)
  715. {
  716. if (!wiringPiSetuped)
  717. {
  718. fprintf (stderr, "%s: You have not called one of the wiringPiSetup\n"
  719. " functions, so I'm aborting your program before it crashes anyway.\n", fName) ;
  720. exit (EXIT_FAILURE) ;
  721. }
  722. }
  723. /*
  724. * gpioMemCheck:
  725. * See if we're using the /dev/gpiomem interface, if-so then some operations
  726. * can't be done and will crash the Pi.
  727. *********************************************************************************
  728. */
  729. static void usingGpioMemCheck (const char *what)
  730. {
  731. if (usingGpioMem)
  732. {
  733. fprintf (stderr, "%s: Unable to do this when using /dev/gpiomem. Try sudo?\n", what) ;
  734. exit (EXIT_FAILURE) ;
  735. }
  736. }
  737. void PrintSystemStdErr () {
  738. struct utsname sys_info;
  739. if (uname(&sys_info) == 0) {
  740. fprintf (stderr, " WiringPi : %d.%d\n", VERSION_MAJOR, VERSION_MINOR);
  741. fprintf (stderr, " system name : %s\n", sys_info.sysname);
  742. //fprintf (stderr, " node name : %s\n", sys_info.nodename);
  743. fprintf (stderr, " release : %s\n", sys_info.release);
  744. fprintf (stderr, " version : %s\n", sys_info.version);
  745. fprintf (stderr, " machine : %s\n", sys_info.machine);
  746. if (strstr(sys_info.machine, "arm") == NULL && strstr(sys_info.machine, "aarch")==NULL) {
  747. fprintf (stderr, " -> This is not an ARM architecture; it cannot be a Raspberry Pi.\n") ;
  748. }
  749. }
  750. }
  751. void piFunctionOops (const char *function, const char* suggestion, const char* url)
  752. {
  753. fprintf (stderr, "Oops: Function %s is not supported\n", function) ;
  754. PrintSystemStdErr();
  755. if (suggestion) {
  756. fprintf (stderr, " -> Please %s\n", suggestion) ;
  757. }
  758. if (url) {
  759. fprintf (stderr, " -> See info at %s\n", url) ;
  760. }
  761. fprintf (stderr, " -> Check at https://github.com/wiringpi/wiringpi/issues.\n\n") ;
  762. exit (EXIT_FAILURE) ;
  763. }
  764. void ReportDeviceError(const char *function, int pin, const char *mode, int ret) {
  765. fprintf(stderr, "wiringPi: ERROR: ioctl %s of %d (%s) returned error '%s' (%d)\n", function, pin, mode, strerror(errno), ret);
  766. }
  767. /*
  768. * piGpioLayout:
  769. * Return a number representing the hardware revision of the board.
  770. * This is not strictly the board revision but is used to check the
  771. * layout of the GPIO connector - and there are 2 types that we are
  772. * really interested in here. The very earliest Pi's and the
  773. * ones that came after that which switched some pins ....
  774. *
  775. * Revision 1 really means the early Model A and B's.
  776. * Revision 2 is everything else - it covers the B, B+ and CM.
  777. * ... and the Pi 2 - which is a B+ ++ ...
  778. * ... and the Pi 0 - which is an A+ ...
  779. *
  780. * The main difference between the revision 1 and 2 system that I use here
  781. * is the mapping of the GPIO pins. From revision 2, the Pi Foundation changed
  782. * 3 GPIO pins on the (original) 26-way header - BCM_GPIO 22 was dropped and
  783. * replaced with 27, and 0 + 1 - I2C bus 0 was changed to 2 + 3; I2C bus 1.
  784. *
  785. * Additionally, here we set the piModel2 flag too. This is again, nothing to
  786. * do with the actual model, but the major version numbers - the GPIO base
  787. * hardware address changed at model 2 and above (not the Zero though)
  788. *
  789. *********************************************************************************
  790. */
  791. const char* revfile = "/proc/device-tree/system/linux,revision";
  792. void piGpioLayoutOops (const char *why)
  793. {
  794. fprintf (stderr, "Oops: Unable to determine Raspberry Pi board revision from %s and from /proc/cpuinfo\n", revfile) ;
  795. PrintSystemStdErr();
  796. fprintf (stderr, " -> %s\n", why) ;
  797. fprintf (stderr, " -> WiringPi is designed for Raspberry Pi and can only be used with a Raspberry Pi.\n\n") ;
  798. fprintf (stderr, " -> Check at https://github.com/wiringpi/wiringpi/issues.\n\n") ;
  799. exit (EXIT_FAILURE) ;
  800. }
  801. int piGpioLayout (void)
  802. {
  803. piBoard();
  804. return RaspberryPiLayout;
  805. }
  806. /*
  807. * piBoardRev:
  808. * Deprecated, but does the same as piGpioLayout
  809. *********************************************************************************
  810. */
  811. int piBoardRev (void)
  812. {
  813. return piGpioLayout () ;
  814. }
  815. const char* GetPiRevision(char* line, int linelength, unsigned int* revision) {
  816. const char* c = NULL;
  817. uint32_t Revision = 0;
  818. _Static_assert(sizeof(Revision)==4, "should be unsigend integer with 4 byte size");
  819. FILE* fp = fopen(revfile,"rb");
  820. if (!fp) {
  821. if (wiringPiDebug)
  822. perror(revfile);
  823. return NULL; // revision file not found or no access
  824. }
  825. int result = fread(&Revision, sizeof(Revision), 1, fp);
  826. fclose(fp);
  827. if (result<1) {
  828. if (wiringPiDebug)
  829. perror(revfile);
  830. return NULL; // read error
  831. }
  832. Revision = bswap_32(Revision);
  833. snprintf(line, linelength, "Revision\t: %04x", Revision);
  834. c = &line[11];
  835. *revision = Revision;
  836. if (wiringPiDebug)
  837. printf("GetPiRevision: Revision string: \"%s\" (%s) - 0x%x\n", line, c, *revision);
  838. return c;
  839. }
  840. /*
  841. * piBoardId:
  842. * Return the real details of the board we have.
  843. *
  844. * This is undocumented and really only intended for the GPIO command.
  845. * Use at your own risk!
  846. *
  847. * Seems there are some boards with 0000 in them (mistake in manufacture)
  848. * So the distinction between boards that I can see is:
  849. *
  850. * 0000 - Error
  851. * 0001 - Not used
  852. *
  853. * Original Pi boards:
  854. * 0002 - Model B, Rev 1, 256MB, Egoman
  855. * 0003 - Model B, Rev 1.1, 256MB, Egoman, Fuses/D14 removed.
  856. *
  857. * Newer Pi's with remapped GPIO:
  858. * 0004 - Model B, Rev 1.2, 256MB, Sony
  859. * 0005 - Model B, Rev 1.2, 256MB, Egoman
  860. * 0006 - Model B, Rev 1.2, 256MB, Egoman
  861. *
  862. * 0007 - Model A, Rev 1.2, 256MB, Egoman
  863. * 0008 - Model A, Rev 1.2, 256MB, Sony
  864. * 0009 - Model A, Rev 1.2, 256MB, Egoman
  865. *
  866. * 000d - Model B, Rev 1.2, 512MB, Egoman (Red Pi, Blue Pi?)
  867. * 000e - Model B, Rev 1.2, 512MB, Sony
  868. * 000f - Model B, Rev 1.2, 512MB, Egoman
  869. *
  870. * 0010 - Model B+, Rev 1.2, 512MB, Sony
  871. * 0013 - Model B+ Rev 1.2, 512MB, Embest
  872. * 0016 - Model B+ Rev 1.2, 512MB, Sony
  873. * 0019 - Model B+ Rev 1.2, 512MB, Egoman
  874. *
  875. * 0011 - Pi CM, Rev 1.1, 512MB, Sony
  876. * 0014 - Pi CM, Rev 1.1, 512MB, Embest
  877. * 0017 - Pi CM, Rev 1.1, 512MB, Sony
  878. * 001a - Pi CM, Rev 1.1, 512MB, Egoman
  879. *
  880. * 0012 - Model A+ Rev 1.1, 256MB, Sony
  881. * 0015 - Model A+ Rev 1.1, 512MB, Embest
  882. * 0018 - Model A+ Rev 1.1, 256MB, Sony
  883. * 001b - Model A+ Rev 1.1, 256MB, Egoman
  884. *
  885. * A small thorn is the olde style overvolting - that will add in
  886. * 1000000
  887. *
  888. * The Pi compute module has an revision of 0011 or 0014 - since we only
  889. * check the last digit, then it's 1, therefore it'll default to not 2 or
  890. * 3 for a Rev 1, so will appear as a Rev 2. This is fine for the most part, but
  891. * we'll properly detect the Compute Module later and adjust accordingly.
  892. *
  893. * And then things changed with the introduction of the v2...
  894. *
  895. * For Pi v2 and subsequent models - e.g. the Zero:
  896. *
  897. * [USER:8] [NEW:1] [MEMSIZE:3] [MANUFACTURER:4] [PROCESSOR:4] [TYPE:8] [REV:4]
  898. * NEW 23: will be 1 for the new scheme, 0 for the old scheme
  899. * MEMSIZE 20: 0=256M 1=512M 2=1G
  900. * MANUFACTURER 16: 0=SONY 1=EGOMAN 2=EMBEST
  901. * PROCESSOR 12: 0=2835 1=2836
  902. * TYPE 04: 0=MODELA 1=MODELB 2=MODELA+ 3=MODELB+ 4=Pi2 MODEL B 5=ALPHA 6=CM
  903. * REV 00: 0=REV0 1=REV1 2=REV2
  904. *********************************************************************************
  905. */
  906. void piBoardId (int *model, int *rev, int *mem, int *maker, int *warranty)
  907. {
  908. const int maxlength = 120;
  909. char line [maxlength+1] ;
  910. const char *c ;
  911. unsigned int revision = 0x00 ;
  912. int bRev, bType, bProc, bMfg, bMem, bWarranty ;
  913. //piGpioLayoutOops ("this is only a test case");
  914. c = GetPiRevision(line, maxlength, &revision); // device tree
  915. if (NULL==c) {
  916. c = GetPiRevisionLegacy(line, maxlength, &revision); // proc/cpuinfo
  917. }
  918. if (NULL==c) {
  919. piGpioLayoutOops ("GetPiRevision failed!") ;
  920. }
  921. if ((revision & (1 << 23)) != 0) // New style, not available for Raspberry Pi 1B/A, CM
  922. {
  923. if (wiringPiDebug)
  924. printf ("piBoardId: New Way: revision is: %08X\n", revision) ;
  925. bRev = (revision & (0x0F << 0)) >> 0 ;
  926. bType = (revision & (0xFF << 4)) >> 4 ;
  927. bProc = (revision & (0x0F << 12)) >> 12 ; // Not used for now.
  928. bMfg = (revision & (0x0F << 16)) >> 16 ;
  929. bMem = (revision & (0x07 << 20)) >> 20 ;
  930. bWarranty = (revision & (0x03 << 24)) != 0 ;
  931. // Ref: https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#raspberry-pi-revision-codes
  932. *model = bType ;
  933. *rev = bRev ;
  934. *mem = bMem ;
  935. *maker = bMfg ;
  936. *warranty = bWarranty ;
  937. RaspberryPiLayout = GPIO_LAYOUT_DEFAULT ; //default
  938. if (wiringPiDebug)
  939. printf ("piBoardId: rev: %d, type: %d, proc: %d, mfg: %d, mem: %d, warranty: %d\n",
  940. bRev, bType, bProc, bMfg, bMem, bWarranty) ;
  941. }
  942. else // Old way
  943. {
  944. if (wiringPiDebug)
  945. printf ("piBoardId: Old Way: revision is: %s\n", c) ;
  946. if (!isdigit (*c))
  947. piGpioLayoutOops ("Bogus \"Revision\" line (no digit at start of revision)") ;
  948. // Make sure its long enough
  949. if (strlen (c) < 4)
  950. piGpioLayoutOops ("Bogus \"Revision\" line (not long enough)") ;
  951. // If longer than 4, we'll assume it's been overvolted
  952. *warranty = strlen (c) > 4 ;
  953. // Extract last 4 characters:
  954. c = c + strlen (c) - 4 ;
  955. // Fill out the replys as appropriate
  956. RaspberryPiLayout = GPIO_LAYOUT_DEFAULT ; //default
  957. /**/ if (strcmp (c, "0002") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; RaspberryPiLayout = GPIO_LAYOUT_PI1_REV1; }
  958. else if (strcmp (c, "0003") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; RaspberryPiLayout = GPIO_LAYOUT_PI1_REV1; }
  959. else if (strcmp (c, "0004") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_SONY ; }
  960. else if (strcmp (c, "0005") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; }
  961. else if (strcmp (c, "0006") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; }
  962. else if (strcmp (c, "0007") == 0) { *model = PI_MODEL_A ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; }
  963. else if (strcmp (c, "0008") == 0) { *model = PI_MODEL_A ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_SONY ; ; }
  964. else if (strcmp (c, "0009") == 0) { *model = PI_MODEL_A ; *rev = PI_VERSION_1_2 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; }
  965. else if (strcmp (c, "000d") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN ; }
  966. else if (strcmp (c, "000e") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY ; }
  967. else if (strcmp (c, "000f") == 0) { *model = PI_MODEL_B ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN ; }
  968. else if (strcmp (c, "0010") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY ; }
  969. else if (strcmp (c, "0013") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EMBEST ; }
  970. else if (strcmp (c, "0016") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_SONY ; }
  971. else if (strcmp (c, "0019") == 0) { *model = PI_MODEL_BP ; *rev = PI_VERSION_1_2 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN ; }
  972. else if (strcmp (c, "0011") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_SONY ; }
  973. else if (strcmp (c, "0014") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EMBEST ; }
  974. else if (strcmp (c, "0017") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_SONY ; }
  975. else if (strcmp (c, "001a") == 0) { *model = PI_MODEL_CM ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EGOMAN ; }
  976. else if (strcmp (c, "0012") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_SONY ; }
  977. else if (strcmp (c, "0015") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 1 ; *maker = PI_MAKER_EMBEST ; }
  978. else if (strcmp (c, "0018") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_SONY ; }
  979. else if (strcmp (c, "001b") == 0) { *model = PI_MODEL_AP ; *rev = PI_VERSION_1_1 ; *mem = 0 ; *maker = PI_MAKER_EGOMAN ; }
  980. else { *model = 0 ; *rev = 0 ; *mem = 0 ; *maker = 0 ; }
  981. }
  982. RaspberryPiModel = *model;
  983. switch (RaspberryPiModel){
  984. case PI_MODEL_A:
  985. case PI_MODEL_B:
  986. case PI_MODEL_AP:
  987. case PI_MODEL_BP:
  988. case PI_ALPHA:
  989. case PI_MODEL_CM:
  990. case PI_MODEL_ZERO:
  991. case PI_MODEL_ZERO_W:
  992. piGpioBase = GPIO_PERI_BASE_OLD ;
  993. piGpioPupOffset = GPPUD ;
  994. break ;
  995. case PI_MODEL_4B:
  996. case PI_MODEL_400:
  997. case PI_MODEL_CM4:
  998. case PI_MODEL_CM4S:
  999. piGpioBase = GPIO_PERI_BASE_2711 ;
  1000. piGpioPupOffset = GPPUPPDN0 ;
  1001. break ;
  1002. case PI_MODEL_5:
  1003. piGpioBase = GPIO_PERI_BASE_2712 ;
  1004. piGpioPupOffset = 0 ;
  1005. break ;
  1006. default:
  1007. piGpioBase = GPIO_PERI_BASE_2835 ;
  1008. piGpioPupOffset = GPPUD ;
  1009. break ;
  1010. }
  1011. }
  1012. /*
  1013. * wpiPinToGpio:
  1014. * Translate a wiringPi Pin number to native GPIO pin number.
  1015. * Provided for external support.
  1016. *********************************************************************************
  1017. */
  1018. int wpiPinToGpio (int wpiPin)
  1019. {
  1020. return pinToGpio [wpiPin & 63] ;
  1021. }
  1022. /*
  1023. * physPinToGpio:
  1024. * Translate a physical Pin number to native GPIO pin number.
  1025. * Provided for external support.
  1026. *********************************************************************************
  1027. */
  1028. int physPinToGpio (int physPin)
  1029. {
  1030. return physToGpio [physPin & 63] ;
  1031. }
  1032. /*
  1033. * setPadDrive:
  1034. * Set the PAD driver value
  1035. *********************************************************************************
  1036. */
  1037. void setPadDrivePin (int pin, int value) {
  1038. if (PI_MODEL_5 != RaspberryPiModel) return;
  1039. if (pin < 0 || pin > GetMaxPin()) return ;
  1040. uint32_t wrVal;
  1041. value = value & 3; // 0-3 supported
  1042. wrVal = (value << 4); //Drive strength 0-3
  1043. pads[1+pin] = (pads[1+pin] & RP1_INV_PAD_DRIVE_MASK) | wrVal;
  1044. if (wiringPiDebug) {
  1045. printf ("setPadDrivePin: pin: %d, value: %d (%08X)\n", pin, value, pads[1+pin]) ;
  1046. }
  1047. }
  1048. void setPadDrive (int group, int value)
  1049. {
  1050. uint32_t wrVal, rdVal;
  1051. if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
  1052. {
  1053. value = value & 7; // 0-7 supported
  1054. if (PI_MODEL_5 == RaspberryPiModel) {
  1055. if (-1==group) {
  1056. printf ("Pad register:\n");
  1057. for (int pin=0, maxpin=GetMaxPin(); pin<=maxpin; ++pin) {
  1058. unsigned int drive = (pads[1+pin] & RP1_PAD_DRIVE_MASK)>>4;
  1059. printf (" Pin %2d: 0x%08X drive: 0x%d = %2dmA\n", pin, pads[1+pin], drive, 0==drive ? 2 : drive*4) ;
  1060. }
  1061. }
  1062. if (group !=0) { // only GPIO range @RP1
  1063. return ;
  1064. }
  1065. switch(value) {
  1066. default:
  1067. /* bcm*/ // RP1
  1068. case 0: /* 2mA*/ value=0; break; // 2mA
  1069. case 1: /* 4mA*/
  1070. case 2: /* 6mA*/ value=1; break; // 4mA
  1071. case 3: /* 8mA*/
  1072. case 4: /*10mA*/ value=2; break; // 8mA
  1073. case 5: /*12mA*/
  1074. case 6: /*14mA*/
  1075. case 7: /*16mA*/ value=3; break; //12mA
  1076. }
  1077. wrVal = (value << 4); //Drive strength 0-3
  1078. //set for all pins even when it's avaiable for each pin separately
  1079. for (int pin=0, maxpin=GetMaxPin(); pin<=maxpin; ++pin) {
  1080. pads[1+pin] = (pads[1+pin] & RP1_INV_PAD_DRIVE_MASK) | wrVal;
  1081. }
  1082. rdVal = pads[1+17]; // only pin 17 readback, for logging
  1083. } else {
  1084. if (-1==group) {
  1085. printf ("Pad register: Group 0: 0x%08X, Group 1: 0x%08X, Group 2: 0x%08X\n", *(pads + 0 + 11), *(pads + 1 + 11), *(pads + 2 + 11)) ;
  1086. }
  1087. if ((group < 0) || (group > 2))
  1088. return ;
  1089. wrVal = BCM_PASSWORD | 0x18 | value; //Drive strength 0-7
  1090. *(pads + group + 11) = wrVal ;
  1091. rdVal = *(pads + group + 11);
  1092. }
  1093. if (wiringPiDebug)
  1094. {
  1095. printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
  1096. printf ("Read : %08X\n", rdVal) ;
  1097. }
  1098. }
  1099. }
  1100. /*
  1101. * getAlt:
  1102. * Returns the ALT bits for a given port. Only really of-use
  1103. * for the gpio readall command (I think)
  1104. *********************************************************************************
  1105. */
  1106. int getAlt (int pin)
  1107. {
  1108. int alt;
  1109. pin &= 63 ;
  1110. /**/ if (wiringPiMode == WPI_MODE_PINS)
  1111. pin = pinToGpio [pin] ;
  1112. else if (wiringPiMode == WPI_MODE_PHYS)
  1113. pin = physToGpio [pin] ;
  1114. else if (wiringPiMode != WPI_MODE_GPIO)
  1115. return 0 ;
  1116. if (PI_MODEL_5 == RaspberryPiModel) {
  1117. alt = (gpio[2*pin+1] & RP1_FSEL_NONE_HW); //0-4 function
  1118. /*
  1119. BCM:
  1120. 000b = GPIO Pin 9 is an input
  1121. 001b = GPIO Pin 9 is an output
  1122. 100b = GPIO Pin 9 takes alternate function 0
  1123. 101b = GPIO Pin 9 takes alternate function 1
  1124. 110b = GPIO Pin 9 takes alternate function 2
  1125. 111b = GPIO Pin 9 takes alternate function 3
  1126. 011b = GPIO Pin 9 takes alternate function 4
  1127. 010b = GPIO Pin 9 takes alternate function 5
  1128. RP1:
  1129. 8 = alternate function 6
  1130. 9 = alternate function 7
  1131. 10 = alternate function 8
  1132. 11 = alternate function 9
  1133. */
  1134. switch(alt) {
  1135. case 0: return FSEL_ALT0;
  1136. case 1: return FSEL_ALT1;
  1137. case 2: return FSEL_ALT2;
  1138. case 3: return FSEL_ALT3;
  1139. case 4: return FSEL_ALT4;
  1140. case RP1_FSEL_GPIO: {
  1141. unsigned int outputmask = gpio[2*pin] & 0x3000; //Bit13-OETOPAD + Bit12-OEFROMPERI
  1142. return (outputmask==0x3000) ? FSEL_OUTP : FSEL_INPT;
  1143. }
  1144. case 6: return FSEL_ALT6;
  1145. case 7: return FSEL_ALT7;
  1146. case 8: return FSEL_ALT8;
  1147. case RP1_FSEL_NONE: return FSEL_ALT9;
  1148. default:return alt;
  1149. }
  1150. } else {
  1151. int fSel = gpioToGPFSEL [pin] ;
  1152. int shift = gpioToShift [pin] ;
  1153. alt = (*(gpio + fSel) >> shift) & 7 ;
  1154. }
  1155. return alt;
  1156. }
  1157. enum WPIPinAlt getPinModeAlt(int pin) {
  1158. return (enum WPIPinAlt) getAlt(pin);
  1159. }
  1160. /*
  1161. * pwmSetMode:
  1162. * Select the native "balanced" mode, or standard mark:space mode
  1163. *********************************************************************************
  1164. */
  1165. void pwmSetMode (int mode)
  1166. {
  1167. if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
  1168. {
  1169. if (PI_MODEL_5 == RaspberryPiModel) {
  1170. if(mode != PWM_MODE_MS) {
  1171. fprintf(stderr, "pwmSetMode: Raspberry Pi 5 missing feature PWM BAL mode\n");
  1172. }
  1173. return;
  1174. }
  1175. if (mode == PWM_MODE_MS) {
  1176. *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE | PWM0_MS_MODE | PWM1_MS_MODE ;
  1177. } else {
  1178. *(pwm + PWM_CONTROL) = PWM0_ENABLE | PWM1_ENABLE ;
  1179. }
  1180. if (wiringPiDebug) {
  1181. printf ("Enable PWM mode: %s. Current register: 0x%08X\n", mode == PWM_MODE_MS ? "mark:space (freq. stable)" : "balanced (freq. change)", *(pwm + PWM_CONTROL));
  1182. }
  1183. }
  1184. }
  1185. /*
  1186. * pwmSetRange:
  1187. * Set the PWM range register. We set both range registers to the same
  1188. * value. If you want different in your own code, then write your own.
  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. /* would be possible on ms mode but not on bal, deactivated, use pwmc modify instead
  1196. if (piGpioBase == GPIO_PERI_BASE_2711) {
  1197. range = (OSC_FREQ_BCM2711*range)/OSC_FREQ_DEFAULT;
  1198. }
  1199. */
  1200. if (!pwm) {
  1201. fprintf(stderr, "wiringPi: pwmSetRange but no pwm memory available, ignoring\n");
  1202. return;
  1203. }
  1204. int readback = 0x00;
  1205. if (PI_MODEL_5 == RaspberryPiModel) {
  1206. pwm[RP1_PWM0_CHAN0_RANGE] = range;
  1207. pwm[RP1_PWM0_CHAN1_RANGE] = range;
  1208. pwm[RP1_PWM0_CHAN2_RANGE] = range;
  1209. pwm[RP1_PWM0_CHAN3_RANGE] = range;
  1210. readback = pwm[RP1_PWM0_CHAN0_RANGE];
  1211. } else {
  1212. *(pwm + PWM0_RANGE) = range ; delayMicroseconds (10) ;
  1213. *(pwm + PWM1_RANGE) = range ; delayMicroseconds (10) ;
  1214. readback = *(pwm + PWM0_RANGE);
  1215. }
  1216. if (wiringPiDebug) {
  1217. printf ("PWM range: %u. Current register: 0x%08X\n", range, readback);
  1218. }
  1219. }
  1220. }
  1221. /*
  1222. * pwmSetClock:
  1223. * Set/Change the PWM clock. Originally my code, but changed
  1224. * (for the better!) by Chris Hall, <chris@kchall.plus.com>
  1225. * after further study of the manual and testing with a 'scope
  1226. *********************************************************************************
  1227. */
  1228. void pwmSetClock (int divisor)
  1229. {
  1230. uint32_t pwm_control ;
  1231. if (!clk) {
  1232. fprintf(stderr, "wiringPi: pwmSetClock but no clk memory available, ignoring\n");
  1233. return;
  1234. }
  1235. if (divisor > PWMCLK_DIVI_MAX) {
  1236. divisor = PWMCLK_DIVI_MAX; // even on Pi5 4095 is OK
  1237. }
  1238. if (PI_MODEL_5 == RaspberryPiModel) {
  1239. if (divisor < 1) {
  1240. if (wiringPiDebug) { printf("Disable PWM0 clock"); }
  1241. clk[CLK_PWM0_CTRL] = RP1_CLK_PWM0_CTRL_DISABLE_MAGIC; // 0 = disable on Pi5
  1242. } else {
  1243. divisor = (OSC_FREQ_BCM2712*divisor)/OSC_FREQ_DEFAULT;
  1244. if (wiringPiDebug) {
  1245. printf ("PWM clock divisor: %d\n", divisor) ;
  1246. }
  1247. //clk[CLK_PWM0_CTRL] = RP1_CLK_PWM0_CTRL_DISABLE_MAGIC;
  1248. //delayMicroseconds(100);
  1249. clk[CLK_PWM0_DIV_INT] = divisor;
  1250. clk[CLK_PWM0_DIV_FRAC] = 0;
  1251. clk[CLK_PWM0_SEL] = 1;
  1252. clk[CLK_PWM0_CTRL] = RP1_CLK_PWM0_CTRL_ENABLE_MAGIC;
  1253. }
  1254. return;
  1255. }
  1256. if (piGpioBase == GPIO_PERI_BASE_2711) {
  1257. //calculate value for OSC 54MHz -> 19.2MHz
  1258. // Pi 4 max divisor is 1456, Pi0-3 is 4095 (0xFFF)
  1259. divisor = (OSC_FREQ_BCM2711*divisor)/OSC_FREQ_DEFAULT;
  1260. }
  1261. if (divisor < 1) {
  1262. divisor = 1;
  1263. }
  1264. if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
  1265. {
  1266. if (wiringPiDebug) {
  1267. printf ("PWM clock divisor: Old register: 0x%08X\n", *(clk + PWMCLK_DIV)) ;
  1268. }
  1269. pwm_control = *(pwm + PWM_CONTROL) ; // preserve PWM_CONTROL
  1270. // We need to stop PWM prior to stopping PWM clock in MS mode otherwise BUSY
  1271. // stays high.
  1272. *(pwm + PWM_CONTROL) = 0 ; // Stop PWM
  1273. // Stop PWM clock before changing divisor. The delay after this does need to
  1274. // this big (95uS occasionally fails, 100uS OK), it's almost as though the BUSY
  1275. // flag is not working properly in balanced mode. Without the delay when DIV is
  1276. // adjusted the clock sometimes switches to very slow, once slow further DIV
  1277. // adjustments do nothing and it's difficult to get out of this mode.
  1278. *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x01 ; // Stop PWM Clock
  1279. delayMicroseconds (110) ; // prevents clock going sloooow
  1280. while ((*(clk + PWMCLK_CNTL) & 0x80) != 0) // Wait for clock to be !BUSY
  1281. delayMicroseconds (1) ;
  1282. *(clk + PWMCLK_DIV) = BCM_PASSWORD | (divisor << 12) ;
  1283. *(clk + PWMCLK_CNTL) = BCM_PASSWORD | 0x11 ; // Start PWM clock
  1284. *(pwm + PWM_CONTROL) = pwm_control ; // restore PWM_CONTROL
  1285. if (wiringPiDebug) {
  1286. printf ("PWM clock divisor %d. Current register: 0x%08X\n", divisor, *(clk + PWMCLK_DIV));
  1287. }
  1288. }
  1289. }
  1290. /*
  1291. * gpioClockSet:
  1292. * Set the frequency on a GPIO clock pin
  1293. *********************************************************************************
  1294. */
  1295. void gpioClockSet (int pin, int freq)
  1296. {
  1297. int divi, divr, divf ;
  1298. FailOnModel5("gpioClockSet");
  1299. pin &= 63 ;
  1300. /**/ if (wiringPiMode == WPI_MODE_PINS)
  1301. pin = pinToGpio [pin] ;
  1302. else if (wiringPiMode == WPI_MODE_PHYS)
  1303. pin = physToGpio [pin] ;
  1304. else if (wiringPiMode != WPI_MODE_GPIO)
  1305. return ;
  1306. divi = 19200000 / freq ;
  1307. divr = 19200000 % freq ;
  1308. divf = (int)((double)divr * 4096.0 / 19200000.0) ;
  1309. if (divi > PWMCLK_DIVI_MAX) {
  1310. divi = PWMCLK_DIVI_MAX;
  1311. }
  1312. *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | GPIO_CLOCK_SOURCE ; // Stop GPIO Clock
  1313. while ((*(clk + gpioToClkCon [pin]) & 0x80) != 0) // ... and wait
  1314. ;
  1315. *(clk + gpioToClkDiv [pin]) = BCM_PASSWORD | (divi << 12) | divf ; // Set dividers
  1316. *(clk + gpioToClkCon [pin]) = BCM_PASSWORD | 0x10 | GPIO_CLOCK_SOURCE ; // Start Clock
  1317. }
  1318. /*
  1319. * wiringPiFindNode:
  1320. * Locate our device node
  1321. *********************************************************************************
  1322. */
  1323. struct wiringPiNodeStruct *wiringPiFindNode (int pin)
  1324. {
  1325. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1326. while (node != NULL)
  1327. if ((pin >= node->pinBase) && (pin <= node->pinMax))
  1328. return node ;
  1329. else
  1330. node = node->next ;
  1331. return NULL ;
  1332. }
  1333. /*
  1334. * wiringPiNewNode:
  1335. * Create a new GPIO node into the wiringPi handling system
  1336. *********************************************************************************
  1337. */
  1338. static void pinModeDummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int mode) { return ; }
  1339. static void pullUpDnControlDummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int pud) { return ; }
  1340. //static unsigned int digitalRead8Dummy (UNU struct wiringPiNodeStruct *node, UNU int UNU pin) { return 0 ; }
  1341. //static void digitalWrite8Dummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
  1342. static int digitalReadDummy (UNU struct wiringPiNodeStruct *node, UNU int UNU pin) { return LOW ; }
  1343. static void digitalWriteDummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
  1344. static void pwmWriteDummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
  1345. static int analogReadDummy (UNU struct wiringPiNodeStruct *node, UNU int pin) { return 0 ; }
  1346. static void analogWriteDummy (UNU struct wiringPiNodeStruct *node, UNU int pin, UNU int value) { return ; }
  1347. struct wiringPiNodeStruct *wiringPiNewNode (int pinBase, int numPins)
  1348. {
  1349. int pin ;
  1350. struct wiringPiNodeStruct *node ;
  1351. // Minimum pin base is 64
  1352. if (pinBase < 64)
  1353. (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: pinBase of %d is < 64\n", pinBase) ;
  1354. // Check all pins in-case there is overlap:
  1355. for (pin = pinBase ; pin < (pinBase + numPins) ; ++pin)
  1356. if (wiringPiFindNode (pin) != NULL)
  1357. (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Pin %d overlaps with existing definition\n", pin) ;
  1358. node = (struct wiringPiNodeStruct *)calloc (sizeof (struct wiringPiNodeStruct), 1) ; // calloc zeros
  1359. if (node == NULL)
  1360. (void)wiringPiFailure (WPI_FATAL, "wiringPiNewNode: Unable to allocate memory: %s\n", strerror (errno)) ;
  1361. node->pinBase = pinBase ;
  1362. node->pinMax = pinBase + numPins - 1 ;
  1363. node->pinMode = pinModeDummy ;
  1364. node->pullUpDnControl = pullUpDnControlDummy ;
  1365. node->digitalRead = digitalReadDummy ;
  1366. //node->digitalRead8 = digitalRead8Dummy ;
  1367. node->digitalWrite = digitalWriteDummy ;
  1368. //node->digitalWrite8 = digitalWrite8Dummy ;
  1369. node->pwmWrite = pwmWriteDummy ;
  1370. node->analogRead = analogReadDummy ;
  1371. node->analogWrite = analogWriteDummy ;
  1372. node->next = wiringPiNodes ;
  1373. wiringPiNodes = node ;
  1374. return node ;
  1375. }
  1376. #ifdef notYetReady
  1377. /*
  1378. * pinED01:
  1379. * pinED10:
  1380. * Enables edge-detect mode on a pin - from a 0 to a 1 or 1 to 0
  1381. * Pin must already be in input mode with appropriate pull up/downs set.
  1382. *********************************************************************************
  1383. */
  1384. void pinEnableED01Pi (int pin)
  1385. {
  1386. pin = pinToGpio [pin & 63] ;
  1387. }
  1388. #endif
  1389. const char DEV_GPIO_PI[] ="/dev/gpiochip0";
  1390. const char DEV_GPIO_PI5[]="/dev/gpiochip4";
  1391. int wiringPiGpioDeviceGetFd() {
  1392. if (chipFd<0) {
  1393. piBoard();
  1394. const char* gpiochip = PI_MODEL_5 == RaspberryPiModel ? DEV_GPIO_PI5 : DEV_GPIO_PI;
  1395. chipFd = open(gpiochip, O_RDWR);
  1396. if (chipFd < 0) {
  1397. fprintf(stderr, "wiringPi: ERROR: %s open ret=%d\n", gpiochip, chipFd);
  1398. } else if (wiringPiDebug) {
  1399. printf ("wiringPi: Open chip %s succeded, fd=%d\n", gpiochip, chipFd) ;
  1400. }
  1401. }
  1402. return chipFd;
  1403. }
  1404. void releaseLine(int pin) {
  1405. if (wiringPiDebug)
  1406. printf ("releaseLine: pin:%d\n", pin) ;
  1407. lineFlags[pin] = 0;
  1408. close(lineFds[pin]);
  1409. lineFds[pin] = -1;
  1410. }
  1411. int requestLine(int pin, unsigned int lineRequestFlags) {
  1412. struct gpiohandle_request rq;
  1413. if (lineFds[pin]>=0) {
  1414. if (lineRequestFlags == lineFlags[pin]) {
  1415. //already requested
  1416. return lineFds[pin];
  1417. } else {
  1418. //different request -> rerequest
  1419. releaseLine(pin);
  1420. }
  1421. }
  1422. //requested line
  1423. if (wiringPiGpioDeviceGetFd()<0) {
  1424. return -1; // error
  1425. }
  1426. rq.lineoffsets[0] = pin;
  1427. rq.lines = 1;
  1428. rq.flags = lineRequestFlags;
  1429. int ret = ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &rq);
  1430. if (ret || rq.fd<0) {
  1431. ReportDeviceError("get line handle", pin, "RequestLine", ret);
  1432. return -1; // error
  1433. }
  1434. lineFlags[pin] = lineRequestFlags;
  1435. lineFds[pin] = rq.fd;
  1436. if (wiringPiDebug)
  1437. printf ("requestLine succeeded: pin:%d, flags: %u, fd :%d\n", pin, lineRequestFlags, lineFds[pin]) ;
  1438. return lineFds[pin];
  1439. }
  1440. /*
  1441. *********************************************************************************
  1442. * Core Functions
  1443. *********************************************************************************
  1444. */
  1445. /*
  1446. * pinModeAlt:
  1447. * This is an un-documented special to let you set any pin to any mode
  1448. *********************************************************************************
  1449. */
  1450. void pinModeAlt (int pin, int mode)
  1451. {
  1452. setupCheck ("pinModeAlt") ;
  1453. if ((pin & PI_GPIO_MASK) == 0) // On-board pin
  1454. {
  1455. /**/ if (wiringPiMode == WPI_MODE_PINS)
  1456. pin = pinToGpio [pin] ;
  1457. else if (wiringPiMode == WPI_MODE_PHYS)
  1458. pin = physToGpio [pin] ;
  1459. else if (wiringPiMode != WPI_MODE_GPIO)
  1460. return ;
  1461. if (PI_MODEL_5 == RaspberryPiModel) {
  1462. //confusion! diffrent to to BCM! this is taking directly the value for the register
  1463. int modeRP1;
  1464. switch(mode) {
  1465. case FSEL_ALT0:
  1466. modeRP1 = 0;
  1467. break;
  1468. case FSEL_ALT1:
  1469. modeRP1 = 1;
  1470. break;
  1471. case FSEL_ALT2:
  1472. modeRP1 = 2;
  1473. break;
  1474. case FSEL_ALT3:
  1475. modeRP1 = 3;
  1476. break;
  1477. case FSEL_ALT4:
  1478. modeRP1 = 4;
  1479. break;
  1480. case FSEL_ALT5:
  1481. modeRP1 = 5;
  1482. break;
  1483. case FSEL_ALT6:
  1484. modeRP1 = 6;
  1485. break;
  1486. case FSEL_ALT7:
  1487. modeRP1 = 7;
  1488. break;
  1489. case FSEL_ALT8:
  1490. modeRP1 = 8;
  1491. break;
  1492. case FSEL_OUTP:
  1493. case FSEL_INPT:
  1494. modeRP1 = RP1_FSEL_GPIO;
  1495. break;
  1496. default:
  1497. fprintf(stderr, "pinModeAlt: invalid mode %d\n", mode);
  1498. return;
  1499. }
  1500. //printf("pinModeAlt: Pi5 alt pin %d to %d\n", pin, modeRP1);
  1501. gpio[2*pin+1] = (modeRP1 & RP1_FSEL_NONE_HW) | RP1_DEBOUNCE_DEFAULT; //0-4 function, 5-11 debounce time
  1502. } else {
  1503. int fSel = gpioToGPFSEL [pin] ;
  1504. int shift = gpioToShift [pin] ;
  1505. *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | ((mode & 0x7) << shift) ;
  1506. }
  1507. }
  1508. }
  1509. /*
  1510. * pinMode:
  1511. * Sets the mode of a pin to be input, output or PWM output
  1512. *********************************************************************************
  1513. */
  1514. //Default: rp1_set_pad(pin, 0, 1, 0, 1, 1, 1, 0);
  1515. void rp1_set_pad(int pin, int slewfast, int schmitt, int pulldown, int pullup, int drive, int inputenable, int outputdisable) {
  1516. pads[1+pin] = (slewfast != 0) | ((schmitt != 0) << 1) | ((pulldown != 0) << 2) | ((pullup != 0) << 3) | ((drive & 0x3) << 4) | ((inputenable != 0) << 6) | ((outputdisable != 0) << 7);
  1517. }
  1518. void pinModeFlagsDevice (int pin, int mode, unsigned int flags) {
  1519. unsigned int lflag = flags;
  1520. if (wiringPiDebug)
  1521. printf ("pinModeFlagsDevice: pin:%d mode:%d, flags: %u\n", pin, mode, flags) ;
  1522. lflag &= ~(GPIOHANDLE_REQUEST_INPUT | GPIOHANDLE_REQUEST_OUTPUT);
  1523. switch(mode) {
  1524. default:
  1525. fprintf(stderr, "pinMode: invalid mode request (only input und output supported)\n");
  1526. return;
  1527. case INPUT:
  1528. lflag |= GPIOHANDLE_REQUEST_INPUT;
  1529. break;
  1530. case OUTPUT:
  1531. lflag |= GPIOHANDLE_REQUEST_OUTPUT;
  1532. break;
  1533. case PM_OFF:
  1534. pinModeFlagsDevice(pin, INPUT, 0);
  1535. releaseLine(pin);
  1536. return;
  1537. }
  1538. requestLine(pin, lflag);
  1539. }
  1540. void pinModeDevice (int pin, int mode) {
  1541. pinModeFlagsDevice(pin, mode, lineFlags[pin]);
  1542. }
  1543. void pinMode (int pin, int mode)
  1544. {
  1545. int fSel, shift, alt ;
  1546. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1547. int origPin = pin ;
  1548. if (wiringPiDebug)
  1549. printf ("pinMode: pin:%d mode:%d\n", pin, mode) ;
  1550. setupCheck ("pinMode") ;
  1551. if ((pin & PI_GPIO_MASK) == 0) // On-board pin
  1552. {
  1553. switch(wiringPiMode) {
  1554. default: //WPI_MODE_GPIO_SYS
  1555. fprintf(stderr, "pinMode: invalid mode\n");
  1556. return;
  1557. case WPI_MODE_PINS:
  1558. pin = pinToGpio [pin];
  1559. break;
  1560. case WPI_MODE_PHYS:
  1561. pin = physToGpio [pin];
  1562. break;
  1563. case WPI_MODE_GPIO_DEVICE_BCM:
  1564. pinModeDevice(pin, mode);
  1565. return;
  1566. case WPI_MODE_GPIO_DEVICE_WPI:
  1567. pinModeDevice(pinToGpio[pin], mode);
  1568. return;
  1569. case WPI_MODE_GPIO_DEVICE_PHYS:
  1570. pinModeDevice(physToGpio[pin], mode);
  1571. return;
  1572. case WPI_MODE_GPIO:
  1573. break;
  1574. }
  1575. if (wiringPiDebug)
  1576. printf ("pinMode: bcm pin:%d mode:%d\n", pin, mode) ;
  1577. softPwmStop (origPin) ;
  1578. softToneStop (origPin) ;
  1579. fSel = gpioToGPFSEL [pin] ;
  1580. shift = gpioToShift [pin] ;
  1581. if (INPUT==mode || PM_OFF==mode) {
  1582. if (PI_MODEL_5 == RaspberryPiModel) {
  1583. if (INPUT==mode) {
  1584. pads[1+pin] = (pin<=8) ? RP1_PAD_DEFAULT_0TO8 : RP1_PAD_DEFAULT_FROM9;
  1585. gpio[2*pin+1] = RP1_FSEL_GPIO | RP1_DEBOUNCE_DEFAULT; // GPIO
  1586. rio[RP1_RIO_OE + RP1_CLR_OFFSET] = 1<<pin; // Input
  1587. } else { //PM_OFF
  1588. pads[1+pin] = (pin<=8) ? RP1_PAD_IC_DEFAULT_0TO8 : RP1_PAD_IC_DEFAULT_FROM9;
  1589. gpio[2*pin+1] = RP1_IRQRESET | RP1_FSEL_NONE_HW | RP1_DEBOUNCE_DEFAULT; // default but with irq reset
  1590. }
  1591. } else {
  1592. *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) ; // Sets bits to zero = input
  1593. }
  1594. if (PM_OFF==mode && !usingGpioMem && pwm && gpioToPwmALT[pin]>0) { //PWM pin -> reset
  1595. pwmWrite(origPin, 0);
  1596. int channel = gpioToPwmPort[pin];
  1597. if (channel>=0 && channel<=3 && PI_MODEL_5 == RaspberryPiModel) {
  1598. unsigned int ctrl = pwm[RP1_PWM0_GLOBAL_CTRL];
  1599. pwm[RP1_PWM0_GLOBAL_CTRL] = (ctrl & ~(1<<channel)) | RP1_PWM_CTRL_SETUPDATE;
  1600. //printf("Disable PWM0[%d] (0x%08X->0x%08X)\n", channel, ctrl, pwm[RP1_PWM0_GLOBAL_CTRL]);
  1601. }
  1602. }
  1603. } else if (mode == OUTPUT) {
  1604. if (PI_MODEL_5 == RaspberryPiModel) {
  1605. pads[1+pin] = (pin<=8) ? RP1_PAD_DEFAULT_0TO8 : RP1_PAD_DEFAULT_FROM9;
  1606. gpio[2*pin+1] = RP1_FSEL_GPIO | RP1_DEBOUNCE_DEFAULT; // GPIO
  1607. rio[RP1_RIO_OE + RP1_SET_OFFSET] = 1<<pin; // Output
  1608. } else {
  1609. *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (1 << shift) ;
  1610. }
  1611. } else if (mode == SOFT_PWM_OUTPUT) {
  1612. softPwmCreate (origPin, 0, 100) ;
  1613. } else if (mode == SOFT_TONE_OUTPUT) {
  1614. softToneCreate (origPin) ;
  1615. } else if (mode == PWM_TONE_OUTPUT)
  1616. {
  1617. pinMode (origPin, PWM_OUTPUT) ; // Call myself to enable PWM mode
  1618. pwmSetMode (PWM_MODE_MS) ;
  1619. }
  1620. else if (PWM_OUTPUT==mode || PWM_MS_OUTPUT==mode || PWM_BAL_OUTPUT==mode) {
  1621. usingGpioMemCheck("pinMode PWM") ; // exit on error!
  1622. alt = gpioToPwmALT[pin];
  1623. if (0==alt) { // Not a hardware capable PWM pin
  1624. return;
  1625. }
  1626. int channel = gpioToPwmPort[pin];
  1627. if (PI_MODEL_5 == RaspberryPiModel) {
  1628. if (channel>=0 && channel<=3) {
  1629. // enable channel pwm m:s mode
  1630. pwm[RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*channel+RP1_PWM0_CHAN_CTRL] = (RP1_PWM_TRAIL_EDGE_MS | RP1_PWM_FIFO_POP_MASK);
  1631. // enable pwm global
  1632. unsigned int ctrl = pwm[RP1_PWM0_GLOBAL_CTRL];
  1633. pwm[RP1_PWM0_GLOBAL_CTRL] = ctrl | (1<<channel) | RP1_PWM_CTRL_SETUPDATE;
  1634. //printf("Enable PWM0[%d] (0x%08X->0x%08X)\n", channel, ctrl, pwm[RP1_PWM0_GLOBAL_CTRL]);
  1635. //change GPIO mode
  1636. pads[1+pin] = RP1_PAD_DEFAULT_FROM9; // enable output
  1637. pinModeAlt(origPin, alt); //switch to PWM mode
  1638. }
  1639. } else {
  1640. // Set pin to PWM mode
  1641. *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
  1642. delayMicroseconds (110) ; // See comments in pwmSetClockWPi
  1643. if (PWM_OUTPUT==mode || PWM_BAL_OUTPUT==mode) {
  1644. pwmSetMode(PWM_MODE_BAL); // Pi default mode
  1645. } else {
  1646. pwmSetMode(PWM_MODE_MS);
  1647. }
  1648. }
  1649. if (PWM_OUTPUT==mode) { // predefine
  1650. pwmSetRange (1024) ; // Default range of 1024
  1651. pwmSetClock (32) ; // 19.2 / 32 = 600KHz - Also starts the PWM
  1652. }
  1653. }
  1654. else if (mode == GPIO_CLOCK)
  1655. {
  1656. RETURN_ON_MODEL5
  1657. if ((alt = gpioToGpClkALT0 [pin]) == 0) // Not a GPIO_CLOCK pin
  1658. return ;
  1659. usingGpioMemCheck ("pinMode CLOCK") ;
  1660. // Set pin to GPIO_CLOCK mode and set the clock frequency to 100KHz
  1661. *(gpio + fSel) = (*(gpio + fSel) & ~(7 << shift)) | (alt << shift) ;
  1662. delayMicroseconds (110) ;
  1663. gpioClockSet (pin, 100000) ;
  1664. }
  1665. }
  1666. else
  1667. {
  1668. if ((node = wiringPiFindNode (pin)) != NULL)
  1669. node->pinMode (node, pin, mode) ;
  1670. return ;
  1671. }
  1672. }
  1673. /*
  1674. * pullUpDownCtrl:
  1675. * Control the internal pull-up/down resistors on a GPIO pin.
  1676. *********************************************************************************
  1677. */
  1678. void pullUpDnControlDevice (int pin, int pud) {
  1679. unsigned int flag = lineFlags[pin];
  1680. unsigned int biasflags = GPIOHANDLE_REQUEST_BIAS_DISABLE | GPIOHANDLE_REQUEST_BIAS_PULL_UP | GPIOHANDLE_REQUEST_BIAS_PULL_DOWN;
  1681. flag &= ~biasflags;
  1682. switch (pud){
  1683. case PUD_OFF: flag |= GPIOHANDLE_REQUEST_BIAS_DISABLE; break;
  1684. case PUD_UP: flag |= GPIOHANDLE_REQUEST_BIAS_PULL_UP; break;
  1685. case PUD_DOWN: flag |= GPIOHANDLE_REQUEST_BIAS_PULL_DOWN; break;
  1686. default: return ; /* An illegal value */
  1687. }
  1688. // reset input/output
  1689. if (lineFlags[pin] & GPIOHANDLE_REQUEST_OUTPUT) {
  1690. pinModeFlagsDevice (pin, OUTPUT, flag);
  1691. } else if(lineFlags[pin] & GPIOHANDLE_REQUEST_INPUT) {
  1692. pinModeFlagsDevice (pin, INPUT, flag);
  1693. } else {
  1694. lineFlags[pin] = flag; // only store for later
  1695. }
  1696. }
  1697. void pullUpDnControl (int pin, int pud)
  1698. {
  1699. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1700. setupCheck ("pullUpDnControl") ;
  1701. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1702. {
  1703. switch(wiringPiMode) {
  1704. default: //WPI_MODE_GPIO_SYS
  1705. fprintf(stderr, "pinMode: invalid mode\n");
  1706. return;
  1707. case WPI_MODE_PINS:
  1708. pin = pinToGpio [pin];
  1709. break;
  1710. case WPI_MODE_PHYS:
  1711. pin = physToGpio [pin];
  1712. break;
  1713. case WPI_MODE_GPIO_DEVICE_BCM:
  1714. return pullUpDnControlDevice(pin, pud);
  1715. case WPI_MODE_GPIO_DEVICE_WPI:
  1716. return pullUpDnControlDevice(pinToGpio[pin], pud);
  1717. case WPI_MODE_GPIO_DEVICE_PHYS:
  1718. return pullUpDnControlDevice(physToGpio[pin], pud);
  1719. case WPI_MODE_GPIO:
  1720. break;
  1721. }
  1722. if (PI_MODEL_5 == RaspberryPiModel) {
  1723. unsigned int pullbits = pads[1+pin] & RP1_INV_PUD_MASK; // remove bits
  1724. switch (pud){
  1725. case PUD_OFF: pads[1+pin] = pullbits; break;
  1726. case PUD_UP: pads[1+pin] = pullbits | RP1_PUD_UP; break;
  1727. case PUD_DOWN: pads[1+pin] = pullbits | RP1_PUD_DOWN; break;
  1728. default: return ; /* An illegal value */
  1729. }
  1730. } else {
  1731. if (piGpioPupOffset == GPPUPPDN0)
  1732. {
  1733. // Pi 4B pull up/down method
  1734. int pullreg = GPPUPPDN0 + (pin>>4);
  1735. int pullshift = (pin & 0xf) << 1;
  1736. unsigned int pullbits;
  1737. unsigned int pull;
  1738. switch (pud) {
  1739. case PUD_OFF: pull = 0; break;
  1740. case PUD_UP: pull = 1; break;
  1741. case PUD_DOWN: pull = 2; break;
  1742. default: return ; /* An illegal value */
  1743. }
  1744. pullbits = *(gpio + pullreg);
  1745. pullbits &= ~(3 << pullshift);
  1746. pullbits |= (pull << pullshift);
  1747. *(gpio + pullreg) = pullbits;
  1748. }
  1749. else
  1750. {
  1751. // legacy pull up/down method
  1752. *(gpio + GPPUD) = pud & 3 ; delayMicroseconds (5) ;
  1753. *(gpio + gpioToPUDCLK [pin]) = 1 << (pin & 31) ; delayMicroseconds (5) ;
  1754. *(gpio + GPPUD) = 0 ; delayMicroseconds (5) ;
  1755. *(gpio + gpioToPUDCLK [pin]) = 0 ; delayMicroseconds (5) ;
  1756. }
  1757. }
  1758. }
  1759. else // Extension module
  1760. {
  1761. if ((node = wiringPiFindNode (pin)) != NULL)
  1762. node->pullUpDnControl (node, pin, pud) ;
  1763. return ;
  1764. }
  1765. }
  1766. /*
  1767. * digitalRead:
  1768. * Read the value of a given Pin, returning HIGH or LOW
  1769. *********************************************************************************
  1770. */
  1771. int digitalReadDevice (int pin) { // INPUT and OUTPUT should work
  1772. if (lineFds[pin]<0) {
  1773. // line not requested - auto request on first read as input
  1774. pinModeDevice(pin, INPUT);
  1775. }
  1776. if (lineFds[pin]>=0) {
  1777. struct gpiohandle_data data;
  1778. int ret = ioctl(lineFds[pin], GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
  1779. if (ret) {
  1780. ReportDeviceError("get line values", pin, "digitalRead", ret);
  1781. return LOW; // error
  1782. }
  1783. return data.values[0];
  1784. }
  1785. return LOW; // error , need to request line before
  1786. }
  1787. int digitalRead (int pin)
  1788. {
  1789. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1790. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1791. {
  1792. switch(wiringPiMode) {
  1793. default: //WPI_MODE_GPIO_SYS
  1794. fprintf(stderr, "digitalRead: invalid mode\n");
  1795. return LOW;
  1796. case WPI_MODE_PINS:
  1797. pin = pinToGpio [pin];
  1798. break;
  1799. case WPI_MODE_PHYS:
  1800. pin = physToGpio [pin];
  1801. break;
  1802. case WPI_MODE_GPIO_DEVICE_BCM:
  1803. return digitalReadDevice(pin);
  1804. case WPI_MODE_GPIO_DEVICE_WPI:
  1805. return digitalReadDevice(pinToGpio[pin]);
  1806. case WPI_MODE_GPIO_DEVICE_PHYS:
  1807. return digitalReadDevice(physToGpio[pin]);
  1808. case WPI_MODE_GPIO:
  1809. break;
  1810. }
  1811. if (PI_MODEL_5 == RaspberryPiModel) {
  1812. switch(gpio[2*pin] & RP1_STATUS_LEVEL_MASK) {
  1813. default: // 11 or 00 not allowed, give LOW!
  1814. case RP1_STATUS_LEVEL_LOW: return LOW ;
  1815. case RP1_STATUS_LEVEL_HIGH: return HIGH ;
  1816. }
  1817. } else {
  1818. if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
  1819. return HIGH ;
  1820. else
  1821. return LOW ;
  1822. }
  1823. }
  1824. else
  1825. {
  1826. if ((node = wiringPiFindNode (pin)) == NULL)
  1827. return LOW ;
  1828. return node->digitalRead (node, pin) ;
  1829. }
  1830. }
  1831. /*
  1832. * digitalRead8:
  1833. * Read 8-bits (a byte) from given start pin.
  1834. *********************************************************************************
  1835. unsigned int digitalRead8 (int pin)
  1836. {
  1837. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1838. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1839. return 0 ;
  1840. else
  1841. {
  1842. if ((node = wiringPiFindNode (pin)) == NULL)
  1843. return LOW ;
  1844. return node->digitalRead8 (node, pin) ;
  1845. }
  1846. }
  1847. */
  1848. /*
  1849. * digitalWrite:
  1850. * Set an output bit
  1851. *********************************************************************************
  1852. */
  1853. void digitalWriteDevice (int pin, int value) {
  1854. if (wiringPiDebug)
  1855. printf ("digitalWriteDevice: ioctl pin:%d value: %d\n", pin, value) ;
  1856. if (lineFds[pin]<0) {
  1857. // line not requested - auto request on first write as output
  1858. pinModeDevice(pin, OUTPUT);
  1859. }
  1860. if (lineFds[pin]>=0 && (lineFlags[pin] & GPIOHANDLE_REQUEST_OUTPUT)>0) {
  1861. struct gpiohandle_data data;
  1862. data.values[0] = value;
  1863. if (wiringPiDebug)
  1864. printf ("digitalWriteDevice: ioctl pin:%d cmd: GPIOHANDLE_SET_LINE_VALUES_IOCTL, value: %d\n", pin, value) ;
  1865. int ret = ioctl(lineFds[pin], GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
  1866. if (ret) {
  1867. ReportDeviceError("set line values", pin, "digitalWrite", ret);
  1868. return; // error
  1869. }
  1870. } else {
  1871. fprintf(stderr, "digitalWrite: no output (%d)\n", lineFlags[pin]);
  1872. }
  1873. return; // error
  1874. }
  1875. void digitalWrite (int pin, int value)
  1876. {
  1877. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1878. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1879. {
  1880. switch(wiringPiMode) {
  1881. default: //WPI_MODE_GPIO_SYS
  1882. fprintf(stderr, "digitalWrite: invalid mode\n");
  1883. return;
  1884. case WPI_MODE_PINS:
  1885. pin = pinToGpio [pin];
  1886. break;
  1887. case WPI_MODE_PHYS:
  1888. pin = physToGpio [pin];
  1889. break;
  1890. case WPI_MODE_GPIO_DEVICE_BCM:
  1891. digitalWriteDevice(pin, value);
  1892. return;
  1893. case WPI_MODE_GPIO_DEVICE_WPI:
  1894. digitalWriteDevice(pinToGpio[pin], value);
  1895. return;
  1896. case WPI_MODE_GPIO_DEVICE_PHYS:
  1897. digitalWriteDevice(physToGpio[pin], value);
  1898. return;
  1899. case WPI_MODE_GPIO:
  1900. break;
  1901. }
  1902. if (PI_MODEL_5 == RaspberryPiModel) {
  1903. if (value == LOW) {
  1904. //printf("Set pin %d >>0x%08x<< to low\n", pin, 1<<pin);
  1905. rio[RP1_RIO_OUT + RP1_CLR_OFFSET] = 1<<pin;
  1906. } else {
  1907. //printf("Set pin %d >>0x%08x<< to high\n", pin, 1<<pin);
  1908. rio[RP1_RIO_OUT + RP1_SET_OFFSET] = 1<<pin;
  1909. }
  1910. } else {
  1911. if (value == LOW)
  1912. *(gpio + gpioToGPCLR [pin]) = 1 << (pin & 31) ;
  1913. else
  1914. *(gpio + gpioToGPSET [pin]) = 1 << (pin & 31) ;
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if ((node = wiringPiFindNode (pin)) != NULL)
  1920. node->digitalWrite (node, pin, value) ;
  1921. }
  1922. }
  1923. /*
  1924. * digitalWrite8:
  1925. * Set an output 8-bit byte on the device from the given pin number
  1926. *********************************************************************************
  1927. void digitalWrite8 (int pin, int value)
  1928. {
  1929. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1930. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1931. return ;
  1932. else
  1933. {
  1934. if ((node = wiringPiFindNode (pin)) != NULL)
  1935. node->digitalWrite8 (node, pin, value) ;
  1936. }
  1937. }
  1938. */
  1939. /*
  1940. * pwmWrite:
  1941. * Set an output PWM value
  1942. *********************************************************************************
  1943. */
  1944. void pwmWrite (int pin, int value)
  1945. {
  1946. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1947. setupCheck ("pwmWrite") ;
  1948. if ((pin & PI_GPIO_MASK) == 0) // On-Board Pin
  1949. {
  1950. /**/ if (wiringPiMode == WPI_MODE_PINS)
  1951. pin = pinToGpio [pin] ;
  1952. else if (wiringPiMode == WPI_MODE_PHYS)
  1953. pin = physToGpio [pin] ;
  1954. else if (wiringPiMode != WPI_MODE_GPIO)
  1955. return ;
  1956. /* would be possible on ms mode but not on bal, deactivated, use pwmc modify instead
  1957. if (piGpioBase == GPIO_PERI_BASE_2711) {
  1958. value = (OSC_FREQ_BCM2711*value)/OSC_FREQ_DEFAULT;
  1959. }
  1960. */
  1961. usingGpioMemCheck ("pwmWrite") ;
  1962. int channel = gpioToPwmPort[pin];
  1963. int readback = 0x00;
  1964. if (PI_MODEL_5 == RaspberryPiModel ) {
  1965. if (channel>=0 && channel<=3) {
  1966. unsigned int addr = RP1_PWM0_CHAN_START+RP1_PWM0_CHAN_OFFSET*channel+RP1_PWM0_CHAN_DUTY;
  1967. pwm[addr] = value;
  1968. readback = pwm[addr];
  1969. } else {
  1970. fprintf(stderr, "pwmWrite: invalid channel at GPIO pin %d \n", pin);
  1971. }
  1972. } else {
  1973. *(pwm + channel) = value ;
  1974. readback = *(pwm + channel);
  1975. }
  1976. if (wiringPiDebug) {
  1977. printf ("PWM value(duty): %u. Current register: 0x%08X\n", value, readback);
  1978. }
  1979. }
  1980. else
  1981. {
  1982. if ((node = wiringPiFindNode (pin)) != NULL)
  1983. node->pwmWrite (node, pin, value) ;
  1984. }
  1985. }
  1986. /*
  1987. * analogRead:
  1988. * Read the analog value of a given Pin.
  1989. * There is no on-board Pi analog hardware,
  1990. * so this needs to go to a new node.
  1991. *********************************************************************************
  1992. */
  1993. int analogRead (int pin)
  1994. {
  1995. struct wiringPiNodeStruct *node = wiringPiNodes ;
  1996. if ((node = wiringPiFindNode (pin)) == NULL)
  1997. return 0 ;
  1998. else
  1999. return node->analogRead (node, pin) ;
  2000. }
  2001. /*
  2002. * analogWrite:
  2003. * Write the analog value to the given Pin.
  2004. * There is no on-board Pi analog hardware,
  2005. * so this needs to go to a new node.
  2006. *********************************************************************************
  2007. */
  2008. void analogWrite (int pin, int value)
  2009. {
  2010. struct wiringPiNodeStruct *node = wiringPiNodes ;
  2011. if ((node = wiringPiFindNode (pin)) == NULL)
  2012. return ;
  2013. node->analogWrite (node, pin, value) ;
  2014. }
  2015. /*
  2016. * pwmToneWrite:
  2017. * Pi Specific.
  2018. * Output the given frequency on the Pi's PWM pin
  2019. *********************************************************************************
  2020. */
  2021. void pwmToneWrite (int pin, int freq)
  2022. {
  2023. setupCheck ("pwmToneWrite") ;
  2024. if (freq == 0)
  2025. pwmWrite (pin, 0) ; // Off
  2026. else
  2027. {
  2028. int range = 600000 / freq ;
  2029. pwmSetRange (range) ;
  2030. pwmWrite (pin, freq / 2) ;
  2031. }
  2032. }
  2033. /*
  2034. * digitalWriteByte:
  2035. * digitalReadByte:
  2036. * Pi Specific
  2037. * Write an 8-bit byte to the first 8 GPIO pins - try to do it as
  2038. * fast as possible.
  2039. * However it still needs 2 operations to set the bits, so any external
  2040. * hardware must not rely on seeing a change as there will be a change
  2041. * to set the outputs bits to zero, then another change to set the 1's
  2042. * Reading is just bit fiddling.
  2043. * These are wiringPi pin numbers 0..7, or BCM_GPIO pin numbers
  2044. * 17, 18, 22, 23, 24, 24, 4 on a Pi v1 rev 0-3
  2045. * 17, 18, 27, 23, 24, 24, 4 on a Pi v1 rev 3 onwards or B+, 2, 3, zero
  2046. *********************************************************************************
  2047. */
  2048. void digitalWriteByte (const int value)
  2049. {
  2050. uint32_t pinSet = 0 ;
  2051. uint32_t pinClr = 0 ;
  2052. int mask = 1 ;
  2053. int pin ;
  2054. FailOnModel5("digitalWriteByte");
  2055. if (wiringPiMode == WPI_MODE_GPIO_SYS)
  2056. {
  2057. return ;
  2058. }
  2059. else
  2060. {
  2061. for (pin = 0 ; pin < 8 ; ++pin)
  2062. {
  2063. if ((value & mask) == 0)
  2064. pinClr |= (1 << pinToGpio [pin]) ;
  2065. else
  2066. pinSet |= (1 << pinToGpio [pin]) ;
  2067. mask <<= 1 ;
  2068. }
  2069. *(gpio + gpioToGPCLR [0]) = pinClr ;
  2070. *(gpio + gpioToGPSET [0]) = pinSet ;
  2071. }
  2072. }
  2073. unsigned int digitalReadByte (void)
  2074. {
  2075. int pin, x ;
  2076. uint32_t raw ;
  2077. uint32_t data = 0 ;
  2078. FailOnModel5("digitalReadByte");
  2079. if (wiringPiMode == WPI_MODE_GPIO_SYS)
  2080. {
  2081. return 0;
  2082. }
  2083. else
  2084. {
  2085. raw = *(gpio + gpioToGPLEV [0]) ; // First bank for these pins
  2086. for (pin = 0 ; pin < 8 ; ++pin)
  2087. {
  2088. x = pinToGpio [pin] ;
  2089. data = (data << 1) | (((raw & (1 << x)) == 0) ? 0 : 1) ;
  2090. }
  2091. }
  2092. return data ;
  2093. }
  2094. /*
  2095. * digitalWriteByte2:
  2096. * digitalReadByte2:
  2097. * Pi Specific
  2098. * Write an 8-bit byte to the second set of 8 GPIO pins. This is marginally
  2099. * faster than the first lot as these are consecutive BCM_GPIO pin numbers.
  2100. * However they overlap with the original read/write bytes.
  2101. *********************************************************************************
  2102. */
  2103. void digitalWriteByte2 (const int value)
  2104. {
  2105. FailOnModel5("digitalWriteByte2");
  2106. if (wiringPiMode == WPI_MODE_GPIO_SYS)
  2107. {
  2108. }
  2109. else
  2110. {
  2111. *(gpio + gpioToGPCLR [0]) = (~value & 0xFF) << 20 ; // 0x0FF00000; ILJ > CHANGE: Old causes glitch
  2112. *(gpio + gpioToGPSET [0]) = ( value & 0xFF) << 20 ;
  2113. }
  2114. }
  2115. unsigned int digitalReadByte2 (void)
  2116. {
  2117. uint32_t data = 0 ;
  2118. FailOnModel5("digitalReadByte2");
  2119. if (wiringPiMode == WPI_MODE_GPIO_SYS)
  2120. {
  2121. }
  2122. else
  2123. data = ((*(gpio + gpioToGPLEV [0])) >> 20) & 0xFF ; // First bank for these pins
  2124. return data ;
  2125. }
  2126. /*
  2127. * waitForInterrupt:
  2128. * Pi Specific.
  2129. * Wait for Interrupt on a GPIO pin.
  2130. * This is actually done via the /dev/gpiochip interface regardless of
  2131. * the wiringPi access mode in-use. Maybe sometime it might get a better
  2132. * way for a bit more efficiency.
  2133. *********************************************************************************
  2134. */
  2135. int waitForInterrupt (int pin, int mS)
  2136. {
  2137. int fd, ret;
  2138. struct pollfd polls ;
  2139. struct gpioevent_data evdata;
  2140. //struct gpio_v2_line_request req2;
  2141. if (wiringPiMode == WPI_MODE_PINS)
  2142. pin = pinToGpio [pin] ;
  2143. else if (wiringPiMode == WPI_MODE_PHYS)
  2144. pin = physToGpio [pin] ;
  2145. if ((fd = isrFds [pin]) == -1)
  2146. return -2 ;
  2147. // Setup poll structure
  2148. polls.fd = fd;
  2149. polls.events = POLLIN | POLLERR ;
  2150. polls.revents = 0;
  2151. // Wait for it ...
  2152. ret = poll(&polls, 1, mS);
  2153. if (ret <= 0) {
  2154. fprintf(stderr, "wiringPi: ERROR: poll returned=%d\n", ret);
  2155. } else {
  2156. //if (polls.revents & POLLIN)
  2157. if (wiringPiDebug) {
  2158. printf ("wiringPi: IRQ line %d received %d, fd=%d\n", pin, ret, isrFds[pin]) ;
  2159. }
  2160. /* read event data */
  2161. int readret = read(isrFds [pin], &evdata, sizeof(evdata));
  2162. if (readret == sizeof(evdata)) {
  2163. if (wiringPiDebug) {
  2164. printf ("wiringPi: IRQ data id: %d, timestamp: %lld\n", evdata.id, evdata.timestamp) ;
  2165. }
  2166. ret = evdata.id;
  2167. } else {
  2168. ret = 0;
  2169. }
  2170. }
  2171. return ret;
  2172. }
  2173. int waitForInterruptInit (int pin, int mode)
  2174. {
  2175. const char* strmode = "";
  2176. if (wiringPiMode == WPI_MODE_PINS) {
  2177. pin = pinToGpio [pin] ;
  2178. } else if (wiringPiMode == WPI_MODE_PHYS) {
  2179. pin = physToGpio [pin] ;
  2180. }
  2181. /* open gpio */
  2182. sleep(1);
  2183. if (wiringPiGpioDeviceGetFd()<0) {
  2184. return -1;
  2185. }
  2186. struct gpioevent_request req;
  2187. req.lineoffset = pin;
  2188. req.handleflags = GPIOHANDLE_REQUEST_INPUT;
  2189. switch(mode) {
  2190. default:
  2191. case INT_EDGE_SETUP:
  2192. if (wiringPiDebug) {
  2193. printf ("wiringPi: waitForInterruptMode mode INT_EDGE_SETUP - exiting\n") ;
  2194. }
  2195. return -1;
  2196. case INT_EDGE_FALLING:
  2197. req.eventflags = GPIOEVENT_REQUEST_FALLING_EDGE;
  2198. strmode = "falling";
  2199. break;
  2200. case INT_EDGE_RISING:
  2201. req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
  2202. strmode = "rising";
  2203. break;
  2204. case INT_EDGE_BOTH:
  2205. req.eventflags = GPIOEVENT_REQUEST_BOTH_EDGES;
  2206. strmode = "both";
  2207. break;
  2208. }
  2209. strncpy(req.consumer_label, "wiringpi_gpio_irq", sizeof(req.consumer_label) - 1);
  2210. //later implement GPIO_V2_GET_LINE_IOCTL req2
  2211. int ret = ioctl(chipFd, GPIO_GET_LINEEVENT_IOCTL, &req);
  2212. if (ret) {
  2213. ReportDeviceError("get line event", pin , strmode, ret);
  2214. return -1;
  2215. }
  2216. if (wiringPiDebug) {
  2217. printf ("wiringPi: GPIO get line %d , mode %s succeded, fd=%d\n", pin, strmode, req.fd) ;
  2218. }
  2219. /* set event fd nonbloack read */
  2220. int fd_line = req.fd;
  2221. isrFds [pin] = fd_line;
  2222. int flags = fcntl(fd_line, F_GETFL);
  2223. flags |= O_NONBLOCK;
  2224. ret = fcntl(fd_line, F_SETFL, flags);
  2225. if (ret) {
  2226. fprintf(stderr, "wiringPi: ERROR: fcntl set nonblock return=%d\n", ret);
  2227. return -1;
  2228. }
  2229. return 0;
  2230. }
  2231. int waitForInterruptClose (int pin) {
  2232. if (isrFds[pin]>0) {
  2233. if (wiringPiDebug) {
  2234. printf ("wiringPi: waitForInterruptClose close thread 0x%lX\n", (unsigned long)isrThreads[pin]) ;
  2235. }
  2236. if (pthread_cancel(isrThreads[pin]) == 0) {
  2237. if (wiringPiDebug) {
  2238. printf ("wiringPi: waitForInterruptClose thread canceled successfuly\n") ;
  2239. }
  2240. } else {
  2241. if (wiringPiDebug) {
  2242. fprintf (stderr, "wiringPi: waitForInterruptClose could not cancel thread\n");
  2243. }
  2244. }
  2245. close(isrFds [pin]);
  2246. }
  2247. isrFds [pin] = -1;
  2248. isrFunctions [pin] = NULL;
  2249. /* -not closing so far - other isr may be using it - only close if no other is using - will code later
  2250. if (chipFd>0) {
  2251. close(chipFd);
  2252. }
  2253. chipFd = -1;
  2254. */
  2255. if (wiringPiDebug) {
  2256. printf ("wiringPi: waitForInterruptClose finished\n") ;
  2257. }
  2258. return 0;
  2259. }
  2260. int wiringPiISRStop (int pin) {
  2261. return waitForInterruptClose (pin);
  2262. }
  2263. /*
  2264. * interruptHandler:
  2265. * This is a thread and gets started to wait for the interrupt we're
  2266. * hoping to catch. It will call the user-function when the interrupt
  2267. * fires.
  2268. *********************************************************************************
  2269. */
  2270. static void *interruptHandler (UNU void *arg)
  2271. {
  2272. int pin ;
  2273. (void)piHiPri (55) ; // Only effective if we run as root
  2274. pin = pinPass ;
  2275. pinPass = -1 ;
  2276. for (;;) {
  2277. int ret = waitForInterrupt(pin, -1);
  2278. if ( ret> 0) {
  2279. if (wiringPiDebug) {
  2280. printf ("wiringPi: call function\n") ;
  2281. }
  2282. if(isrFunctions [pin]) {
  2283. isrFunctions [pin] () ;
  2284. }
  2285. // wait again - in the past forever - now can be stopped by waitForInterruptClose
  2286. } else if( ret< 0) {
  2287. break; // stop thread!
  2288. }
  2289. }
  2290. waitForInterruptClose (pin);
  2291. if (wiringPiDebug) {
  2292. printf ("wiringPi: interruptHandler finished\n") ;
  2293. }
  2294. return NULL ;
  2295. }
  2296. /*
  2297. * wiringPiISR:
  2298. * Pi Specific.
  2299. * Take the details and create an interrupt handler that will do a call-
  2300. * back to the user supplied function.
  2301. *********************************************************************************
  2302. */
  2303. int wiringPiISR (int pin, int mode, void (*function)(void))
  2304. {
  2305. const int maxpin = GetMaxPin();
  2306. if (pin < 0 || pin > maxpin)
  2307. return wiringPiFailure (WPI_FATAL, "wiringPiISR: pin must be 0-%d (%d)\n", maxpin, pin) ;
  2308. if (wiringPiMode == WPI_MODE_UNINITIALISED)
  2309. return wiringPiFailure (WPI_FATAL, "wiringPiISR: wiringPi has not been initialised. Unable to continue.\n") ;
  2310. if (wiringPiDebug) {
  2311. printf ("wiringPi: wiringPiISR pin %d, mode %d\n", pin, mode) ;
  2312. }
  2313. if (isrFunctions [pin]) {
  2314. printf ("wiringPi: ISR function alread active, ignoring \n") ;
  2315. }
  2316. isrFunctions [pin] = function ;
  2317. isrMode[pin] = mode;
  2318. if(waitForInterruptInit (pin, mode)<0) {
  2319. if (wiringPiDebug) {
  2320. fprintf (stderr, "wiringPi: waitForInterruptInit failed\n") ;
  2321. }
  2322. };
  2323. if (wiringPiDebug) {
  2324. printf ("wiringPi: mutex in\n") ;
  2325. }
  2326. pthread_mutex_lock (&pinMutex) ;
  2327. pinPass = pin ;
  2328. if (wiringPiDebug) {
  2329. printf("wiringPi: pthread_create before 0x%lX\n", (unsigned long)isrThreads[pin]);
  2330. }
  2331. if (pthread_create (&isrThreads[pin], NULL, interruptHandler, NULL)==0) {
  2332. if (wiringPiDebug) {
  2333. printf("wiringPi: pthread_create successed, 0x%lX\n", (unsigned long)isrThreads[pin]);
  2334. }
  2335. while (pinPass != -1)
  2336. delay (1) ;
  2337. } else {
  2338. if (wiringPiDebug) {
  2339. printf("wiringPi: pthread_create failed\n");
  2340. }
  2341. }
  2342. if (wiringPiDebug) {
  2343. printf ("wiringPi: mutex out\n") ;
  2344. }
  2345. pthread_mutex_unlock (&pinMutex) ;
  2346. if (wiringPiDebug) {
  2347. printf ("wiringPi: wiringPiISR finished\n") ;
  2348. }
  2349. return 0 ;
  2350. }
  2351. /*
  2352. * initialiseEpoch:
  2353. * Initialise our start-of-time variable to be the current unix
  2354. * time in milliseconds and microseconds.
  2355. *********************************************************************************
  2356. */
  2357. static void initialiseEpoch (void)
  2358. {
  2359. #ifdef OLD_WAY
  2360. struct timeval tv ;
  2361. gettimeofday (&tv, NULL) ;
  2362. epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
  2363. epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
  2364. #else
  2365. struct timespec ts ;
  2366. clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
  2367. epochMilli = (uint64_t)ts.tv_sec * (uint64_t)1000 + (uint64_t)(ts.tv_nsec / 1000000L) ;
  2368. epochMicro = (uint64_t)ts.tv_sec * (uint64_t)1000000 + (uint64_t)(ts.tv_nsec / 1000L) ;
  2369. #endif
  2370. }
  2371. /*
  2372. * delay:
  2373. * Wait for some number of milliseconds
  2374. *********************************************************************************
  2375. */
  2376. void delay (unsigned int howLong)
  2377. {
  2378. struct timespec sleeper, dummy ;
  2379. sleeper.tv_sec = (time_t)(howLong / 1000) ;
  2380. sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
  2381. nanosleep (&sleeper, &dummy) ;
  2382. }
  2383. /*
  2384. * delayMicroseconds:
  2385. * This is somewhat intersting. It seems that on the Pi, a single call
  2386. * to nanosleep takes some 80 to 130 microseconds anyway, so while
  2387. * obeying the standards (may take longer), it's not always what we
  2388. * want!
  2389. *
  2390. * So what I'll do now is if the delay is less than 100uS we'll do it
  2391. * in a hard loop, watching a built-in counter on the ARM chip. This is
  2392. * somewhat sub-optimal in that it uses 100% CPU, something not an issue
  2393. * in a microcontroller, but under a multi-tasking, multi-user OS, it's
  2394. * wastefull, however we've no real choice )-:
  2395. *
  2396. * Plan B: It seems all might not be well with that plan, so changing it
  2397. * to use gettimeofday () and poll on that instead...
  2398. *********************************************************************************
  2399. */
  2400. void delayMicrosecondsHard (unsigned int howLong)
  2401. {
  2402. struct timeval tNow, tLong, tEnd ;
  2403. gettimeofday (&tNow, NULL) ;
  2404. tLong.tv_sec = howLong / 1000000 ;
  2405. tLong.tv_usec = howLong % 1000000 ;
  2406. timeradd (&tNow, &tLong, &tEnd) ;
  2407. while (timercmp (&tNow, &tEnd, <))
  2408. gettimeofday (&tNow, NULL) ;
  2409. }
  2410. void delayMicroseconds (unsigned int howLong)
  2411. {
  2412. struct timespec sleeper ;
  2413. unsigned int uSecs = howLong % 1000000 ;
  2414. unsigned int wSecs = howLong / 1000000 ;
  2415. /**/ if (howLong == 0)
  2416. return ;
  2417. else if (howLong < 100)
  2418. delayMicrosecondsHard (howLong) ;
  2419. else
  2420. {
  2421. sleeper.tv_sec = wSecs ;
  2422. sleeper.tv_nsec = (long)(uSecs * 1000L) ;
  2423. nanosleep (&sleeper, NULL) ;
  2424. }
  2425. }
  2426. /*
  2427. * millis:
  2428. * Return a number of milliseconds as an unsigned int.
  2429. * Wraps at 49 days.
  2430. *********************************************************************************
  2431. */
  2432. unsigned int millis (void)
  2433. {
  2434. uint64_t now ;
  2435. #ifdef OLD_WAY
  2436. struct timeval tv ;
  2437. gettimeofday (&tv, NULL) ;
  2438. now = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
  2439. #else
  2440. struct timespec ts ;
  2441. clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
  2442. now = (uint64_t)ts.tv_sec * (uint64_t)1000 + (uint64_t)(ts.tv_nsec / 1000000L) ;
  2443. #endif
  2444. return (uint32_t)(now - epochMilli) ;
  2445. }
  2446. /*
  2447. * micros:
  2448. * Return a number of microseconds as an unsigned int.
  2449. * Wraps after 71 minutes.
  2450. *********************************************************************************
  2451. */
  2452. unsigned int micros (void)
  2453. {
  2454. uint64_t now ;
  2455. #ifdef OLD_WAY
  2456. struct timeval tv ;
  2457. gettimeofday (&tv, NULL) ;
  2458. now = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
  2459. #else
  2460. struct timespec ts ;
  2461. clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
  2462. now = (uint64_t)ts.tv_sec * (uint64_t)1000000 + (uint64_t)(ts.tv_nsec / 1000) ;
  2463. #endif
  2464. return (uint32_t)(now - epochMicro) ;
  2465. }
  2466. unsigned long long piMicros64(void) {
  2467. struct timespec ts;
  2468. clock_gettime (CLOCK_MONOTONIC_RAW, &ts) ;
  2469. uint64_t now = (uint64_t)ts.tv_sec * (uint64_t)1000000 + (uint64_t)(ts.tv_nsec / 1000) ;
  2470. return (now - epochMicro) ;
  2471. }
  2472. /*
  2473. * wiringPiVersion:
  2474. * Return our current version number
  2475. *********************************************************************************
  2476. */
  2477. void wiringPiVersion (int *major, int *minor)
  2478. {
  2479. *major = VERSION_MAJOR ;
  2480. *minor = VERSION_MINOR ;
  2481. }
  2482. int wiringPiUserLevelAccess(void)
  2483. {
  2484. struct stat statBuf ;
  2485. const char* gpiomemModule = gpiomem_BCM;
  2486. piBoard();
  2487. if (PI_MODEL_5 == RaspberryPiModel) {
  2488. gpiomemModule = gpiomem_RP1;
  2489. }
  2490. return stat(gpiomemModule, &statBuf) == 0 ? 1 : 0;
  2491. }
  2492. int wiringPiGlobalMemoryAccess(void)
  2493. {
  2494. const char* gpiomemGlobal;
  2495. int fd=-1;
  2496. unsigned int MMAP_size;
  2497. unsigned int BaseAddr, PWMAddr;
  2498. piBoard();
  2499. if (PI_MODEL_5 == RaspberryPiModel) {
  2500. gpiomemGlobal = pciemem_RP1;
  2501. MMAP_size = pciemem_RP1_Size;
  2502. BaseAddr = 0x00000000;
  2503. PWMAddr = 0x00000000; //not supported so far
  2504. } else {
  2505. gpiomemGlobal = gpiomem_global;
  2506. MMAP_size = BLOCK_SIZE;
  2507. BaseAddr = piGpioBase + 0x00200000 ;
  2508. PWMAddr = piGpioBase + 0x0020C000 ;
  2509. }
  2510. if ((fd = open (gpiomemGlobal, O_RDWR | O_SYNC | O_CLOEXEC)) >0) {
  2511. int returnvalue = 1; // OK
  2512. uint32_t * lgpio = (uint32_t *)mmap(0, MMAP_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, BaseAddr) ;
  2513. if (lgpio == MAP_FAILED) {
  2514. returnvalue = 0;
  2515. if (wiringPiDebug)
  2516. fprintf(stderr,"wiringPiGlobalMemoryAccess: mmap (GPIO 0x%X,0x%X) failed: %s\n", BaseAddr, MMAP_size, strerror (errno)) ;
  2517. } else {
  2518. munmap(lgpio, MMAP_size);
  2519. if (PI_MODEL_5 == RaspberryPiModel) {
  2520. returnvalue = 2; // GPIO & PWM accessible (same area, nothing to mmap)
  2521. } else {
  2522. //check PWM area
  2523. uint32_t* lpwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, PWMAddr) ;
  2524. if (lpwm == MAP_FAILED) {
  2525. returnvalue = 1; // only GPIO accessible
  2526. if (wiringPiDebug)
  2527. fprintf(stderr,"wiringPiGlobalMemoryAccess: mmap (PWM 0x%X,0x%X) failed: %s\n", PWMAddr, MMAP_size, strerror (errno)) ;
  2528. } else {
  2529. returnvalue = 2; // GPIO & PWM accessible
  2530. munmap(lpwm, BLOCK_SIZE);
  2531. }
  2532. }
  2533. }
  2534. close(fd);
  2535. return returnvalue;
  2536. }
  2537. return 0; // Failed!
  2538. }
  2539. /*
  2540. * wiringPiSetup:
  2541. * Must be called once at the start of your program execution.
  2542. *
  2543. * Default setup: Initialises the system into wiringPi Pin mode and uses the
  2544. * memory mapped hardware directly.
  2545. *
  2546. * Changed now to revert to "gpio" mode if we're running on a Compute Module.
  2547. *********************************************************************************
  2548. */
  2549. int wiringPiSetup (void)
  2550. {
  2551. int fd ;
  2552. int model, rev, mem, maker, overVolted ;
  2553. if (wiringPiSetuped)
  2554. return 0 ;
  2555. wiringPiSetuped = TRUE ;
  2556. if (getenv (ENV_DEBUG) != NULL)
  2557. wiringPiDebug = TRUE ;
  2558. if (getenv (ENV_CODES) != NULL)
  2559. wiringPiReturnCodes = TRUE ;
  2560. if (wiringPiDebug)
  2561. printf ("wiringPi: wiringPiSetup called\n") ;
  2562. // Get the board ID information. We're not really using the information here,
  2563. // but it will give us information like the GPIO layout scheme (2 variants
  2564. // on the older 26-pin Pi's) and the GPIO peripheral base address.
  2565. // and if we're running on a compute module, then wiringPi pin numbers
  2566. // don't really mean anything, so force native BCM mode anyway.
  2567. piBoardId (&model, &rev, &mem, &maker, &overVolted) ;
  2568. if ((model == PI_MODEL_CM) ||
  2569. (model == PI_MODEL_CM3) ||
  2570. (model == PI_MODEL_CM3P))
  2571. wiringPiMode = WPI_MODE_GPIO ;
  2572. else
  2573. wiringPiMode = WPI_MODE_PINS ;
  2574. /**/ if (piGpioLayout () == GPIO_LAYOUT_PI1_REV1) // A, B, Rev 1, 1.1
  2575. {
  2576. pinToGpio = pinToGpioR1 ;
  2577. physToGpio = physToGpioR1 ;
  2578. }
  2579. else // A2, B2, A+, B+, CM, Pi2, Pi3, Zero, Zero W, Zero 2 W
  2580. {
  2581. pinToGpio = pinToGpioR2 ;
  2582. physToGpio = physToGpioR2 ;
  2583. }
  2584. // Open the master /dev/ memory control device
  2585. // Device strategy: December 2016:
  2586. // Try /dev/mem. If that fails, then
  2587. // try /dev/gpiomem. If that fails then game over.
  2588. const char* gpiomemGlobal = gpiomem_global;
  2589. const char* gpiomemModule = gpiomem_BCM;
  2590. if (PI_MODEL_5 == model) {
  2591. gpiomemGlobal = pciemem_RP1;
  2592. gpiomemModule = gpiomem_RP1;
  2593. // PWM alt pins @RP1 - need to be translated to RP1_FSEL with pinModeAlt
  2594. gpioToPwmALT[12] = FSEL_ALT0;
  2595. gpioToPwmALT[13] = FSEL_ALT0;
  2596. gpioToPwmALT[18] = FSEL_ALT3;
  2597. gpioToPwmALT[19] = FSEL_ALT3;
  2598. //PWM0 channel @RP1
  2599. gpioToPwmPort[12] = 0;
  2600. gpioToPwmPort[13] = 1;
  2601. gpioToPwmPort[18] = 2;
  2602. gpioToPwmPort[19] = 3;
  2603. }
  2604. usingGpioMem = FALSE;
  2605. if (gpiomemGlobal==NULL || (fd = open (gpiomemGlobal, O_RDWR | O_SYNC | O_CLOEXEC)) < 0)
  2606. {
  2607. if (wiringPiDebug) {
  2608. printf ("wiringPi: no access to %s try %s\n", gpiomemGlobal, gpiomemModule) ;
  2609. }
  2610. if (gpiomemModule && (fd = open (gpiomemModule, O_RDWR | O_SYNC | O_CLOEXEC) ) >= 0) // We're using gpiomem
  2611. {
  2612. piGpioBase = 0 ;
  2613. usingGpioMem = TRUE ;
  2614. }
  2615. else
  2616. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: Unable to open %s or %s: %s.\n"
  2617. " Aborting your program because if it can not access the GPIO\n"
  2618. " hardware then it most certianly won't work\n"
  2619. " Try running with sudo?\n", gpiomemGlobal, gpiomemModule, strerror (errno)) ;
  2620. }
  2621. if (wiringPiDebug) {
  2622. printf ("wiringPi: access to %s succeded %d\n", usingGpioMem ? gpiomemModule : gpiomemGlobal, fd) ;
  2623. }
  2624. // GPIO:
  2625. if (PI_MODEL_5 != model) {
  2626. //Set the offsets into the memory interface.
  2627. GPIO_PADS = piGpioBase + 0x00100000 ;
  2628. GPIO_CLOCK_ADR = piGpioBase + 0x00101000 ;
  2629. GPIO_BASE = piGpioBase + 0x00200000 ;
  2630. GPIO_TIMER = piGpioBase + 0x0000B000 ;
  2631. GPIO_PWM = piGpioBase + 0x0020C000 ;
  2632. GPIO_RIO = 0x00 ;
  2633. // Map the individual hardware components
  2634. // GPIO:
  2635. base = NULL;
  2636. gpio = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_BASE) ;
  2637. if (gpio == MAP_FAILED)
  2638. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (GPIO) failed: %s\n", strerror (errno)) ;
  2639. // PWM
  2640. pwm = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PWM) ;
  2641. if (pwm == MAP_FAILED)
  2642. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PWM) failed: %s\n", strerror (errno)) ;
  2643. // Clock control (needed for PWM)
  2644. clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_CLOCK_ADR) ;
  2645. if (clk == MAP_FAILED)
  2646. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (CLOCK) failed: %s\n", strerror (errno)) ;
  2647. // The drive pads
  2648. pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
  2649. if (pads == MAP_FAILED)
  2650. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (PADS) failed: %s\n", strerror (errno)) ;
  2651. // The system timer
  2652. timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
  2653. if (timer == MAP_FAILED)
  2654. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap (TIMER) failed: %s\n", strerror (errno)) ;
  2655. // Set the timer to free-running, 1MHz.
  2656. // 0xF9 is 249, the timer divide is base clock / (divide+1)
  2657. // so base clock is 250MHz / 250 = 1MHz.
  2658. *(timer + TIMER_CONTROL) = 0x0000280 ;
  2659. *(timer + TIMER_PRE_DIV) = 0x00000F9 ;
  2660. timerIrqRaw = timer + TIMER_IRQ_RAW ;
  2661. // Export the base addresses for any external software that might need them
  2662. _wiringPiBase = base ;
  2663. _wiringPiGpio = gpio ;
  2664. _wiringPiPwm = pwm ;
  2665. _wiringPiClk = clk ;
  2666. _wiringPiPads = pads ;
  2667. _wiringPiTimer = timer ;
  2668. _wiringPiRio = NULL ;
  2669. } else {
  2670. unsigned int MMAP_size = (usingGpioMem) ? gpiomem_RP1_Size : pciemem_RP1_Size;
  2671. GPIO_PADS = (RP1_PADS0_Addr-RP1_IO0_Addr) ;
  2672. GPIO_CLOCK_ADR = (RP1_CLOCK_Addr-RP1_BASE_Addr);
  2673. GPIO_BASE = (RP1_IO0_Addr-RP1_BASE_Addr) ;
  2674. GPIO_TIMER = 0x00;
  2675. GPIO_PWM = RP1_PWM0_Addr-RP1_BASE_Addr;
  2676. GPIO_RIO = (RP1_SYS_RIO0_Addr-RP1_IO0_Addr) ;
  2677. //map hole RP1 memory block from beginning,
  2678. base = (unsigned int *)mmap(0, MMAP_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x00000000) ;
  2679. if (base == MAP_FAILED)
  2680. return wiringPiFailure (WPI_ALMOST, "wiringPiSetup: mmap failed: %s\n", strerror (errno)) ;
  2681. if (usingGpioMem) {
  2682. gpio = base; // RP1 start adress of map memory for gpio (same as module memory)
  2683. pwm = NULL; // outside of mapped memory, PWM not available from none root
  2684. clk = NULL; // outside of mapped memory, CLK main not available from none root
  2685. } else {
  2686. gpio = &base[GPIO_BASE/4]; // RP1 start adress of map memory for gpio
  2687. pwm = &base[GPIO_PWM/4]; // RP1 start adress of map memory for pwm0
  2688. clk = &base[GPIO_CLOCK_ADR/4]; // RP1 start adress of map memory for clocks_main
  2689. }
  2690. pads = &gpio[GPIO_PADS/4]; // RP1 start adress of map memory for pads
  2691. rio = &gpio[GPIO_RIO/4]; // RP1 start adress of map memory for rio
  2692. GPIO_PADS += GPIO_BASE;
  2693. GPIO_RIO += GPIO_BASE;
  2694. // Export the base addresses for any external software that might need them
  2695. _wiringPiBase = base ;
  2696. _wiringPiGpio = gpio ;
  2697. _wiringPiPwm = pwm ;
  2698. _wiringPiClk = clk ;
  2699. _wiringPiPads = pads ;
  2700. _wiringPiTimer = NULL ;
  2701. _wiringPiRio = rio ;
  2702. }
  2703. if (wiringPiDebug) {
  2704. printf ("wiringPi: memory map gpio 0x%x %s\n", GPIO_BASE , _wiringPiGpio ? "valid" : "invalid");
  2705. printf ("wiringPi: memory map pads 0x%x %s\n", GPIO_PADS , _wiringPiPads ? "valid" : "invalid");
  2706. printf ("wiringPi: memory map rio 0x%x %s\n", GPIO_RIO , _wiringPiRio ? "valid" : "invalid");
  2707. printf ("wiringPi: memory map pwm0 0x%x %s\n", GPIO_PWM , _wiringPiPwm ? "valid" : "invalid");
  2708. printf ("wiringPi: memory map clocks 0x%x %s\n", GPIO_CLOCK_ADR, _wiringPiClk ? "valid" : "invalid");
  2709. printf ("wiringPi: memory map timer 0x%x %s\n", GPIO_TIMER ,_wiringPiTimer ? "valid" : "invalid");
  2710. }
  2711. initialiseEpoch () ;
  2712. return 0 ;
  2713. }
  2714. /*
  2715. * wiringPiSetupGpio:
  2716. * Must be called once at the start of your program execution.
  2717. *
  2718. * GPIO setup: Initialises the system into GPIO Pin mode and uses the
  2719. * memory mapped hardware directly.
  2720. *********************************************************************************
  2721. */
  2722. int wiringPiSetupGpio (void)
  2723. {
  2724. (void)wiringPiSetup () ;
  2725. if (wiringPiDebug)
  2726. printf ("wiringPi: wiringPiSetupGpio called\n") ;
  2727. wiringPiMode = WPI_MODE_GPIO ;
  2728. return 0 ;
  2729. }
  2730. /*
  2731. * wiringPiSetupPhys:
  2732. * Must be called once at the start of your program execution.
  2733. *
  2734. * Phys setup: Initialises the system into Physical Pin mode and uses the
  2735. * memory mapped hardware directly.
  2736. *********************************************************************************
  2737. */
  2738. int wiringPiSetupPhys (void)
  2739. {
  2740. (void)wiringPiSetup () ;
  2741. if (wiringPiDebug)
  2742. printf ("wiringPi: wiringPiSetupPhys called\n") ;
  2743. wiringPiMode = WPI_MODE_PHYS ;
  2744. return 0 ;
  2745. }
  2746. int wiringPiSetupPinType (enum WPIPinType pinType) {
  2747. if (wiringPiDebug)
  2748. printf ("wiringPi: wiringPiSetupPinType(%d) called\n", (int) pinType) ;
  2749. switch (pinType) {
  2750. case WPI_PIN_BCM: return wiringPiSetupGpio();
  2751. case WPI_PIN_WPI: return wiringPiSetup();
  2752. case WPI_PIN_PHYS: return wiringPiSetupPhys();
  2753. default: return -1;
  2754. }
  2755. }
  2756. int wiringPiSetupGpioDevice (enum WPIPinType pinType) {
  2757. if (wiringPiSetuped)
  2758. return 0 ;
  2759. if (wiringPiDebug) {
  2760. printf ("wiringPi: wiringPiSetupGpioDevice(%d) called\n", (int)pinType) ;
  2761. }
  2762. if (getenv (ENV_DEBUG) != NULL)
  2763. wiringPiDebug = TRUE ;
  2764. if (getenv (ENV_CODES) != NULL)
  2765. wiringPiReturnCodes = TRUE ;
  2766. if (wiringPiGpioDeviceGetFd()<0) {
  2767. return -1;
  2768. }
  2769. wiringPiSetuped = TRUE ;
  2770. if (piGpioLayout () == GPIO_LAYOUT_PI1_REV1){
  2771. pinToGpio = pinToGpioR1 ;
  2772. physToGpio = physToGpioR1 ;
  2773. } else {
  2774. pinToGpio = pinToGpioR2 ;
  2775. physToGpio = physToGpioR2 ;
  2776. }
  2777. initialiseEpoch () ;
  2778. switch (pinType) {
  2779. case WPI_PIN_BCM:
  2780. wiringPiMode = WPI_MODE_GPIO_DEVICE_BCM;
  2781. break;
  2782. case WPI_PIN_WPI:
  2783. wiringPiMode = WPI_MODE_GPIO_DEVICE_WPI;
  2784. break;
  2785. case WPI_PIN_PHYS:
  2786. wiringPiMode = WPI_MODE_GPIO_DEVICE_PHYS;
  2787. break;
  2788. default:
  2789. wiringPiSetuped = FALSE;
  2790. return -1;
  2791. }
  2792. return 0 ;
  2793. }
  2794. /*
  2795. * wiringPiSetupSys:
  2796. * GPIO Sysfs Interface for Userspace is deprecated
  2797. * https://www.kernel.org/doc/html/v5.5/admin-guide/gpio/sysfs.html
  2798. *
  2799. * Switched to new GPIO driver Interface in version 3.3
  2800. */
  2801. int wiringPiSetupSys (void)
  2802. {
  2803. if (wiringPiSetuped)
  2804. return 0 ;
  2805. if (wiringPiDebug)
  2806. printf ("wiringPi: wiringPiSetupSys called\n") ;
  2807. return wiringPiSetupGpioDevice(WPI_PIN_BCM);
  2808. }