Extending Rhomb.IoT
Rhomb.IoT by default comes vitaminized with a lot of functions that will make you not need to write code to create applications, however sometimes you will want to write your own library or add a module that performs a new function.
Previously in First Application we have seen how to create a main.cpp file as a central point of our application. We are going to take it up again to add our own library.
Basic main.cpp
We will start with this main.cpp
:
// src/main.cpp
#include "rhomb.iot.h"
void setup() {
core::setup();
}
void loop() {
core::loop();
}
What can our application do?
We are going to create a small example (Hello World!) where we will connect a potentiometer to an analog pin, read its value and send an alert to the server in case it is higher than a previously set value.
Create a header file
Rhomb.IoT is a Header Only project, we want to crate a header file for our library: potentiometer.h
.
Simplified file structure:
.
├── lib/
│ └── rhomb.iot/
│ └── potentiometer/
| ├── potentiometer.h
├── src/
│ └── main.cpp
We created the folder potentiometer
and added the file potentiometer.h
with this initial code:
// lib/potentiometer/potentiometer.h
#pragma once
namespace potentiometer {
const analogPin = AD0;
const maxValue = 50; // percentage
// It will be executed in a recurrent way with the Arduino loop
uint8_t loop(uint8_t param) {
int read = analogRead(analogPin);
int percentage = map(read, 0, 1023, 0, 100);
echo::info("Percentage is", percentage);
}
uint8_t init() {
echo::info("INIT Potentiometer");
// Subscribe our loop method to the Arduino Loop
puf::on(EV_BEFORE_LOOP, loop);
}
} // namespace potentiometer
We will talk later about this code. Now add the library to the main.cpp
// src/main.cpp
#include <Arduino.h>
#include "rhomb.iot.h"
#include "potentiometer.h"
void setup() {
core::setup();
potentiometer::init();
}
void loop() {
core::loop();
}
Simply include the library and call potentiometer::init()
method on the setup.
The first version of the library is ready, but this is very simple, it only prints on screen the read value. Also the loop function of our library is running over the main loop function of arduino, this means that a lot of output will be sent to the debug terminal because we are using the method echo::info()
to print a message (echo
is a wrapper for Arduino Serial).
Add a delay to the loop function:
// lib/potentiometer/potentiometer.h
[...]
unsigned long timer = 0;
uint8_t loop(uint8_t param) {
// read always
int read = analogRead(analogPin);
int percentage = map(read, 0, 1023, 0, 100);
// but print once every 5 seconds
if (millis() - timer >= 5000) {
echo::info("Percentage is", percentage);
timer = millis();
}
}
[...]
Danger
You should not use the method delay()
of Arduino if you are not sure what you are doing.