Getting data to IoT cloud widget

I am using the HC-SR04 to measure distance and would like to display the measurement on a widget. I have a widget defined as value but it never updates, always displays zero. I am also trying to light an LED widget when the distance is less than 10cm. The distance is displayed correctly in the serial monitor but the physical LED on pin 7 does not light. It does not print "LED status changed" in the serial output.

/* 
  Sketch generated by the Arduino IoT Cloud Thing "Untitled"
  https://create.arduino.cc/cloud/things/865b47d3-7e78-4878-9038-4b3aec5535b1 

  Arduino IoT Cloud Variables description

  The following variables are automatically generated and updated when changes are made to the Thing

  int distance;
  bool led;

  Variables which are marked as READ/WRITE in the Cloud Thing will also have functions
  which are called when their values are changed from the Dashboard.
  These functions are generated with the Thing and added at the end of this sketch.
*/

#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
int trigPin = 9;
int echoPin = 10;
//int led = 7;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
   pinMode(led, OUTPUT);     //wire to digital 7
   pinMode(trigPin, OUTPUT); //wire to digital 9 
   pinMode(echoPin, INPUT);   //wire to digital 10
  delay(1500); 

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  
  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
 */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}

void loop() {
  ArduinoCloud.update();
  // Your code here 
  long duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration=pulseIn(echoPin, HIGH);
  distance = (duration/2)/29.1;
  Serial.print(distance);
  Serial.println("CM");
  delay(10);

 if((distance<=10))
  {
    
   digitalWrite(led, HIGH);
   digitalWrite(led, true);
}
  else if(distance>10)
 {
   digitalWrite(led, LOW);
   digitalWrite(led, false);
  }
  
}



/*
  Since Led is READ_WRITE variable, onLedChange() is
  executed every time a new value is received from IoT Cloud.
*/
void onLedChange()  {
  Serial.print("Led status changed:");
  Serial.println(led);
}

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