【问题标题】:Converting string to int in arduino在arduino中将字符串转换为int
【发布时间】:2021-10-09 03:17:10
【问题描述】:

我的if 语句弹出一个错误,我需要您的帮助来修复它,错误显示从String 类型到int 类型的无效转换。

int inputPin = 8;
int pirState = LOW;
int val = 0;
int counter = 0;
String temp_obj;

#include <Wire.h>
#include <Adafruit_MLX90614.h>
#include <LiquidCrystal_I2C.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  temp_obj = mlx.readObjectTempC();
  mlx.readObjectTempC()
  temp_obj = temp_obj.substring(5, 6);
  lcd.begin();
  lcd.backlight();
  pinMode(inputPin, INPUT);
  Serial.begin(9600);
  mlx.begin();
}

void loop() {
  val = digitalRead(inputPin);
  if (val == HIGH) {
    Serial.print("Tem ");
    Serial.print(mlx.readObjectTempC());
    Serial.println(" Celsius");
    lcd.setCursor(0, 0);
    lcd.print("temperature");
    lcd.print(mlx.readObjectTempC());
    counter = counter + 1;
    delay(90);
    temp_obj = temp_obj.substring(0);
    Serial.println(temp_obj);
  }
}

void kaiguan() {
  if (pirState == LOW) {
    Serial.println("Motion detected!");
    pirState = HIGH;
    Serial.println(mlx.readObjectTempC());
    if (int(temp_obj) < 30) {
      //an error has popped up for my if statement and I need YOUR help to fix it the error says invalid cast from type String to type int.
      lcd.setCursor(0, 1);
      lcd.print(temp_obj);
      lcd.setCursor(0, 2);
      lcd.print("Not detected,reset!");
    }
  }
}

【问题讨论】:

  • 你用过API和语言文档吗?
  • @TedLyngmo - 嘿,我是个编辑新手,我猜你和我在同一时间 - 但我用适当的间距和诸如此类的东西格式化了代码 - 它告诉我我需要解释我的编辑-所以我在帖子和编辑摘要中都这样做了-在从您的编辑中刷新后-但它不允许我发布。知道为什么吗?我不确定我做错了什么。
  • 重点是,你搜索过“arduino String to int”吗?第一个热门是toInt 的 Arduino 文档

标签: c string arduino type-conversion integer


【解决方案1】:

改变

int(temp_obj)

到

temp_obj.toInt()

您可以在official doc 中阅读有关该功能的更多信息,正如评论中指出的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2011-10-02
    相关资源
    最近更新 更多