Lightning Snacks

A Vending Machine using the Bitcoin Lightning Network on a Full Node Raspberry Pi

Problem Definition

Most vending snack machines are coin-operated. This leads to many drawbacks such as incorrect/no change, some coins are not recognized, management of coins by owner and no coins in your wallet.

Sometimes my colleagues ask me for some coins, and in return they give banknotes or pay me via Revolut. Why should we all go through this hassle if when can do online transactions? We can use Visa/Mastercard scanners attached with vending machines and people can buy snacks easily. Well, the problem is that for every authorized transaction, the bank takes a commission. Is it worth for the merchant to pay a commission for a cheap snack item? I don’t think so. Apart from that, this technique is not recommended because there might be hackers that can attach card sniffers to the vending machine intending to hijack your card. So, what’s the solution?

The Solution

Nowadays everyone owns a smartphone. With Bitcoin, you can have your own non-custodial wallet on your phone. You can do global transactions on decentralized platforms without making use of third-party APIs (banks) to verify transactions. Can we apply this technology to our vending machine? We can but it won’t be ideal. The problem lies in the transaction confirmation time and the transaction fees.

One confirmation (1 block) takes about 10 minutes and we usually assume that a transaction is fully confirmed when it is 6 blocks deep. This means that a full confirmation takes about 1 hour (10 minutes * 6 blocks). This is very fast when compared to traditional systems, but it won’t be ideal for our vending machine system. Imagine our client waiting 1 hour to buy some candy. Since snacks are not expensive, we can assume that one confirmation (1 block deep) is enough, but our client must still wait 10 minutes for the transaction to be processed.

The other problem relies in the transaction fees. Transaction fees are included with every Bitcoin transaction in order to have transactions processed by a miner and confirmed by the Bitcoin network. The space available for transactions in a block is currently limited to 1 MB. This means that to get your transaction processed quickly you must outbid other users. Therefore, it can get expensive to buy some snacks.

Bitcoin Cash (another cryptocurrency – fork of Bitcoin) simply solves these problems by increasing the block size and disabling the ‘replace by higher fee’ feature. Therefore, a transaction can be created with a lower transaction fee and once created, we can safely assume that the transaction is going to be placed in the next block. This might lead to other problems, but I don’t want to debate Bitcoin Cash vs Bitcoin in this article.

The Bitcoin Lightning Network (Layer 2 Protocol on Bitcoin) is the ideal solution for our vending snack machine. It is a decentralized network powered by smart contracts that enables instant payments with very low-cost transaction fees across participants. Lightning enables one to send very small funds in Bitcoin without custodial risk. Everyone can be part of the network by hosting and opening a channel with a node. When opening a channel, participants must commit an amount which is stored on the blockchain. Transactions then can be passed through multiple channels in a mesh network of payment channels. These transactions are not stored on the public blockchain and therefore the base layer fees are avoided. I must admit that it is a bit complicated to work with but once you understand what is happening, you will appreciate the principles behind this system.


Building the Prototype

For this project one used the Raspberry Pi 3 B+ with an external hard disk storing the entire Bitcoin testnet blockchain. The Bitcoin Lightning Network was installed using the Raspibolt tutorial and Python was used to develop the whole system. That is creating the GUI using a game engine called PyGame, interfacing with the LND network, connecting with the Coinbase API for price conversion, making invoices into QRCodes, recursively checking for payments and eventually turning the motors using GPIO commands for successful payments. The Eclair Mobile Testnet app was installed on my phone to test for the client perspective.


Description Link
3D printed some of the objects found in this project.


Official Raspberry Pi 7″ Touchscreen Display
Bitcoin Lighting Network on Raspberry Pi (RaspiBolt)
Python gRPC client for the Lightning Network Daemon
LND gRPC API Reference
Conversion from  Euro to Bitcoin
Python Game Engine for User Interface – PyGame
Raspberry pi motor library
NEMA 17 Motor
Shaft Holder Extension Rod
QR Code Generator
Android Eclair Mobile Testnet



This prototype clearly demonstrates that the Lightning Network is a potential solution for the problems mentioned before. One managed to buy snacks instantly with very low transaction fees. On average, every transaction fee was about 4 satoshis which is equivalent to 0.0002557 EUR (at the time of writing 1 BTC is equivalent to 6385 Euros). One problem that I constantly encountered was the inbound capacity limit which is described clearly here: Developers are working on this using a solution called Lightning Loops: In the future I want to test this prototype on the Bitcoin Mainnet using a 4GB Raspberry Pi 4 and experiment with the looping solution.

Thanks for reading 🙂

Photo booth – Raspberry Pi

Photo Booth using the Raspberry Pi and Pi Camera. Designed for 7″ touch screen. Just run  python code in Raspbian.

from __future__ import print_function
import pygame
import time
from picamera import PiCamera
import sys
from PIL import Image

import os


win = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
camera = PiCamera()
camera.resolution = (800,800)
#camera.color_effects = (128,128) #turn camera to black and white

class button():
    def __init__(self, color, x,y,width,height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self,win,outline=None):
        #Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline,(self.x-2,self.y-2,self.width+4,self.height+4),0)

        pygame.draw.rect(win, self.color,(self.x,self.y,self.width,self.height),0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 60)
            text = font.render(self.text, 1, (0,0,0))
            win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

    def isOver(self, pos):
        #Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0]  self.y and pos[1] < self.y + self.height:
                return True

        return False

def redrawWindow():

def counterWindow():
        counterLabel.text = str(counter)
        counterLabel.text = "Smile"

def loadimage():
    global imagename
    img = pygame.image.load(imagename)
    img = pygame.transform.scale(img,(480,480))

def takePhoto():
    global showImage
    global counterActive
    global counter
    global imagename
    print("Take Photo")
    for x in range(4):

    files = [

    result ="RGB", (800, 800))

    for index, file in enumerate(files):
      path = os.path.expanduser(file)
      img =
      img.thumbnail((400, 400), Image.ANTIALIAS)
      x = index // 2 * 400
      y = index % 2 * 400
      w, h = img.size
      print('pos {0},{1} size {2},{3}'.format(x, y, w, h))
      result.paste(img, (x, y, x + w, y + h))

    imagename = str(round(time.time() * 1000)) +'.jpg'
    showImage = True
    counterActive = False
    counter = 6

def resetStatus():
    global counter
    global startProcess
    global counterActive
    global imageCounter

    counter = 6
    startProcess = True
    counterActive = False
    imageCounter = 0

run = True
counter = 6
startProcess = True
counterActive = False
showImage = False
greenButton = button((0,255,0),280,200,250,100,'Take Photos')
counterLabel = button((100,255,255),300,200,250,100,'0')
imageCounter = 0
imagename =""

while run:
    if(startProcess == True):
    elif(counterActive == True):
        counter = counter-1
    elif(showImage == True):
        imageCounter = imageCounter +1
        if(imageCounter == 15):


    if(counterActive == False):
        for event in pygame.event.get():
            pos = pygame.mouse.get_pos()

            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if greenButton.isOver(pos):
                    print("Clicked the button")
                    counterActive = True
                    startProcess = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False

    if(counter == 0):

Flask Server with GPIOs

Let’s say that you have a running Flask server and you want your user to control the state (on/off) of an LED via the GPIO. The following technique shows how to connect Flask server with a separate GPIO script using PID.

Download the whole project

Run the following two scripts at the same time using the terminal:

from flask import *
import os
import signal

app = Flask(__name__)

#create a route path for index page
def index():
    return render_template("index.html")

#create a route path for about page
def about():

    if 'name' in session: #if session 'name' exists
        print(session['name']) #print what's inside session[name]

        session.pop('name',None) #after printing, delete session name

    return render_template("aboutus.html") #render the html template aboutus

#/students accepts a get and post requests
def student():
    if(request.method == 'POST'): #if user fills a form
        studentName = request.form['studentname']
        if(studentName == "jimmy"):
            session["name"] = studentName #create session, name it 'name' and fill with studentName
            return redirect(url_for("about")) #redirect to about page
            return render_template("student.html") #render student template

        return render_template("student.html")#render student template

