'my problem is my arduino don't work correctly

This is my code:

int data;

void setup(){
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  Serial.println("Hi");
} 

void loop(){
  delay(500);
  while(Serial.available())
  {
    int data = Serial.read();
    Serial.print(data);
  }
  
  if (data == 1)
    digitalWrite(13, HIGH);
  else if (data == 0)
    digitalWrite(13,LOW);
}
  

Now when I run the code and send a data the arduino don't work correctly for example: I send 1 and my arduino prints: 49 \n 10 and then led don't turn ON

This is the printed text :

-> Hi 
-> 49
-> 10

And never data == 1



Solution 1:[1]

Your variable data is an int. Serial.read() has to fit its data into that type, so it returns the ASCII value of your input. 49 is ASCII for 1 and 10 is ASCII for LF or line feed.

To get the character you inputted, set the type of data to char. This should then return 1.

Solution 2:[2]

can you try to change your int data to char data and use

if (data == '1'){
digitalWrite(13, HIGH);
}
else if (data == '0'){
digitalWrite(13, LOW);
}

i think if you using int that will convert from character to decimal from ASCII table

Solution 3:[3]

you initialized the data twice the data you couldn't access the data inside you while loop

try this code

int data;

void setup(){
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  Serial.println("Hi");
} 

void loop(){
  delay(500);
  while(Serial.available())
  {
    data = Serial.read();  //you don't need to initialize the data again 
  }
  
  Serial.print(data);
  
  if (data == 1)
    digitalWrite(13, HIGH);
  else if (data == 0)
    digitalWrite(13,LOW);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GreenCobalt
Solution 2 Raden Bagus Joned
Solution 3 Revan99