Communication between c# and Arduino.

Hello, i'm working in a project that can stop a conveyor when the production line is full, this information is captured by a c# app and after if its full that app sends 1 to arduino via serial port but if its empty sends 0.

i have this code on arduino

int input = 0;  
void setup(){
 
  pinMode(13, OUTPUT); // Declaramos que utilizaremos el pin 13 como salida
 
  Serial.begin(9600);
}
 
void loop(){
  if(input ==1){
  while (Serial.available()>0){
 
    input=Serial.read();
  }

  }
      if (input=='1'){
         Serial.println("Se recibio un 1");
      digitalWrite(13, HIGH); //Si el valor de input es 1, se enciende el led
 
    }
 
    else
 
    {
      Serial.println("Se recibio un 0");
      digitalWrite(13, LOW); //Si el valor de input es diferente de 1, se apaga el LED
    }
}

the principal issue that i have with this program is when the c# application stop, arduino still working and never stop the conveyor.

i want to know when c# stops to sending data to arduino and stop the sketch and the conveyor too.

i hope u can help me
Sorry for my bad english and thanks a lot.

Try the following sketch (yours one with slight modification):

int input = 0;
void setup()
{
  pinMode(13, OUTPUT); // Declaramos que utilizaremos el pin 13 como salida
  Serial.begin(9600);
  digitalWrite(13, LOW);
}

void loop()
{
  //if (input == 1)
  //{
  while (Serial.available() > 0)
  {
    input = Serial.read();
    //}
    //  }
    if (input == '1')
    {
      Serial.println("Se recibio un 1");
      digitalWrite(13, HIGH); //Si el valor de input es 1, se enciende el led
    }
    if(input == '0')
    {
      Serial.println("Se recibio un 0");
      digitalWrite(13, LOW); //Si el valor de input es diferente de 1, se apaga el LED
    }
  }
}

Hey thanks, now i can save the variable and add a timer to close the connection after a time