How to mock Raspberry pins

June 29, 2017
Arduino Car Tuning

Developing apps, that control Raspberry Pi’s GPIO pins is pretty straightforward task, but it’s not confortable doing it directly on it. In the past day I’ve been searching for good ways to mock the pins on my local machine and test the app, without pushing the code to the device on every save, but couldn’t find any reliable solution. Since I feel most comfortable using Javascript (Node) for my projects, I’m usually using the pigpio’s node wrapper, so I decided to build a really simple mocking library, that copies all methods from the original library, but instead prints the output to the console.

The repository is located at https://github.com/deepsyx/pigpio-mock

How do I use it?

First, you need to install it to your project with

npm install --save-dev pigpio-mock

then replace the const pigpio = require('pigpio') in your code with:

const pigpio = process.env.NODE_ENV !== "production" ? 
    require("pigpio-mock") : 
    require("pigpio");

and you’re ready to go. Just make sure to start the node on your Pi in production mode (having NODE_ENV=production).

Example

By executing the following code(which increases the brightness of a LED diode every 0.5 seconds):

const Gpio = require("pigpio-mock").Gpio;
const led = new Gpio(13, { mode: Gpio.OUTPUT });
let dutyCycle = 0;

setInterval(function() {
    led.pwmWrite(dutyCycle);

    dutyCycle += 50;
    if (dutyCycle > 255) {
        dutyCycle = 0;
    }
}, 500);

the expected output to the console should be:

[GPIO 13 / constructor] Initializing...
[GPIO 13 / constructor] Setting mode = 1
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 0
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 50
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 100
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 150
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 200
[GPIO 13 / pwmWrite-analogWrite] Setting dutyCycle = 250
.......

Last words

The library itself is really simple, but it should do the job for most cases. If you’re interested in getting Raspberry Pi and start doing magic, I recommend geting Raspberry Pi 3 Kit with Clear Case and 2.5A Power Supply.

Read more

Home automation with Raspberry Pi, Node and React
Bypassing legacy capchas combined with email confirmation

Hey! I just started blogging and I'll post regularly about tech. If you enjoy my posts, leave your email below and I'll try to send you a newsletter once a month. I won't spam you :)