IoT Clouds Variable doesn't affect as demand

Iam making a project about led control with Ultrasonic and a virtual slider from arduino ioT cloud. iam using a virtual swtich (on/off) from arduino IoT cloud as the logic changer. when the switch is on i want the led is controlled by ultrasonic, where the distance <= 80 turn on lamp1 and if not would turn it off, but when the virtual switch is off i want the lamp1 is no longer controlled by ultrasonic, instead by a slider (using PWM). but what happens is when i turn on the swtich, lamp1 doesn't change it's state even the distance is > 80, but when the switch is off, lamp1 can be controlled by the slider, here's my code :

#define trig 8
#define echo 7
#define lamp1 11

void setup() {
  Serial.begin(9600);
  delay(1500);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(lamp1, OUTPUT);

  initProperties();
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}

void loop() {
  ArduinoCloud.update();

  if (lED) {
    // Jika switch ON, kontrol lamp1 menggunakan jarak ultrasonik
    controlWithUltrasonic();
  } else {
    // Jika switch OFF, kontrol lamp1 menggunakan slider dim
    analogWrite(lamp1, dim);
  }

  delay(100);  // Delay untuk menghindari pembaruan terlalu cepat
}

void controlWithUltrasonic() {
  // Mengambil pembacaan jarak dari sensor ultrasonik
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  
  long duration = pulseIn(echo, HIGH);
  distance = duration / 29 / 2;

  // Mengatur lamp1 berdasarkan jarak ultrasonik
  if (distance <= 80) {
    digitalWrite(lamp1, HIGH);
  } else {
    digitalWrite(lamp1, LOW);
  }
}

void onLEDChange() {
  // Jika switch berubah ke ON atau OFF, panggil mode kontrol yang sesuai
  if (lED) {
    controlWithUltrasonic();  // Mulai kontrol dengan ultrasonik
  } else {
    analogWrite(lamp1, dim);  // Mulai kontrol dengan slider
  }
}

void onDimChange() {
  // Perbarui lamp1 dengan nilai slider hanya jika lED dalam posisi OFF
  if (!lED) {
    analogWrite(lamp1, dim);
  }
}

ketik atau tempel kode di sini

ketik atau tempel kode di sini

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