Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Mechatronics LAB
Published © GPL3+

Arduino and MicroPython a Sequence of Statements ESP32

In this section, we delve into using loops to repeat a block of instructions in your ESP32 projects based on specific conditions. Loops such

BeginnerProtip26
Arduino and MicroPython a Sequence of Statements ESP32

Things used in this project

Hardware components

ESP32 Board
×1
LED
×1
Sensor/Potentiometer
×1
Resistors (if necessary)
×1
Breadboard (optional, for easier connections)
×1

Story

Read more

Schematics

2_10_structuring_code_into_functional_blocks_with_functions_r1giI3MEM1.png

Code

Arduino code

Arduino
const int sensorPin = 34; // analog input pin (change this to a valid ADC pin on ESP32)
const int LED_BUILTIN = 2; // built-in LED pin on ESP32 (adjust if needed)

void setup()
{
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT); // enable LED pin as output
}

void loop()
{
 while(analogRead(sensorPin) > 1000) // Adjust threshold value if needed
 {
   blink();    // call a function to turn an LED on and off
   Serial.print(" More Than 1000: ");
   Serial.println(analogRead(sensorPin));  // Print the sensor value
 }
 Serial.println(analogRead(sensorPin)); // this is not executed until after
                                        // the while loop finishes!!!
}

void blink()
{
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN, LOW);
  delay(100);
}

Micropython Code

Python
from machine import Pin, ADC
import time

sensorPin = ADC(Pin(34))  # Analog input pin (change this to a valid ADC pin on ESP32)
sensorPin.width(ADC.WIDTH_12BIT)  # Set the width of the ADC to 12 bits (0-4095)
sensorPin.atten(ADC.ATTN_11DB)  # Set the attenuation to measure up to 3.3V
LED_BUILTIN = Pin(2, Pin.OUT)  # Built-in LED pin on ESP32 (adjust if needed)

def setup():
   print("Setup complete")  # Initialization message

def loop():
   while sensorPin.read() > 1000:  # Adjust threshold value if needed
       blink()  # Call a function to turn an LED on and off
       print("More Than 1000: ", sensorPin.read())  # Print the sensor value
   print(sensorPin.read())  # This is not executed until after the while loop finishes!!!

def blink():
   LED_BUILTIN.value(1)
   time.sleep(0.1)
   LED_BUILTIN.value(0)
   time.sleep(0.1)

setup()

while True:
   loop()
   time.sleep(1)  # Small delay to prevent overloading the CPU

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.