Change sensor value via serial monitor

Hi everyone! I'm still a beginner with Arduino and I'm trying to understand how to change the value read by a sensor via serial monitor.

I am attaching a piece of the example sketch


void handleLight() {
  
  light =analogRead(LDR_PIN);
  Serial.println(light);
  pixels.begin();
  lcd.init();
  lcd.backlight();
  
    if (light < 700) { 
      
      for(int i=0;i<NUMPIXELS;i++)
         pixels.setPixelColor(i, pixels.Color(0,255,0)); 
         pixels.show();
         lcd.clear();
         lcd.setCursor(0,0);
         lcd.print("Light OK");
         delay (1000);
     
     }  else { for(int i=0;i<NUMPIXELS;i++)
      
          pixels.setPixelColor(i, pixels.Color(255,0,0)); 
          pixels.show();
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Light OFF");
          delay (1000);
}
}

I would like to be able to change the value (700) via serial monitor.

I would suggest to study Serial Input Basics to handle this

Step 1: Replace '700' with a variable. For example, a global variable named 'Threshold':
int Threshold = 700; // Default threshold

Step 2: Get input from Serial Monitor. Probably in loop().

  if (Serial.available())
  {
    int value = Serial.parseInt();
    // Zero means timeout so ignore that value
    if (value > 0 && value <= 1024)
      Threshold = value;
  }

Thanks so much! A question however, reading the guide called "Serial Input Basics" I saw that in example 4 they use the atoi command to convert the value from numeric to ascii (again if I understand correctly).

Don't I have to enter it?

No, atoi converts from ASCII to int

Serial.parseInt() will do that for you

ah ok, thank you

Thanks!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.