简体   繁体   English

将int变量与字符串连接会导致奇怪的输出

[英]Concatenating an int variable with a string results in a strange output

I have an arduino program in mind that i am trying to make. 我正在尝试制作一个arduino程序。

Its purpose: Read digital pins from 2, to 11. Print the pin number, and "1" if pin is high, or "0" if pin is low. 其目的:从2到11读取数字引脚。打印引脚号;如果引脚为高电平,则打印“ 1”;如果引脚为低电平,则打印“ 0”。

This is what i've tried to do: 这是我尝试做的:

void loop() {
  for(int i = 2; i<12; i++){
    if(digitalRead(i) == HIGH){
      Serial.println(i + "1");
    }
    if(digitalRead(i) == LOW){
     Serial.println(i + "0");
   }
  }
}

The output should be "21" if pin 2 is HIGH , or "20" if pin 2 is LOW . 输出应为 “21”,如果销2是HIGH ,或“20”,如果销2是LOW The same applies to the other pins. 其他引脚也一样。

Instead , all it prints is 相反 ,它打印的只是

Ò>Tm_°

>Tm_°

>Tm_°

Tm_°







Ò>Tm_°

>Tm_°

>Tm_°

Tm_°

Any advice on how i can get this to work? 关于如何使它起作用的任何建议?

What happen with your code ? 您的代码会怎样?

Serial.println(2 + "1") won't give you 21 in C (in this case used for Arduino). Serial.println(2 + "1")不会为您提供21的C语言(本例中为Arduino使用)。

You are trying to concatenate an integer and a string directly and it is not valid in C (or almost programming language). 您正在尝试直接连接整数和字符串,并且在C (或几乎是编程语言)中无效。

Solution: 解:

void loop() {
  char pin_display;
  for(int i = 2; i<12; i++){
    if(digitalRead(i) == HIGH){
      pin_display = i + 0x30 //convert to Ascii
      Serial.print(pin_display);
      Serial.print("1");
    }
    ...

As mentioned in the other answer, the problem happens in Serial.println(i + "1") . 如另一个答案中所述,问题发生在Serial.println(i + "1") This expression is evaluated as int + pointer that results in a corrupted pointer . 该表达式被评估为int +指针 ,导致指针损坏。 A short way to fix that is creating a String from the integer variable: Serial.println(String(i)+"1") . 一种简单的修复方法是从整数变量创建StringSerial.println(String(i)+"1") This expression is evaluated as String + pointer that results in a valid String object. 该表达式被评估为String +指针 ,该指针将导致一个有效的String对象。

Corrected code: 更正的代码:

void loop() {
    for(int i = 2; i<12; i++){
       if(digitalRead(i) == HIGH){
          Serial.println(String(i) + "1");
       }
       if(digitalRead(i) == LOW){
         Serial.println(String(i) + "0");
       }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM