读取变量并将其打印在监视器上 - Arduino

问题描述 投票:0回答:1

我正在尝试读取变量并将其打印在显示屏上 但 IF 可能有问题 我将感谢您的帮助

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); 

int Value_pin_A0; // global variable to store the sensor value

void setup() {
  Serial.begin(9600); //initialize serial communication at 9600 bits per second
}

void loop() {
  //the loop routine runs over and over again forever
  int sensorValue = analogRead(A0); //read the input on analog pin 0
  Value_pin_A0 = sensorValue;
  Serial.println(sensorValue); //print out the value you read
  if ((Value_pin_A0 > 800)) {
    lcd.setCursor(0, 0);                  // move cursor to   (3, 0)
    lcd.print("               ");        // print message at (0, 0)
    lcd.setCursor(0, 0);                // move cursor to   (3, 0)
    lcd.print("Value over 800");         // print message at (0, 0)
    delay(500);                       // display the above for two seconds
  }
  if ((Value_pin_A0 < 799)) {
    lcd.setCursor(0, 0);                  // move cursor to   (3, 0)
    lcd.print("               ");        // print message at (0, 0)
    lcd.setCursor(0, 0);                // move cursor to   (3, 0)
    lcd.print("Value less 799");         // print message at (0, 0)
    delay(500);                       // display the above for two seconds
  }
}

将其打印在显示屏上

loops if-statement arduino arduino-nano
1个回答
0
投票

在您的代码中,您需要初始化 LCD 并打开背光。此外,您还需要检查 LCD 的 I2C 地址是否正确。对于您使用的单位,通常是 0x27 或 0x3f。如果这是错误的,您将什么也看不到。

在下面的代码中,我使用的是 Arduino Uno 和地址为 0x3f 的 I2C LCD,并且我显示从 A0 读取的值,因此如果 A0 上没有连接,您应该会看到一个不断变化的值(我得到的值约为 270 - 285).

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3f, 16, 2);  // Set the LCD I2C address - ususally 0x27 or 0x3F

void setup() {
    lcd.init();      
    lcd.backlight();
    
    lcd.clear();              
    lcd.print("Hello world");
}

void loop() {
    int sensorValue = analogRead(A0);
    lcd.setCursor(0, 1);  // Display analogue reading on line 2
    lcd.print(String(sensorValue) + "      ");
    delay(500);
}

如果 LCD 上看不到任何内容,则 I2C 连接可能有误。您应该在 A4 上有 SDA,在 A5 上有 SCL。

您说过上面的代码可以工作,但您想要一个带有 IF 语句的版本来检查 A0 上的读数是否高于或低于 800 - 所以下面的版本满足该要求。

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3f, 16, 2);  // Set the LCD I2C address - ususally 0x27 or 0x3F

void setup() {
    lcd.init();      
    lcd.backlight();
    
    lcd.clear();              
    lcd.print("Hello world");
}

void loop() {
    int sensorValue = analogRead(A0);
    lcd.setCursor(0, 1);  // Analogue reading on line 2
    if (sensorValue >= 800) lcd.print(">= 800 ");
    else lcd.print("< 800 ");
    delay(500);
}
© www.soinside.com 2019 - 2024. All rights reserved.