Hi all,
I am having a strange problem with a little test sketch I wrote in preparation for a larger project.
I'm trying to format strings with "sprintf" so that I don't need to build up output with multiple print calls.
Here's my code:
// LCD library
#include <LiquidCrystal.h>
LiquidCrystal lcd(11,10,9,5,4,3,2); // Noritake 16x2 VFD in 4 bit mode
#define chars 16
#define lines 2
char buffer[20]; // sprintf buffer
const char *hex_mask = "ADC5: 0x%03X";
const char *dec_mask = "CAL : %.2f VDC";
unsigned long readAnalog(byte port)
{
#define reads 1000
unsigned long value = 0;
for (int x = 0; x < reads; x++) {
value += analogRead(port); // multiple reads avg out noise
}
return (value / reads);
}
// floating point version of map()
float fmap(float x, float x1, float x2, float y1, float y2)
{
return ((x - x1) * (y2 - y1) / (x2 - x1) + y1);
}
void setup()
{
// pinMode(12, OUTPUT);
// digitalWrite(12, LOW); // only needed for LCD (Vee)
lcd.begin(chars, lines);
analogReference(EXTERNAL); // use external 5.0V reference
}
void loop()
{
unsigned long vlong = 0;
float vfloat = 0;
lcd.setCursor(0, 0); // column 0, row 0
vlong = readAnalog(A5); // read ADC
sprintf(buffer, hex_mask, vlong);
lcd.print(buffer);
lcd.setCursor(0, 1); // column 0, row 1
vfloat = fmap(vlong, 0.0, 1023.0, 0.0, 5.0); // map A/D to voltage to 0...5
sprintf(buffer, dec_mask, vfloat);
lcd.print(buffer);
}
However, on the VFD (LCD) display, it shows:
ADC5: 0x3FF
<- right
CAL : ? VDC
<- wrong!
I tested the relevant code with GCC in Linux and it works fine:
#include <stdio.h>
// floating point version of map()
float fmap(float x, float x1, float x2, float y1, float y2)
{
return ((x - x1) * (y2 - y1) / (x2 - x1) + y1);
}
int main(void)
{
char buffer[20]; // sprintf buffer
const char *hex_mask = "ADC5: 0x%03X";
const char *dec_mask = "CAL : %.2f VDC";
unsigned long vlong = 1023;
float vfloat = fmap(vlong, 0.0, 1023.0, 0.0, 5.0);
sprintf(buffer, hex_mask, vlong);
fprintf(stdout, buffer);
fprintf(stdout, "\n"); // needed for screen
sprintf(buffer, dec_mask, vfloat);
fprintf(stdout, buffer);
fprintf(stdout, "\n"); // needed for screen
return 0;
}
...results in:
root@michael:~/c-progs# ./test
ADC5: 0x3FF
CAL : 5.00 VDC
Anyone see anything wrong? This is driving me nuts! It should work. I suspect it's a simple problem staring me right in the face......
Any ideas will be appreciated. Thanks!
-- Roger