#routes with paramaters
def led(param=None):
    if(param == "on"): #if paramater is /led/on
        #read process id from text file generated by
        processId = int( #load the process id

        fh.write("1") #save 1 in text file. 1 means LED ON. 0 means LED Off

        #send signal to process id
        os.kill(processId, signal.SIGUSR1)
        return "LED ON"
    elif(param =="off"): # if paramater is /led/off
        #read process id from text file
        processId = int(


        #send signal to process id (ledscript)
        os.kill(processId, signal.SIGUSR1)
        return "LED OFF"
        return "LED MAIN PAGE"

if __name__ == "__main__":
    app.secret_key = 'asdfd!45sdf' #create secret key to secure sessions, host = "")

import RPi.GPIO as GPIO
import time
import traceback
import os
import signal

def Main():
        #when scripts runs create processid.txt
        fh.write(str(os.getpid())) #get current process id and store in file



        GPIO.setup(4, GPIO.OUT, initial = GPIO.LOW) #setup GPIO4 to low

        def handUSR1(signum,frame): #this function is automatically triggered from flask
            led = int(

            if(led == 0): #if 0 is found in text file
                print("LED OFF") #turn off led
                print("LED ON") #if not 0 (1) is found in text file
                GPIO.output(4,GPIO.HIGH) #turn on led

        signal.signal(signal.SIGUSR1,handUSR1) #callback function for SIGUSR1 signal (from flask when kill command is given)


    except Exception as ex:
        GPIO.cleanup() #this ensures a clean exit


Control a separate running script from a Web Server (python)- RPi

Let’s say that you have a running Flask server and you want your user to control the state (on/off) of a motion sensor via the GPIO. The most complex way is to create a multi-threading script which handles the server and GPIO code.

Another approach is to separate the server script from the GPIO script. Thus having two layers of scripts. This has the advantage to debug in isolation. For this technique one has to use Unix Signals which can be used to send signals from one process to another.

When you execute a script on your UNIX system, the system creates a process id (pid) which is different every time. A signal is a software interrupt which notifies a process with a significant event or request.

The following table gives a list of the most common signals:

SIGHUP 1 Linux sends a process this signal when it becomes disconnected from a terminal.
SIGINT 2 Linux sends a process this signal when the user tries to end it by

pressing CTRL+C.

SIGILL 4 Linux sends a process this signal when it attempts to execute an illegal instruction.
SIGABRT 6 Linux sends a process this signal to the process when the process calls the ‘abort ()’ function
SIGFPE 8 Linux sends a process this signal when it has executed an invalid floating-point math instruction
SIGKILL 9 Linux sends a process this signal to end it immediately
SIGUSR1 10 User programs can send this signal to other process
SIGUSR2 12 User programs can send this signal to other process
SIGSEGV 11 Linux sends a process this signal when the program has attempted an invalid memory access
SIGPIPE 13 Linux sends a process this signal when the program has attempted to access a broken data stream, such as a socket connection that has been already closed
SIGALRM 14 A process can receive this signal from the Linux using the function alarm (), after a time period mentioned in its argument.
SIGTERM 15 Linux sends a process this signal requesting it to terminate
SIGCHLD 17 Linux sends a process this signal when a child process exits
SIGXCPU 24 Linux sends a process this signal when it exceeds the limit of

CPU time that it can consume.

SIGVTALRM 26 A process can receive this signal from the Linux using the function setitimer (), after a time period mentioned in its argument.

We are interested in SIGUSR1 and SIGUSR2 which can be used to send user signals.

Step 1:

First create the server layer ( Documentation about Flask server can be found here.

from flask import *
import os
import signal

app = Flask(__name__)

def index():
    return render_template('index.html')

def process1():
    #read process id from text file
    processId = int(

    #send signal to process id
    os.kill(processId, signal.SIGUSR1)

    return render_template('trigger1.html')

def process2():
    #read process id from text file
    processId = int(

    #send signal to process id
    os.kill(processId, signal.SIGUSR2)

    return render_template('trigger2.html')

if __name__ == '__main__':,host='')

Step 2:

Create the script (you can modify this to control the GPIOs)

import os
import signal
import time

fh.write(str(os.getpid())) #get current process id and store in file

def handUSR1(signum,frame):

def handUSR2(signum,frame):

signal.signal(signal.SIGUSR1,handUSR1) #callback function for SIGUSR1 signal
signal.signal(signal.SIGUSR2,handUSR2) #callback function for SIGUSR2 signal

    print("Waiting for signal")

Step 3: Run Server


Step 4: Run


Step 5: 

In the browser, click Trigger 1 and Trigger 2 hyperlink buttons. Notice that outputs ‘triggered 10′ and ‘triggered 12′. This means that both signals were sent and received correctly.


Link to project:

PIXEL(Raspbian)-Virtual Box-Persistence Drive

Please note that this is not officially approved by the PI team but the MagPi magazine offers a similar tutorial using a pendrive.

Step 1

Download the Pixel (Jessie Raspbian) image file:

Step 2:

Open Virtual Box, press new and create the following settings:


Press Create and enter the following settings


Press Start



Step 3:

Browse to the downloaded ISO file and press Start


Pixel is loaded


Step 4:

To test persistence, create a new folder on your desktop and restart your OS.



Once your OS is restarted, you will notice that the folder you created is lost. This is because there is no persistence drive present.


Step 5 (to create persistence drive):

Open terminal window and enter sudo apt install gparted


When installation is finished, enter sudo gparted


Click on Device > Create Partition Table and press Apply


Right Click on the unallocated partition and press New


Enter label name persistence with the following default settings and press Add


Press the green very good sign and press Apply to any warning messages


Press Close and close everything


Now we are going to copy  the whole operating system from the virtual optical drive to
the hard drive.

Open the terminal window and enter sudo dd if=/dev/sr0 of=/dev/sda bs=1M


Close the virtual machine (shutdown the OS)

Step 6:

Create a new Virtual Machine with the following settings. It is very important that you use your previously created virtual hard disk file. Do no create a new virtual hard disk.


Step 7:

Start your new machine and create a new python script to test persistence. I saved my file in the desktop. Restart your OS.


Step 8:

Test file is still there. Persistence worked 🙂



Maltese Online Radio – Raspberry Pi

So here’s the story:

  1. I woke up to Mum complaining that she can’t listen any longer to the radio from our kitchen due to noise interferance
  2. My brother suggested of buying an online radio
  3. I said “No..I can build one using the Raspberry Pi 2 and Music Player Daemon”
  4. I expected some excitement from their end but they just replied “ok”. Sad.
  5. Using the terminal I installed the player:
sudo apt-get install mpd mpc
  1. Changed the audio output to the headphone jack:
  2. In the terminal I added some local radio stations using the command mpc add. I used Chrome’s Developer Tools(f12) to get these links:
Classic FM  mpc add
Radio Malta 1 mpc add
One Radio mpc add
Radio Malta 2 mpc add
Magic Malta mpc add
Radio 101 mpc add
Radju Marija mpc add
bay radio mpc add
bay easy mpc add
bay retro mpc add
Campus FM mpc add mms://
RTK FM mpc add
Vibe FM mpc add 
Bkara FM mpc add 
  1. From Ebay, I bought: 16 x 2 LCD Keypad Kit + DIY Transparent Acrylic Case For Raspberry Pi. I selected this product because it comes with 5 buttons and a case.
  1. When the product arrived, I attached the LCD on the Pi. No soldering is required. It’s very easy. Just place the LCD board in the respective GPIOs.
  2. Followed this tutorial to enable I2C (with Raspi Config) –
  3. Continued the setup :×2-character-lcd-plus-keypad-for-raspberry-pi/usage
  4. Installed the following library (can be done in step 10):
  5. Programmed the following code (Buttons Up&Down = Volume Control; Buttons Left/Right = Skip radio; Button Select – Turn off Pi) :
# Example using a character LCD plate.
import time
import Adafruit_CharLCD as LCD
import traceback
import subprocess
import os.path
import os

# Initialize the LCD using the pins
lcd = LCD.Adafruit_CharLCDPlate()
# create some custom characters
lcd.create_char(1, [2, 3, 2, 2, 14, 30, 12, 0])
lcd.create_char(2, [0, 1, 3, 22, 28, 8, 0, 0])
lcd.create_char(3, [0, 14, 21, 23, 17, 14, 0, 0])
lcd.create_char(4, [31, 17, 10, 4, 10, 17, 31, 0])
lcd.create_char(5, [8, 12, 10, 9, 10, 12, 8, 0])
lcd.create_char(6, [2, 6, 10, 18, 10, 6, 2, 0])
lcd.create_char(7, [31, 17, 21, 21, 21, 21, 17, 31])

#turn on green light
lcd.set_color(0.0, 0.0, 1.0)
lcd.message("connecting: \n")

message = ""

def isConnected():
    global lcd
    while True: #keep repeating until internet connection is found
            ip = subprocess.check_output("hostname -I",shell=True)
            ip = ip[:3]
            if ip != "192":
                counter = 0
                while True:
                    print 'trying to connect to internet'
                    lcd.message("connecting to\n internet")
                    remote_server = ""
                    status =['ping','-c','1',remote_server])#test connection with google
                    if(status == 0):
                        counter +=1

                    if(counter > 3):

def startPlaying():
    global lcd
    lcd.clear()"mpc stop ",shell=True)"mpc play ",shell=True) #start player

def updateCurrentStation():
    global message
    message = subprocess.check_output('mpc current',shell=True)
    message = updateStationName(message.strip())
    if(len(message) > 15):
        message = message[:16] + '\n' + message[16:30]

def updateStationName(message): #this function updates those station name that are not returning a proper name
    if(message == ""):
        message = "101"
    elif(message == ""):
        message = "One Radio"
    elif(message == ""):
        message = "Bkara FM"
    elif(message == ""):
        message = "RTK"
    elif(message == ""):
        message = "Classic FM"
    return message

def checkStatus():
    status = subprocess.check_output('mpc status',shell=True)
    if(status[0:6] == 'volume'): #empty status starts with text volume

def Main():

    global lcd
    global message
    cache_oldmessage = ""


        # Make list of button value, text, and backlight color.
        buttons = ( (LCD.SELECT, 'Select', (1,1,1)),
                    (LCD.LEFT,   'Left'  , (1,0,0)),
                    (LCD.UP,     'Up'    , (0,0,1)),
                    (LCD.DOWN,   'Down'  , (0,1,0)),
                    (LCD.RIGHT,  'Right' , (1,0,1)) )

        while True:

            # Loop through each button and check if it is pressed.
            for button in buttons:
                if lcd.is_pressed(button[0]):

                    if(button[0] == LCD.LEFT):
                        print("left button")                       

                        lcd.message("connecting:\n ")
              "mpc next ",shell=True)

                    elif(button[0] == LCD.RIGHT):
                        print("right button")

                        lcd.message("connecting: \n")
              "mpc prev ",shell=True)

                    elif(button[0] == LCD.UP):
              "mpc volume +5" ,shell=True)
                        print("volume increased")

                    elif(button[0] == LCD.DOWN):
              "mpc volume -5" ,shell=True)
                        print("volume decreased")

                    elif(button[0] == LCD.SELECT):
                        lcd.set_color(0.0, 1.0, 1.0)
                        lcd.set_color(0.0, 0.0, 0.0)

              ['poweroff -f'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                        os.system('shutdown now -h')

                    time.sleep(0.75) #button click delay

            if(cache_oldmessage != message):
                cache_oldmessage = message

    except Exception as ex:
        lcd.set_color(1.0, 0.0, 0.0)


  1. Followed the following tutorial to launch the python script automatically on start-up:
  2. If you are having mpc connection timeouts with newest raspbian versions, just follow the fix by user csrlima in the following forum:
  3. Tested the radio. Like a boss 🙂


Raspberry Pi GPIO Emulator

This Raspberry Pi emulator simulates some of the functions used in the RPi.GPIO library (using python). The intention of this library is educational.



The easiest way is to download the zip file and extract the files in the same working environment of your script. To use the emulator just type the following at the beginning of your script.

from EmulatorGUI import GPIO


This library simulates the following functions which are used in the RPi.GPIO library.

  • GPIO.setmode()
  • GPIO.setwarnings()
  • GPIO.setup()
  • GPIO.input()
  • GPIO.output()

Test Example

from EmulatorGUI import GPIO
#import RPi.GPIO as GPIO
import time
import traceback

def Main():


        GPIO.setup(4, GPIO.OUT)
        GPIO.setup(17, GPIO.OUT, initial = GPIO.LOW)
        GPIO.setup(18, GPIO.OUT, initial = GPIO.LOW)
        GPIO.setup(21, GPIO.OUT, initial = GPIO.LOW)
        GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        GPIO.setup(15, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
        GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
        GPIO.setup(26, GPIO.IN)

            if (GPIO.input(23) == False):

            if (GPIO.input(15) == True):

            if (GPIO.input(24) == True):

            if (GPIO.input(26) == True):

    except Exception as ex:
        GPIO.cleanup() #this ensures a clean exit



Click here to download