Using: Arduino Micro, IDE v1.0.5, and this 16x2 display.
This is a very early version of the sketch. It will eventually grow into a full-blown tachometer (I'll attach two optical sensors that will time the rotation of two rods - but that code is not there yet). For now, it just generates two random numbers, changes their values every second, and displays the result. I'm just testing the display for now.
The numbers can be any value between less than 1, and a few hundreds (roughly speaking), and not necessarily integers. I want to display the numbers with 4 digits total, including the decimal dot (if any). Examples:
0.236
7.59
48.1
236
If the value is negative, or larger than 1000, an error message needs be displayed instead.
So: read (or, for now, simulate) the value, give it the right format, and display. This is my current code:
#include <Adafruit_CharacterOLED.h>
Adafruit_CharacterOLED lcd(OLED_V2, 6, 7, 8, 9, 10, 11, 12);
// global variables for the simulated speeds
float mir;
float ecc;
void setup()
{
// initialize display
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("mirror: RPM");
lcd.setCursor(0, 1);
lcd.print("eccent: RPM");
// initialize simulated values
mir = random(0, 100);
ecc = random(0, 100);
}
void printspeed(float sp, int x, int y)
{
// the formatted string
String buf;
// required by dtostrf()
char temp[5];
// position the cursor
lcd.setCursor(x, y);
// format the number depending on its value
if (sp < 0) {
buf = " neg";
} else if (sp >= 0 && sp < 10) {
buf = dtostrf(sp, 4, 2, temp);
} else if (sp >= 10 && sp < 100) {
buf = dtostrf(sp, 4, 1, temp);
} else if (sp >= 100 && sp < 1000) {
buf = (String) round(sp);
} else {
buf = "high";
}
// and print to LCD
lcd.print(buf);
}
// generate a new random value for the simulation
float tweaksp(float sp)
{
float jit = 1.5;
float ret;
int jitint = (int) 1000 * jit;
ret = sp + (float)random(-jitint, jitint)/1000;
if (ret < 0)
ret += jit;
if (ret >= 1000)
ret -= 100;
return ret;
}
void loop()
{
// refresh random value
mir = tweaksp(mir);
ecc = tweaksp(ecc);
// display
printspeed(mir, 8, 0);
printspeed(ecc, 8, 1);
delay(1000);
}
It works fine for a while, but then it crashes and the display becomes corrupt. I suspect this might have something to do with my using String in the sketch.
Is there a way to format and display the numbers without using String? I've tried to avoid using it, but couldn't find a solution.