首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印温度到LCD外环

打印温度到LCD外环
EN

Stack Overflow用户
提问于 2013-11-23 08:03:31
回答 1查看 1.5K关注 0票数 0

我对Arduino或一般的编程是个新手,我正在尝试一些东西。我使用的是一个基本菜单的代码,你只需按下按钮就可以滚动浏览。这很好用,但我想让它在第一个菜单上显示温度。

计算温度的代码在循环()中,而定制菜单的代码在setup()loop()之前。我想使用lcd.print(temperatureC)将温度打印到LCD,但不能使用temperatureC,因为它只在loop()中声明。

有什么办法可以解决这个问题吗?我对此非常陌生。

代码语言:javascript
复制
#include <LiquidCrystal.h>

LiquidCrystal lcd(8,9,10,11,12,13);
int tempPin = A0;
int photocellPin = A1;
const byte mySwitch = 7;
#define aref_voltage 3.3


// these "states" are what screen is currently being displayed.
typedef enum 
  {
  POWER_ON, TEMPERATURE, LIGHTSENSOR, EXHAUST_FAN1, EXHAUST_FAN2,
  // add more here ...

  LAST_STATE  // have this last
  } states;

byte state = POWER_ON;

byte oldSwitch = HIGH;

void powerOn ()
  {
  Serial.println ("Welcome!");
  lcd.setCursor(0,0);
  lcd.print("Welcome!");
  delay(2000);

  }

void showTemperature ()
  {
  Serial.println ("Temperature");
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Temperature");
  lcd.setCursor(0,1);
  lcd.print(temperatureC);



void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor 
  analogReference(EXTERNAL);
  pinMode (mySwitch, INPUT_PULLUP);
  lcd.begin(16, 2);
  lcd.clear();
  powerOn ();
}

void loop()
{ 
  int sensorVal = analogRead(tempPin);
  delay(5);
  int photocellVal = analogRead(photocellPin);
  delay(5);
  float voltage = (sensorVal) * aref_voltage;
  voltage /= 1024.0; 
  float temperatureC = (voltage - .5) * 100;
  temperatureC = round(temperatureC * 2.0) / 2.0;

  {
  byte switchValue = digitalRead (mySwitch);

  // detect switch presses
  if (switchValue != oldSwitch)
    {
    delay (100);   // debounce

    // was it pressed?
    if (switchValue == LOW)
      {
      state++;      // next state
      if (state >= LAST_STATE)
        state = TEMPERATURE;  

      switch (state)
        {
        case POWER_ON:     powerOn ();         break;
        case TEMPERATURE:  showTemperature (); break;
        case LIGHTSENSOR:  showLightsensor (); break;
        case EXHAUST_FAN1: showExhaustFan1 (); break;
        case EXHAUST_FAN2: showExhaustFan2 (); break;
        }  // end of switch
      }  // end of switch being pressed

    oldSwitch = switchValue;  
    } // end of switch changing state

  }  // end of loop
EN

回答 1

Stack Overflow用户

发布于 2013-11-25 23:12:36

将读取温度的代码移动到它自己的方法中,(与轻量读取代码分开-为此创建另一个方法)……

代码语言:javascript
复制
float getTemperature() {
  int sensorVal = analogRead(tempPin);
  delay(5);
  float voltage = (sensorVal) * aref_voltage;
  voltage /= 1024.0; 
  float temperatureC = (voltage - .5) * 100;
  temperatureC = round(temperatureC * 2.0) / 2.0;
  return temperatureC;
}

然后在showTemperature()方法中调用此方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20156725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档