Solutions
No Results
Solution

Arduino on Algorand Blockchain

Overview

The Internet of Things is growing and getting more and more attention over time.
With a community of millions of users, Arduino is the most popular development board on the market.

In this solution, you will learn how to connect any Arduino to the Algorand Blockchain.
We will see how to build a simple IoT device that sends temperature measures to the Algorand Blockchain.

Requirements

Any Arduino

Any kind of Arduino will do the job. However the Arduino UNO is recommended to follow along.

A HC-05 Bluetooth Module

The HC-05 Bluetooth Module is a Serial Bluetooth Module for Arduino and other MCUs.

A Computer

It will be used to develop our IoT ecosystem and will act as the IoT Node.

An Algorand TestNet Wallet

It will be our entry point to perform the transactions on the Algorand Blockchain.
You can create an account online using My Algo or locally by following the Create an Account on TestNet using JavaScript tutorial.

A PureStake API key

This will allow us to connect and interact with the Algorand Blockchain.
To get a PureStake API key, you can follow steps 1 and 2 of the Getting Started with the PureStake API Service tutorial.

How it works

EditorImages/2020/06/02 19:28/IoT-Device.png

  1. The temperature value is measured by the sensor. Here we will not use any temperature sensor. For simplicity, the temperature value will be hard-coded within the Arduino firmware.
  2. The measure is sent via bluetooth to the IoT Node.
  3. The IoT Node receives the data and send it to the Algorand Blockchain.

Note

  • Steps 1 - 2 are performed by the IoT Device (Arduino).
  • Steps 3 by the IoT Node (Computer).

IoT Device

The IoT Device firmware is pretty straightforward.

To start off, get a copy of the firmware with this command:

 git clone https://github.com/TedNIVAN/algorand-iot-device.git

Note

Make sure you have git installed.

Then open up the iot-device.ino file within the Arduino IDE.

#include <SoftwareSerial.h>

SoftwareSerial BTserial(10, 11);

void setup()
{
    BTserial.begin(9600);

    char data[] = "70";

    for (int i = 0; i < sizeof(data) - 1; i++)
    {
        BTserial.print(data[i] & 0xFF, DEC);
        BTserial.print(" "); //separator
    }

    BTserial.println("");
}

void loop()
{
}

Let’s have a look at the code now:

  1. First we establish the Bluetooth serial communication.
  2. We define the plain data that we want to send (here we want to send a 70°C value)
  3. Finally we send the data to the IoT Node.

Note

To add security, we could encrypt the data before sending it.

IoT Node

The IoT Node is responsible for collecting the data from the IoT Device.
To start off, get a copy of the algorand-iot-node with this command:

git clone https://github.com/TedNIVAN/algorand-iot-node.git

To set everything up follow these commands:

cd algorand-iot-node
npm i

Note

Make sure you have Node.js installed.

Now that we are all set, we can configure the IoT Node. To do so, open up the .env file.

Here we have to set up:

  1. The Bluetooth serial port and serial speed for connecting the IoT Node to the IoT Device.
    You can find out the port on Mac or Linux with the following command:

ls /dev/cu.*


EditorImages/2020/05/09 11:46/Screenshot_2020-05-09_13-45-28-751.png

Here the port corresponding to the HC-05 Bluetooth Module is: /dev/cu.DSDTECHHC-05-DevB
2. Your PureStake testnet node and API key.
3. Your Algorand mnemonic phrase is used to recover your account to sign the transactions used in the example.

You should have a configuration close to that:

SERIAL_DEVICE=/dev/cu.DSDTECHHC-05-DevB
SERIAL_SPEED=9600

NODE="https://testnet-algorand.api.purestake.io/ps1"
APIKEY="af4Dyq6Pxb8c7I0ddWtJ********************"
MN="huge damp drum waste eager sail symptom census source ****************************************************"

Now let’s see what our code does.

Move to the app.js file.

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const algosdk = require('algosdk');

require('dotenv').config();

const mcu = process.env.SERIAL_DEVICE;
const serialPort = new SerialPort(mcu, { baudRate: JSON.parse(process.env.SERIAL_SPEED) });

const parser = new Readline();
serialPort.pipe(parser);

