Arduino中String类型转int提示无效转换错误的解决方法
报错原因
你代码中触发报错的根本原因是:Arduino 的 String 类型不支持直接通过int(变量名)的方式强制转换为整数类型,必须调用String类内置的转换方法才能完成类型转换。
同时你的代码还存在多处隐性问题,即使修复类型转换报错也无法正常运行:
mlx.readObjectTempC()接口返回的是float浮点型数值,不能直接赋值给String类型的temp_obj变量setup()函数中mlx.readObjectTempC()语句末尾缺少分号,会触发额外编译错误- 你初始化的是16*2规格的LCD屏,仅支持0、1两个行号,
lcd.setCursor(0, 2)调用的第三行不存在,无法输出内容 setup()中你先调用传感器读数再执行mlx.begin()初始化传感器,会导致读取的温度值无效- 自定义函数
kaiguan()从未被调用,内部逻辑永远不会执行 loop()中的temp_obj = temp_obj.substring(0)属于无效操作,返回结果和原字符串完全一致
修复方法
核心报错修复
直接将报错的判断行
if (int(temp_obj) < 30)
替换为
if (temp_obj.toInt() < 30)
即可解决invalid cast from type String to type 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() { lcd.begin(); lcd.backlight(); pinMode(inputPin, INPUT); Serial.begin(9600); // 先初始化传感器再读数 mlx.begin(); // 先把浮点型温度转成String再赋值 temp_obj = String(mlx.readObjectTempC()); temp_obj = temp_obj.substring(5, 6); } void loop() { val = digitalRead(inputPin); if (val == HIGH) { Serial.print("Tem "); float currentTemp = mlx.readObjectTempC(); Serial.print(currentTemp); Serial.println(" Celsius"); lcd.setCursor(0, 0); lcd.print("temperature"); lcd.print(currentTemp); counter = counter + 1; delay(90); // 每次读取最新温度更新temp_obj temp_obj = String(currentTemp).substring(5, 6); Serial.println(temp_obj); // 调用开关检测逻辑 kaiguan(); } else { if (pirState == HIGH) { Serial.println("Motion ended!"); pirState = LOW; } } } void kaiguan() { if (pirState == LOW) { Serial.println("Motion detected!"); pirState = HIGH; Serial.println(mlx.readObjectTempC()); // 修复类型转换问题 if (temp_obj.toInt() < 30) { lcd.setCursor(0, 1); lcd.print(temp_obj); // 16*2屏只能用行0和行1,第二行内容覆盖显示 lcd.setCursor(0, 1); lcd.print("Not detected,reset!"); } } }
内容的提问来源于stack exchange,提问作者henry
相关产品推荐
相关产品推荐

