A practical example of integrating IoT devices with blockchain technology. This project demonstrates how to read real-world sensor data from a DHT22 temperature/humidity sensor connected to Raspberry Pi 5, and store that data on-chain using the Cardano blockchain.
This repository provides a complete, working example of:
- IoT Data Collection: Reading temperature and humidity from DHT22 sensor via Raspberry Pi 5
- Real-time Monitoring: Continuous sensor data monitoring with auto-retry mechanism
- Blockchain Integration: Creating and submitting transactions to Cardano blockchain
- Data Immutability: Storing IoT sensor data permanently on-chain
- Environmental monitoring with tamper-proof data storage
- Supply chain temperature tracking
- Smart home automation with blockchain verification
- IoT device data provenance and audit trails
βββββββββββββββββββ
β DHT22 Sensor β (Temperature & Humidity)
β GPIO 4, Pin 7 β
ββββββββββ¬βββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β Raspberry Pi 5 β
β βββββββββββββββββββββββββββββββββ β
β β Python Script (read_dht22.py)β β
β β β’ Read sensor via GPIO β β
β β β’ Return JSON data β β
β ββββββββββββ¬βββββββββββββββββββββ β
β β β
β βΌ β
β βββββββββββββββββββββββββββββββββ β
β β Node.js (index.js) β β
β β β’ Collect sensor data β β
β β β’ Format for blockchain β β
β β β’ Auto retry on errors β β
β ββββββββββββ¬βββββββββββββββββββββ β
βββββββββββββββΌββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β Cardano Blockchain β
β βββββββββββββββββββββββββββββββββ β
β β Transaction Submission β β
β β β’ Metadata: sensor readings β β
β β β’ Timestamp β β
β β β’ Immutable storage β β
β βββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββ
- Sensor Reading: DHT22 sensor measures temperature and humidity
- Data Collection: Raspberry Pi reads sensor data via GPIO pins
- Data Processing: Node.js formats data into JSON structure
- Transaction Creation: Data is embedded into Cardano transaction metadata
- On-Chain Storage: Transaction is submitted to Cardano blockchain
- Verification: Data is permanently stored and publicly verifiable
# 1. Install Python dependencies
sudo pip3 install rpi-lgpio adafruit-circuitpython-dht --break-system-packages
# 2. Install Node.js dependencies
npm install
# 3. Configure GPIO permissions (one-time setup)
sudo usermod -a -G gpio $USER
sudo reboot
# 4. Run IoT monitor
npm start- Raspberry Pi 5 (or any Raspberry Pi with GPIO)
- DHT22 Sensor (AM2302 - Temperature & Humidity sensor)
- Jumper Wires (3 wires: Power, Data, Ground)
- Optional: 10kΞ© pull-up resistor for Data line
DHT22 Sensor Raspberry Pi 5
βββββββββββ ββββββββββββββββ
β + β βββββββββΊ β Pin 1 (3.3V) β
β β β β
β Data β βββββββββΊ β Pin 7 (GPIO4)β
β β β β
β - β βββββββββΊ β Pin 9 (GND) β
βββββββββββ ββββββββββββββββ
| DHT22 Pin | Raspberry Pi Pin | GPIO | Description |
|---|---|---|---|
| + (VCC) | Pin 1 | 3.3V | Power supply |
| Data | Pin 7 | GPIO 4 | Data signal |
| - (GND) | Pin 9 | GND | Ground |
- Always use 3.3V, NOT 5V - Using 5V may damage your Raspberry Pi
- Power off Raspberry Pi before connecting/disconnecting sensors
- Hardware: Raspberry Pi 5 (or any model with GPIO)
- OS: Raspberry Pi OS (Debian-based)
- Node.js: v16.x or higher
- Python: 3.7 or higher
- Network: Internet connection for blockchain transactions
git clone <your-repo-url>
cd iot1sudo apt-get update
sudo apt-get install -y python3 python3-pip build-essential python3-dev nodejs npm# Install DHT22 sensor libraries
sudo pip3 install rpi-lgpio adafruit-circuitpython-dht --break-system-packagesnpm installTo run without sudo, add your user to the gpio group:
sudo usermod -a -G gpio $USER
sudo reboot # Required for group changes to take effectIf you want to submit transactions to Cardano blockchain, create a .env file:
# Copy example environment file
cp .env.example .env
# Edit .env with your credentials
nano .envAdd your Blockfrost API key and wallet mnemonic:
BLOCKFROST_API_KEY=your_blockfrost_api_key
MNEMONIC="your mnemonic phrase goes here"How to get credentials:
- Blockfrost API Key: Sign up at blockfrost.io and create a project
- Mnemonic: Your 12/15/24-word wallet recovery phrase
.env file to version control!
# Test sensor reading
python3 dht22.py
# Expected output: {"temperature": 23.9, "humidity": 78.6}
# Test with npm
npm test
# Verify GPIO permissions
groups | grep gpio
# Test Node.js environment
node --version
npm --versionThis project provides 3 main operating modes:
Purpose: Continuously read and display temperature/humidity data from DHT22 sensor.
How to run:
# Run continuous monitoring (reads every 0.5 seconds)
npm start
# Or run with auto-reload (for development)
npm run devExpected Output:
========================================
DHT22 Real-Time Sensor Monitor
========================================
Connection Details:
Positive -> 3.3V (Pin 1)
Out -> GPIO 4 (Pin 7)
Negative -> GND (Pin 9)
========================================
Read Interval: 3 seconds
Press Ctrl+C to stop
========================================
[8:15:48 PM] β Reading #1 | Temp: 23.9Β°C | Humidity: 78.6%
[8:15:54 PM] β Reading #2 | Temp: 23.9Β°C | Humidity: 78.1%
[8:15:58 PM] β Reading #3 | Temp: 24.0Β°C | Humidity: 78.1%
[8:16:01 PM] β Reading #4 | Temp: 23.9Β°C | Humidity: 78.1%
Stop the program: Press Ctrl+C
========================================
π Session Statistics
========================================
Total readings: 262
Successful: 260
Failed: 2
Success rate: 99.2%
========================================
DHT22 Monitor stopped
========================================
Symbol Explanations:
- β : Successful reading
- β³ : Retrying due to temporary error
- β : Failed after all retry attempts
Purpose: Quick check of current sensor data.
# Using Python (direct)
python3 dht22.py
# Output: {"temperature": 23.9, "humidity": 78.6}
# Using Node.js wrapper
npm run ms
# Output: { temperature: 23.9, humidity: 78.7 }
# Or use npm test
npm testWhen to use:
- Test if sensor is working
- Debug hardware connections
- Get quick values without continuous monitoring
Purpose: Read sensor and write data to Cardano blockchain (automatically every 2 minutes).
Step 1: Check configuration
# Check if .env file has all required information
cat .envThe .env file must contain:
BLOCKFROST_API_KEY=preprod...your_key_here
MNEMONIC="word1 word2 word3 ... word12"Step 2: Run blockchain write script
npm start -- --writeExpected Output:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π€ BLOCKCHAIN TRANSACTION - WRITE DATA β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β° Time: 11/4/2025, 8:15:48 PM
π‘ Step 1/5: Reading sensor data...
β Temperature: 23.9Β°C
β Humidity: 78.6%
π¨ Step 2/5: Building transaction...
β’ Sensor Name: dht22_01
β’ Temperature (on-chain): 23900 (23.9Β°C Γ 1000)
β’ Humidity (on-chain): 78600 (78.6% Γ 1000)
β Transaction built successfully
βοΈ Step 3/5: Signing transaction...
β Transaction signed
π€ Step 4/5: Submitting to Cardano Preprod network...
β Transaction submitted!
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Transaction Hash:
a1b2c3d4e5f6789abcdef...
π View on Explorer:
https://preprod.cexplorer.io/tx/a1b2c3d4e5f6789abcdef...
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β³ Step 5/5: Waiting for blockchain confirmation...
β Transaction confirmed on blockchain!
β
SUCCESS: Data written to Cardano blockchain
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β° Next submission in 2 minutes...
Data stored on blockchain:
// Data format in smart contract
{
sensorName: 'dht22_01',
temperature: 23900, // = 23.9Β°C Γ 1000
humidity: 78600 // = 78.6% Γ 1000
}View transaction on blockchain:
- Testnet (Preprod): https://preprod.cexplorer.io/tx/YOUR_TX_HASH
- Mainnet: https://cexplorer.io/tx/YOUR_TX_HASH
Important Notes:
- Script runs continuously every 2 minutes
- Each transaction costs ~0.2 ADA gas fee
- Ensure wallet has sufficient ADA balance (minimum 2-3 ADA)
- Data is stored permanently on blockchain and cannot be deleted
Purpose: View historical sensor data stored on blockchain.
# Monitor blockchain data (updates every 30 seconds)
npm run monitorExpected Output:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β οΏ½ BLOCKCHAIN QUERY - READ DATA β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
οΏ½π Querying Cardano blockchain...
β’ Sensor: dht22_01
β’ Policy ID: d5e6f7a8b9c0d1e2f3...
οΏ½ Fetching transactions...
β Found 145 transactions
βοΈ Processing transaction data...
β’ Processed 10/145 transactions...
β’ Processed 20/145 transactions...
...
β’ Processed 140/145 transactions...
β Successfully processed 145 records
β
Query completed successfully
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Showing 5 most recent records:
π Record #141
Time: 11/4/2025, 8:00:00 PM
Temperature: 23.8Β°C
Humidity: 78.5%
Transaction: https://preprod.cexplorer.io/tx/abc123...
π Record #142
Time: 11/4/2025, 8:02:00 PM
Temperature: 23.9Β°C
Humidity: 78.6%
Transaction: https://preprod.cexplorer.io/tx/def456...
[... 3 more records ...]
β° Refreshing in 30 seconds...
The system automatically retries when sensor read errors occur:
Successful retry example:
[8:20:10 PM] β³ Retry 1/5 - Sensor timeout
[8:20:12 PM] β³ Retry 2/5 - Timed out waiting for PulseIn on START
[8:20:14 PM] β Reading #5 | Temp: 23.9Β°C | Humidity: 78.6%
ββ Success after 2 retries
Failed retry example:
[8:20:20 PM] β³ Retry 1/5 - Sensor timeout
[8:20:22 PM] β³ Retry 2/5 - No response
[8:20:24 PM] β³ Retry 3/5 - Timeout
[8:20:26 PM] β³ Retry 4/5 - RuntimeError
[8:20:28 PM] β³ Retry 5/5 - Sensor timeout
[8:20:30 PM] β Failed after 5 attempts: Sensor communication error
Retry configuration:
- Maximum retry attempts: 5 times
- Delay between retries: 2 seconds
- Maximum total timeout: ~12 seconds
| Command | Purpose | Runs Forever? |
|---|---|---|
npm run write |
Write to blockchain | β Yes (every 2 min) |
npm run monitor |
Read from blockchain | β Yes (every 30s) |
npm run sensor |
Test sensor directly | β No |
Edit write.ts to change how often data is submitted to blockchain:
const intervalMs = 2 * 60 * 1000; // Current: 2 minutes
// const intervalMs = 5 * 60 * 1000; // 5 minutes
// const intervalMs = 10 * 60 * 1000; // 10 minutesEdit dht22.py to use a different GPIO pin:
board_pin = board.D4 # Current: GPIO 4 (Pin 7)
# board_pin = board.D17 # GPIO 17 (Pin 11)
# board_pin = board.D27 # GPIO 27 (Pin 13)Configure blockchain settings in .env file:
# Blockfrost API (Get from https://blockfrost.io)
BLOCKFROST_API_KEY=your_blockfrost_api_key
# Wallet Mnemonic (24 words)
MNEMONIC="your mnemonic phrase goes here"Blockfrost vs Local Node:
- Blockfrost (Recommended): Easy API access, no node setup required
- Local Node: More decentralized, requires running cardano-node
Problem: ModuleNotFoundError: No module named 'adafruit_dht'
sudo pip3 install rpi-lgpio adafruit-circuitpython-dht --break-system-packagesProblem: Permission denied (GPIO access)
sudo usermod -a -G gpio $USER
sudo reboot
# Verify group membership
groups | grep gpioProblem: Failed to read sensor after 5 attempts
Check the following:
- β Verify wiring connections (especially Data pin to GPIO 4)
- β Confirm using 3.3V, NOT 5V
- β Increase READ_INTERVAL to 5000ms or higher
- β Try different GPIO pin (GPIO 17, 27)
- β Restart Raspberry Pi
- β Test with:
python3 dht22.pyornpm test
Problem: RuntimeError: Timed out
This is normal for DHT22 sensors. The script will auto-retry. If persistent:
# Check power supply (undervoltage can cause issues)
vcgencmd get_throttled
# Check CPU temperature (overheating can affect GPIO)
vcgencmd measure_temp
# Test sensor directly
python3 dht22.py
# Try reading multiple times
for i in {1..5}; do python3 dht22.py; sleep 3; doneProblem: Transaction submission failed
Check:
- β
.envfile exists with validBLOCKFROST_API_KEYandMNEMONIC - β Blockfrost API key is for correct network (testnet/mainnet)
- β Wallet has sufficient ADA balance (min 2 ADA for testnet)
- β Mnemonic phrase is correct (12/15/24 words)
- β Network connectivity to Blockfrost API
Problem: Invalid metadata format
Ensure sensor data is valid JSON:
# Test sensor output
python3 dht22.py | jq .
# Expected output:
# {
# "temperature": 23.9,
# "humidity": 78.6
# }iot1/
βββ index.ts # Main sensor monitoring application
βββ write.ts # Blockchain data submission script
βββ read.ts # Read blockchain data
βββ read-sensor.ts # Simple sensor reading script
βββ dht22.py # Python script for DHT22 sensor (GPIO)
βββ sensor.ts # TypeScript sensor interface
βββ package.json # Node.js dependencies
βββ tsconfig.json # TypeScript configuration
βββ plutus.json # Cardano smart contract config
βββ .env # Environment variables (Blockfrost, mnemonic)
βββ .env.example # Environment template
βββ action/ # Blockchain transaction handlers
β βββ claim.ts # Claim transaction logic
β βββ read.ts # Read on-chain data
β βββ write.ts # Write data to blockchain
βββ scripts/ # Smart contract utilities
β βββ index.ts # Contract exports
β βββ mesh.ts # Cardano Mesh SDK integration
βββ README.md # This documentation
index.ts: Main monitoring app - reads sensor every 3 seconds with retry mechanismwrite.ts: Submits sensor data to Cardano blockchain every 2 minutesdht22.py: Python script that interfaces with DHT22 via GPIO 4sensor.ts: TypeScript wrapper for Python sensor communicationread-sensor.ts: Simple one-time sensor reading scriptaction/write.ts: Creates and submits Cardano transactions with sensor dataaction/read.ts: Queries blockchain for historical sensor datascripts/mesh.ts: Smart contract wrapper using Mesh SDKplutus.json: Smart contract configuration for on-chain validation.env: Stores Blockfrost API key and wallet mnemonic (never commit!)
- Read Sensor Data: Node.js calls Python script to read DHT22
- Format Metadata: Sensor data is formatted as Cardano transaction metadata
- Build Transaction: Use Cardano SDK to construct transaction with metadata
- Sign Transaction: Sign with wallet private key
- Submit to Network: Broadcast to Cardano blockchain
- Confirmation: Wait for transaction confirmation
// Example: Read historical sensor data from blockchain
import { readSensorData } from './action/read';
const txHash = "abc123...";
const sensorData = await readSensorData(txHash);
console.log(sensorData);# Check GPIO status
gpio readall
# Monitor CPU temperature
watch vcgencmd measure_temp
# Check power supply status
vcgencmd get_throttled
# View system logs
journalctl -f- Supply chain temperature monitoring
- Environmental data marketplaces
- Decentralized sensor networks
- IoT device authentication
Contributions are welcome! Please feel free to submit pull requests or open issues.
ISC
- Never commit
.envfile to version control - Add to.gitignore - Never share your mnemonic phrase with anyone
- Use Blockfrost API keys with appropriate permissions
- Store mnemonic securely (consider hardware wallets for mainnet)
- Test on Cardano testnet before mainnet deployment
- Regularly update dependencies for security patches
- Monitor transaction costs and wallet balance on mainnet
- Use separate wallets for testing and production
- Batch multiple readings into single blockchain transaction to save fees
- Use local Cardano node for faster transaction submission
- Implement data validation before submitting to blockchain
- Consider using IPFS for large data payloads (store hash on-chain)
For questions or issues:
- Open an issue on GitHub
- Check Troubleshooting section
- Review Cardano Stack Exchange
Built with β€οΈ using Raspberry Pi 5 and Cardano Blockchain