parser.on('data', temperature => {

    temperature = temperature.split(' ').map(Number);
    temperature = String.fromCharCode(temperature[0], temperature[1]);

    sendToAlgorandBlockchain(temperature);

});

sendToAlgorandBlockchain = (value) => {

    const baseServer = process.env.NODE;
    const port = "";
    const token = {
        'X-API-Key': process.env.APIKEY
    }

    const algodclient = new algosdk.Algod(token, baseServer, port);

    var mnemonic = process.env.MN;
    var account = algosdk.mnemonicToSecretKey(mnemonic);

    let note = algosdk.encodeObj(value);

    (async () => {

        let params = await algodclient.getTransactionParams();
        let endRound = params.lastRound + parseInt(1000);

        let txn = {
            "from": account.addr,
            "to": account.addr,
            "fee": 10,
            "amount": 0,
            "firstRound": params.lastRound,
            "lastRound": endRound,
            "genesisID": params.genesisID,
            "genesisHash": params.genesishashb64,
            "note": note,
        };

        const txHeaders = {
            'Content-Type': 'application/x-binary'
        }
        let signedTxn = algosdk.signTransaction(txn, account.sk);
        let tx = (await algodclient.sendRawTransaction(signedTxn.blob, txHeaders));
        console.log("Transaction : " + tx.txId);
    })().catch(e => {
        console.log(e);
    });

}

At top, we initialize the environment:

The bluetooth serial communication gets set up. Within the parser object, we listen to any bluetooth data event. The method gets triggered whenever new data is available. Once data is available, it is then converted from Ascii Codes to Characters. Finally, the plain temperature text measure is sent to the Algorand Blockchain via the sendToAlgorandBlockchain function.

The beautiful thing with the Algorand Blockchain is that you do not have to write any Smart Contract to store data to the Blockchain.
To do so, we will use the transaction note field. It has a capacity of up to 1kb in length.
All we need to do is to create a new transaction. Here, we set the receiver address to the sender address inside the txn object to keep it simple. As the purpose of this application is not to send money, we can leave the transaction amount to 0.

Alright, we are all good now! We can move on to the Testing section.

Testing

IoT Device side

  1. First make sure that the Bluetooth module is connected as follow:
    EditorImages/2020/05/08 17:40/arduino-hc05.png

  2. Flash the firmware to the Arduino.

Info

The schematic was created with Fritzing.

IoT Node side

Setting up the bluetooth:

  1. Enable the bluetooth communication on your computer.
  2. Pair your computer to the bluetooth HC-05 module (the pairing code should be 0000 or 1234 depending on the module).

    EditorImages/2020/05/09 11:47/Screenshot_2020-05-09_13-43-04-109.png
    EditorImages/2020/05/09 11:47/Screenshot_2020-05-09_13-43-26-865.png

Now head over to the IoT Node code:

  1. Run: node app.js
  2. Click on the reset button of the Arduino to initiate a transaction.
  3. Copy the outputted transaction id:
    EditorImages/2020/05/08 17:46/Screenshot_2020-05-01_15-29-08-330.png

Now we are going to visualize the transaction into a block explorer. To do so, head over to https://algoexplorer.io/ and paste the transaction id into the search field and select TESTNET on the right side before searching. Scroll down and click on the Message Pack tab.

EditorImages/2020/05/08 17:47/Screenshot_2020-05-01_15-31-26-063.png

Here we see that the transaction note with a value of 70 has been stored to the Algorand Blockchain.

You can also fetch the transaction note and display its content in a more elegant manner:
EditorImages/2020/05/08 17:48/iot-client.png

Here I will present how to visualize the transaction note into a web app.

To begin, get a copy of this repository:

git clone https://github.com/TedNIVAN/algorand-iot-client.git

  1. Open up the index.js file.
  2. Set your PureStake API key and your account address (generated from your mnemonic).
  3. Open up the index.html file and paste the transaction id to the input field.
  4. Click on the Start button.

Video

This video shows how to set up the IoT Node.

Info

Please ignore the AES Encryption Algorithm part on the video.

javascript

Arduino

IoT

C

Hardware

May 19, 2020