Mechatronics LAB
Published © GPL3+

Taking Actions Based on Conditions Arduino And MicroPython

In this section, we explore how to execute specific blocks of code based on conditions in your ESP32 projects. This capability is essential

BeginnerProtip-60 minutes18
Taking Actions Based on Conditions Arduino And MicroPython

Things used in this project

Hardware components

ESP32
×1
Pushbutton switch
×1
LED
×1

Story

Read more

Schematics

2_10_structuring_code_into_functional_blocks_with_functions_AwscwJDq9V.png

Code

Arduino code

Arduino
const int LED_BUILTIN = 13;  // Built-in LED pin on ESP32 (adjust if needed)
const int inputPin = 17;    // Define the input pin connected to a button or sensor

void setup()
{
 pinMode(LED_BUILTIN, OUTPUT);     // declare LED pin as output
 pinMode(inputPin, INPUT_PULLUP);  // declare pushbutton pin as input with internal pull-up resistor
}

void loop()
{
 int val = digitalRead(inputPin);  // read input value
 if (val == LOW)                   // Input is LOW when the button is pressed
 {
   digitalWrite(LED_BUILTIN, HIGH); // turn LED on if switch is pressed
 }
 else
 {
   digitalWrite(LED_BUILTIN, LOW);  // turn LED off if switch is not pressed
 }
}

Micropython Code

Python
from machine import Pin
import time

input_pin = Pin(2, Pin.IN)         # choose the input pin (for a pushbutton)
led_builtin = Pin(3, Pin.OUT)      # built-in LED pin

while True:
   val = input_pin.value()        # read input value
   if val == 0:                   # Input is 0 when the button is pressed
       led_builtin.on()           # turn LED on if switch is pressed
   else:
       led_builtin.off()          # turn LED off if switch is not pressed
   time.sleep(0.1)                # slight delay for stability

Credits

Mechatronics LAB
75 projects • 47 followers
I am Sarful , I am a Mechatronics Engineer & also a teacher I am Interested in the evolution of technology in the automation industry .
Contact

Comments

Please log in or sign up to comment.