0

我正在尝试在 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();
}

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

4

1 回答 1

0

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

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

dtostrf(voltage, 0, 2, buf);

此外,如果您有兴趣,您可以在此处查看 Arduino 如何打印浮动。

于 2013-08-06T09:54:31.427 回答