No Trespassing demo with laser and photoresistor then sending data to RTW

In this tutorial I will show you how to connect your ultrasonic range sensor to ESP32 displaying the data though serial monitor.I will be using the HC-SR04 ultrasonic sensor, which is a module that measures the distance from an object using sonar. It works by sending out a high pulse and calculating how long it takes before it returns.


1 x ESP32 OLED

1 x Photoresistor KeyS

1 x Laser KeyS (Red Laser)

7 x Wire


The Laser has 3 pins which includes Vcc, Gnd, Trig and Echo and the photo resistor has 3 pins also.


5V Vcc
Pin 32 A0


5V Vcc

The analog pin needs to be connected to a pin where you can do AnalogRead , and the reason i use the Pin 32 on my ESP32 is because you cannot use WIfi And analogRead at the same time on pins less then number 32 because those pins use the Wifi module. this may vary depending on what microcontroller you have.

Source Code

Start with defining the AnalogPin. After that you need to define the type of variables that will be used, which will be an int and you can just call it for what you want i will call it for int value. In setup() the serial monitor is initialized and set the analogpin to Input

In loop() you will just listen on the value the photoresistor gives you , if it gives you the value that corresponds to the value of the red laser then it means that the laser is detected. If you get any other value it means that something has «interrupted» the laser.
The value of the photoresistor will keep being printed in the serial monitor.
Then you can have an action f.example turning on a led light etc.

#include <Nornir_ESP32.h>
const int Detect = 32 ;// pin 36 for  sensor
// RTW config
const String host = "http://[domain][service]?objectID=[id number]&token=[your token]"
void setup() {

//define detect input pin
pinMode(Detect, INPUT);
//Paste Wifi Code here check Wifi post for the code
void loop() {
read photoresistor value 
int detected = analogRead(Detect);// 

/* Here if the value of the photoresistor
is under 1000 which is the value
of the red laser it will send
data to RTW that detected = true
Which is fine but if someone interrupts the laser
It will send Detected = false and you can do 
an action based no that. */
    if(detected < 1000){
      RTW_send_data(host, "DETECTED=true");
      RTW_send_data(host, "DETECTED=false");
      //Sound the alarm someone has trespassed
Related posts
IntegrationPostsThe Things Network

How we integrated an external service to RTW using Webhooks and PhP


Code used to connect to WIFI with Esp32 (Referenced as WifiCode)


Automatic trash can opener based on distance


Automatic adjust brightness according to how bright the environment is

Legg igjen en kommentar

Din e-postadresse vil ikke bli publisert. Obligatoriske felt er merket med *