IOTA Hardware Integration Tutorial: Control a Relay with IOTA Balance on Raspberry Pi

·

In this hands-on tutorial, you’ll learn how to build a real-world IoT application using IOTA, a blockchain-like distributed ledger technology designed for the Internet of Things (IoT). We’ll walk through integrating IOTA with hardware—specifically, a Raspberry Pi and a relay module—to control an LED based on the balance of an IOTA address. This project demonstrates how cryptocurrency can directly power physical devices in a machine-to-machine economy.

Whether you're new to IOTA or expanding your IoT development skills, this guide offers a practical entry point into decentralized device automation.


How It Works

The system monitors a specific IOTA address for incoming transactions. When funds are detected, the Raspberry Pi activates a relay connected to an LED. Each unit of IOTA balance powers the LED for one second. Once the balance drops to zero, the light turns off.

This concept can scale to real-world applications like pay-per-use appliances (e.g., refrigerators, washing machines), where users send microtransactions to unlock functionality.

👉 Discover how blockchain enables smart device monetization — explore more use cases here.


Components Needed

Here’s what you’ll need to assemble the circuit:

Total cost: under $50 USD (~350 CNY), making this an affordable and educational project.


Circuit Assembly

Follow these wiring instructions carefully:

  1. Connect Raspberry Pi Pin 2 (5V) to the VCC pin on the relay module.
  2. Connect Pin 6 (Ground) to the GND on the relay.
  3. Connect Pin 12 (GPIO18) to the IN control pin of the relay.
  4. Link the COM terminal of the relay to the positive terminal of the 9V battery.
  5. Connect the NO (Normally Open) terminal to the anode (long leg) of the LED, then add the 330Ω resistor from the cathode to the battery’s negative terminal.

When GPIO18 sends a HIGH signal, the relay closes, completing the circuit and lighting the LED.


Software Setup

Before coding, ensure your Raspberry Pi has:

Install Required Libraries

Run these commands in your terminal:

sudo apt update
sudo apt install python3-pip
pip3 install pyota

PyIOTA allows your script to query balances and interact with the Tangle—the DAG-based data structure underlying IOTA.

👉 Learn how decentralized ledgers support secure IoT ecosystems — dive deeper now.


Python Code Explained

Below is the complete script with comments explaining each section:

import time
import datetime
import RPi.GPIO as GPIO
from iota import Iota
from iota import Address

# GPIO setup
LEDPIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LEDPIN, GPIO.OUT)
GPIO.output(LEDPIN, GPIO.LOW)

# Connect to an IOTA full node
iotaNode = "https://nodes.thetangle.org:443"
api = Iota(iotaNode, "")

# Replace with your generated IOTA address
address = [Address(b'GTZUHQSPRAQCTSQBZEEMLZPQUPAA9LPLGWCKFNEVKBINXEXZRACVKKKCYPWPKH9AWLGJHPLOZZOYTALAWOVSIJIYVZ')]

def checkbalance():
    print("Checking balance...")
    gb_result = api.get_balances(address)
    balance = gb_result['balances']
    return balance[0]

# Initial balance check
currentbalance = checkbalance()
lastbalance = currentbalance

# Runtime variables
lightbalance = 0
balcheckcount = 0
lightstatus = False

# Main loop: runs every second
while True:
    # Check balance every 10 seconds
    if balcheckcount == 10:
        currentbalance = checkbalance()
        if currentbalance > lastbalance:
            lightbalance += (currentbalance - lastbalance)
            lastbalance = currentbalance
        balcheckcount = 0

    # Turn light ON if balance > 0
    if lightbalance > 0:
        if not lightstatus:
            print("Light ON")
            GPIO.output(LEDPIN, GPIO.HIGH)
            lightstatus = True
        lightbalance -= 1
    else:
        if lightstatus:
            print("Light OFF")
            GPIO.output(LEDPIN, GPIO.LOW)
            lightstatus = False

    # Display remaining runtime
    print(f"Time left: {datetime.timedelta(seconds=lightbalance)}")

    balcheckcount += 1
    time.sleep(1)

Key Features of the Code


Running the Script

Save the code as let_there_be_light.py and run:

python3 let_there_be_light.py

You should see output like:

Checking balance...
Time left: 0:00:05
Light ON

Now, send IOTA tokens to your designated address using any wallet app.

Once confirmed on the Tangle, the LED will turn on and stay lit until the balance depletes.


Frequently Asked Questions

Q: Can I use a different cryptocurrency instead of IOTA?

While this tutorial uses IOTA due to its feeless microtransactions and IoT focus, similar logic applies to other blockchains. However, high fees or slow confirmation times may limit practicality for real-time device control.

Q: Is this secure for commercial use?

For production environments, enhance security by:

Q: Why check balance only every 10 seconds?

Frequent API calls can overload public nodes. Polling every 10 seconds balances responsiveness with network etiquette.

Q: Can I control multiple devices?

Yes! Extend the code to monitor multiple addresses or use a multi-channel relay. Assign each channel a unique funding address for independent control.

Q: What happens if the Pi loses internet?

The script continues running but won’t detect new payments until connectivity resumes. Consider adding offline fallback logic or local caching.

Q: Does IOTA support smart contracts?

Not natively yet, but upcoming upgrades like IOTA Smart Contracts will allow complex logic directly on-chain, enabling richer IoT automation.


Real-World Applications

This simple demo illustrates a broader vision: machine economies, where devices autonomously transact without human intervention.

Imagine:

With secure, decentralized ledgers like IOTA, such scenarios become technically feasible and economically viable.

👉 See how next-gen blockchain platforms are transforming IoT — start exploring today.


Core Keywords

Integrated naturally throughout:

This tutorial blends practical electronics with cutting-edge distributed ledger technology, offering developers a foundation for building autonomous, monetizable IoT systems. By linking digital value to physical actions, we move closer to a truly interconnected world economy.