将电位计值转换为GLCD显示的字符串

时间:2013-08-02 22:12:47

标签: arduino

我正试图在Adafruit ST7565 GLCD上显示电位计的值。我的串行监视器给出的值介于1.62-1.67之间,而GLCD的值介于-20,000到+20,000之间。我不确定算术/数据类型是否错误,或者我是否为“sprintf”转换不正确地分配内存。

#include "ST7565.h"
#include "stdlib.h"

char buffer[5];
int ledPin =  13;    // LED connected to digital pin 13
char str[8];

// the LCD backlight is connected up to a pin so you can turn it on & off
#define BACKLIGHT_LED 10
// pin 9 - Serial data out (SID)
// pin 8 - Serial clock out (SCLK)
// pin 7 - Data/Command select (RS or A0)
// pin 6 - LCD reset (RST)
// pin 5 - LCD chip select (CS)
ST7565 glcd(9, 8, 7, 6, 5);

#define LOGO16_GLCD_HEIGHT 16 
#define LOGO16_GLCD_WIDTH  16 

void setup()   {
  Serial.begin(9600);
  // turn on backlight
  pinMode(BACKLIGHT_LED, OUTPUT);
  digitalWrite(BACKLIGHT_LED, HIGH);
  // initialize and set the contrast to 0x18
  glcd.begin(0x18);
  glcd.display(); // show splashscreen
  delay(3000);
  glcd.clear();
  Serial.println(" ");
  digitalWrite(BACKLIGHT_LED, HIGH);
  glcd.drawstring(0,0," ");
  glcd.display();
  glcd.clear();
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
  digitalWrite(BACKLIGHT_LED, HIGH);
  Serial.println(voltage);
  sprintf(str,"%d",voltage); // converts to decimal base.
  glcd.drawstring(0,0,str);
  glcd.display();
  delay(500);
  glcd.clear();
}

任何见解都表示赞赏。我没有太多正式的编程经验,因此链接有关数据类型的教程将没有任何用处。我需要看到一个像这样的具体例子才能真正理解。

1 个答案:

答案 0 :(得分:0)

您使用%d打印出float;这是未定义的行为(在您的情况下,它可能会抛弃float位序列的某些部分的整数表示。)

使用dtostrf

而不是使用sprintf(因为sprintf(..., "%f", val)据报道在Arduino上已被破坏)
dtostrf(voltage, 0, 2, buf);

另外,如果您有兴趣,可以看看Arduino如何打印浮动here