Wednesday, February 21, 2018

PiGPIOPin - when you want to use pin numbers and not BCM on the Raspberry Pi in Python

A while back I was doing some bare Arduino compatible boards using the ATMega328 chip. From this I saw that Arduino did not map the pins on the IC to the same numbers on the Arduino.  They used a simple order on the Arduino board and the Arduino ID so it was easy to find the right pin for wiring and also for your code.

Only problem is when you use the chip with the bootloader the mappings are different to the pin number so you need a lookup tool to know when you want to use Arduino Pin 13 that it's ATMega Pin 19.
After a while this became a bit annoying so I put together an .h file with a bunch of constants that got around this.

On the Raspberry Pi there is a similar situation.  The default numbering mechanism used is the BCM numbering which is great if you're operating at chip level, but at a board level it means things like:

BCM GPIO 5 is board pin 29

I still have to count pins to get to board pin 29, so having to also know it's then GPIO 5 in my code can sometimes be a bit annoying.

The original RPi.GPIO library allows you to choose BCM or Board numbers

 import RPi.GPIO as GPIO  


Giving the user the choice.

With the fantastic GPIOZero BCM numbering is enforced and there is no option to use board numbering.
GPIOZero is a great library and makes controlling motors, working with MCP3008 (analog input) and distance sensors a lot easier.

For those who want to use board pin numbers and want to take advantage of GPIOZero the use of the BCM numbering can be annoying.

To make it easier I decided to do a similar lookup table like I did for the Arduino.
Mapping Pin number variables to BCM numbers.
The code and an example is on GitHub.

It's straight forward to use.

Have in the same folder as your code or in the python path.

Put the following line at the top

from PiGPIOPin import *

Then instead of using something like

red = LED(17) # 17 is the BCM number that is at board pin 11


red = LED(PIN11) 

Each BCM number is mapped a PIN* variable.

The rest of the code then works as normal.

Using this gives the option back to use board pin numbers and not BCM numbers.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.