Skip to content

5. Input & Output device

This week I worked on microcontrollers and tried different inputs and outputs.

Traffic Light

Output

RGB LED light which indicates for a traffic light and it has 3 pins for red, green and blue

Code

    from machine import Pin
    import time
    RLED =Pin(12,Pin.OUT)
    YLED =Pin(13,Pin.OUT)
    GLED =Pin(14,Pin.OUT)
    Fan=Pin(2,Pin.OUT)

    button = Pin(0, Pin.IN, Pin.PULL_UP)
    while True:
        RLED.value(1)
        time.sleep(2)
        YLED.value(1)
        time.sleep(2)
        RLED.value(0)
        YLED.value(0)
        GLED.value(1)
        time.sleep(2)
        GLED.value(0)
        YLED.value(1)
        time.sleep(2)
        YLED.value(0)

Result

Fan

Input

A rotary potentiometer is a type of adjustable resistor that uses a rotating shaft to change its resistance. It consists of a circular resistive element, a wiper that moves along this element, and three terminals: two connected to the ends of the resistive element and one to the wiper. By turning the shaft, the position of the wiper changes, varying the resistance between the terminals and thus adjusting the output voltage. Commonly used in applications like volume controls, light dimmers, and tuning devices, rotary potentiometers are valued for their simplicity and durability, though they can experience mechanical wear over time.

Output

A fan motor is an electric motor that powers a fan to create airflow, used in various applications such as household appliances, HVAC systems, and electronic cooling devices. It consists of a stator, rotor, and fan blades, with the stator generating a magnetic field that turns the rotor and attached blades to move air. Fan motors come in different types, including AC motors for household fans, DC motors for devices like computer fans, and brushless DC motors for efficiency and quiet operation. They are essential for cooling, ventilation, and maintaining optimal temperatures in a wide range of environments.

Code

    from machine import Pin, ADC, PWM
    import time

    # Set up the fan control pin with PWM for speed control
    fan = PWM(Pin(13), freq=1000)

    # Set up the potentiometer (ADC)
    pot = ADC(Pin(39))  # Adjust the pin number based on your board
    pot.atten(ADC.ATTN_11DB)  # Set the attenuation for full range (0-3.3V)
    pot.width(ADC.WIDTH_10BIT)  # Set the width to 10 bits (0-1023)

    while True:
        # Read the potentiometer value
        pot_value = pot.read()

        # Map the potentiometer value to the PWM duty cycle
        fan_duty = int((pot_value / 1023) * 1023)  # Scale the value to 0-1023

        # Set the fan speed
        fan.duty(fan_duty)

        # Small delay to avoid excessive CPU usage
        time.sleep(0.01)

Result

Door Bell

Input

A pushbutton is a mechanical switch that is activated by pressing it to make or break an electrical circuit, allowing users to control devices and functions. It typically consists of a button, housing, contacts, and a spring that returns the button to its original position. Pushbuttons can be normally open or normally closed and come in momentary or maintained types. They are widely used in consumer electronics, industrial controls, automotive applications, and home appliances due to their simplicity, reliability, and versatility, although they can experience mechanical wear over time.

Output

A buzzer is an electronic device that produces an audible sound or tone when activated, typically used for signaling or alert purposes. It operates by converting electrical energy into sound through mechanical, electromagnetic, or piezoelectric means. Commonly found in alarms, timers, and user interfaces, buzzers are essential for providing auditory feedback or warnings in various applications, including household appliances, automotive systems, and electronic gadgets. Buzzers are valued for their simplicity, reliability, and effectiveness in drawing attention.

Code

    from machine import Pin, PWM
    import time

    # Set up the buzzer pin with PWM for sound control
    buzzer = PWM(Pin(2), freq=1000)

    # Set up the button pin with a pull-up resistor
    button = Pin(0, Pin.IN, Pin.PULL_UP)

    # Debounce time in milliseconds
    debounce_time = 200
    last_button_press = 0

    # Function to play a tone
    def play_tone(frequency, duration):
        buzzer.freq(frequency)
        buzzer.duty(512)  # 50% duty cycle
        time.sleep(duration)
        buzzer.duty(0)  # Turn off the buzzer
        time.sleep(0.05)  # Short delay between notes

    # Function to play the Pink Panther theme
    def play_pink_panther_theme():
        notes = [
            (392, 0.4),  # G4
            (494, 0.4),  # B4
            (523, 0.4),  # C5
            (494, 0.4),  # B4
            (392, 0.4),  # G4
            (523, 0.4),  # C5
            (494, 0.4),  # B4
            (392, 0.4),  # G4
            (349, 0.4),  # F4
            (294, 0.4),  # D4
            (349, 0.4),  # F4
            (392, 0.4),  # G4
            (294, 0.4),  # D4
            (349, 0.4),  # F4
            (392, 0.4),  # G4
        ]

        for note in notes:
            play_tone(note[0], note[1])

    while True:
        # Read the button state
        button_state = button.value()

        # Check if the button is pressed (active low)
        if button_state == 0:
            # Check for debounce
            if (time.ticks_ms() - last_button_press) > debounce_time:
                # Play the Pink Panther theme
                play_pink_panther_theme()
                # Update the last button press time
                last_button_press = time.ticks_ms()

        # Small delay to avoid excessive CPU usage
        time.sleep(0.01)

Result

Motion Detection

Input

PIR Sensor

Output

RGB LED

Result

Wi-Fi Strength Measurement

Wi-Fi strength measurement refers to the process of determining the quality and reliability of a Wi-Fi signal at a particular location. This measurement is typically expressed in terms of signal strength, often represented in decibels relative to one milliwatt (dBm). It helps assess how well a Wi-Fi network can support data transmission and connectivity. Common methods to measure Wi-Fi strength include:

  • RSSI (Received Signal Strength Indicator): A metric provided by Wi-Fi adapters indicating the power level of the received signal.

  • dBm: A logarithmic measurement of signal strength; higher values (closer to 0 dBm) indicate stronger signals, while lower values (e.g., -90 dBm) indicate weaker signals.

Tools like Wi-Fi analyzers and signal strength meters on smartphones or laptops are commonly used for these measurements. Wi-Fi strength measurement is crucial for optimizing network performance, troubleshooting connectivity issues, and ensuring reliable wireless communication.

ESP32

Receiver Code

    #include <WiFi.h>

    // Replace with your access point credentials
    const char* ssid = "ReceiverESP32";
    const char* password = "receiverpassword";

    // IP and port of the Transmitter ESP32
    const char* transmitterIP = "192.168.1.100";
    const int transmitterPort = 12345;

    WiFiServer server(80);
    WiFiClient client;

    void setup() {
    Serial.begin(115200);

    // Start Wi-Fi in Access Point mode
    WiFi.softAP(ssid, password);
    Serial.println("Receiver ESP32 started as Access Point");

    // Start UDP client
    client.connect(transmitterIP, transmitterPort);
    if (client.connected()) {
        Serial.println("Connected to Transmitter ESP32");
    } else {
        Serial.println("Failed to connect to Transmitter ESP32");
    }
    }

    void loop() {
    int n = WiFi.scanNetworks(); // Scan for available networks

    if (n > 0) {
        for (int i = 0; i < n; i++) {
        String data = "SSID: " + WiFi.SSID(i) + " | RSSI: " + String(WiFi.RSSI(i));
        Serial.println(data);

        if (client.connected()) {
            client.println(data); // Send data to Transmitter ESP32
        }
        }
    } else {
        Serial.println("No networks found");
    }

    delay(z); // Delay between scans
    }

Transmitter Code

    #include <WiFi.h>

    const char* ssid = "TransmitterESP32";
    const char* password = "transmitterpassword";

    WiFiServer server(12345);

    void setup() {
    Serial.begin(115200);

    // Start Wi-Fi in Access Point mode
    WiFi.softAP(ssid, password);
    Serial.println("Transmitter ESP32 started as Access Point");

    // Start the server
    server.begin();
    Serial.println("Server started, waiting for connection...");
    }

    void loop() {
    WiFiClient client = server.available(); // Check for incoming clients

    if (client) {
        Serial.println("Client connected");

        while (client.connected()) {
        if (client.available()) {
            String line = client.readStringUntil('\n');
            Serial.println(line); // Print received data
        }
        }

        client.stop();
        Serial.println("Client disconnected");
    }
    }

Results

MKR1010 & LED

The code for the Arduino MKR 1010 includes two parts: one MKR 1010 configured as an access point (AP) and another as a client. The AP code sets up a Wi-Fi network with a specified SSID and password, allowing other devices to connect. The client code connects to this AP, measures the Wi-Fi signal strength (RSSI), and uses two LEDs to indicate signal strength: a red LED for strong signals and a blue LED for weak signals. The client continuously monitors the signal strength and updates the LED status accordingly, providing a visual representation of the Wi-Fi signal quality. Adjustments to the threshold values for weak and strong signals can be made based on the specific environment.

Access Point Code

    #include <SPI.h>
    #include <WiFiNINA.h>

    const char* ssid = "MKR1010_AP";
    const char* password = "12345678";

    void setup() {
    Serial.begin(9600);

    // Check for the WiFi module
    if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        while (true);
    }

    // Configure as Access Point
    Serial.print("Setting up Access Point: ");
    Serial.println(ssid);

    int status = WiFi.beginAP(ssid, password);

    if (status != WL_AP_LISTENING) {
        Serial.println("Creating Access Point failed!");
        while (true);
    }

    Serial.println("Access Point created successfully");
    }

    void loop() {
    // AP logic can be added here
    delay(1000);
    }

Client Code

    #include <SPI.h>
    #include <WiFiNINA.h>

    // Define LED pins
    const int blueLedPin = 6;
    const int redLedPin = 7;

    // Wi-Fi credentials
    const char* ssid = "MKR1010_AP";
    const char* password = "12345678";

    // Threshold for signal strength (dBm)
    const int weakThreshold = -70; // Adjust as needed
    const int strongThreshold = -50; // Adjust as needed

    void setup() {
    // Initialize serial communication
    Serial.begin(9600);

    // Initialize LED pins
    pinMode(blueLedPin, OUTPUT);
    pinMode(redLedPin, OUTPUT);

    // Connect to Wi-Fi
    Serial.println("Connecting to Wi-Fi...");
    WiFi.begin(ssid, password);

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to Wi-Fi");

    // Print the IP address
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
    }

    void loop() {
    // Measure Wi-Fi signal strength
    int32_t rssi = WiFi.RSSI();

    // Print signal strength to Serial Monitor
    Serial.print("Signal Strength (RSSI): ");
    Serial.println(rssi);

    // Control LEDs based on signal strength
    if (rssi >= strongThreshold) {
        // Strong signal
        digitalWrite(redLedPin, HIGH); // Red LED on
        digitalWrite(blueLedPin, LOW); // Blue LED off
    } else if (rssi <= weakThreshold) {
        // Weak signal
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, HIGH); // Blue LED on
    } else {
        // Intermediate signal strength
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, LOW); // Blue LED off
    }

    // Delay before the next measurement
    delay(1000);
    }

ESP32 & LED

Access Point Code

    #include <WiFi.h>

    const char* ssid = "ESP32_AP";
    const char* password = "12345678";

    void setup() {
    Serial.begin(115200);

    // Configure as Access Point
    Serial.print("Setting up Access Point: ");
    Serial.println(ssid);

    WiFi.softAP(ssid, password);

    Serial.println("Access Point created successfully");
    Serial.print("IP Address: ");
    Serial.println(WiFi.softAPIP());
    }

    void loop() {
    // AP logic can be added here
    delay(1000);
    }

Client Code

    #include <WiFi.h>

    // Define LED pins
    const int blueLedPin = 2; // GPIO2 for blue LED
    const int redLedPin = 4;  // GPIO4 for red LED

    // Wi-Fi credentials
    const char* ssid = "ESP32_AP";
    const char* password = "12345678";

    // Threshold for signal strength (dBm)
    const int weakThreshold = -70; // Adjust as needed
    const int strongThreshold = -50; // Adjust as needed

    void setup() {
    // Initialize serial communication
    Serial.begin(115200);

    // Initialize LED pins
    pinMode(blueLedPin, OUTPUT);
    pinMode(redLedPin, OUTPUT);

    // Connect to Wi-Fi
    Serial.println("Connecting to Wi-Fi...");
    WiFi.begin(ssid, password);

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to Wi-Fi");

    // Print the IP address
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
    }

    void loop() {
    // Measure Wi-Fi signal strength
    int32_t rssi = WiFi.RSSI();

    // Print signal strength to Serial Monitor
    Serial.print("Signal Strength (RSSI): ");
    Serial.println(rssi);

    // Control LEDs based on signal strength
    if (rssi >= strongThreshold) {
        // Strong signal
        digitalWrite(redLedPin, HIGH); // Red LED on
        digitalWrite(blueLedPin, LOW); // Blue LED off
    } else if (rssi <= weakThreshold) {
        // Weak signal
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, HIGH); // Blue LED on
    } else {
        // Intermediate signal strength
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, LOW); // Blue LED off
    }

    // Delay before the next measurement
    delay(1000);
    }

Result

Esp01

Install library, driver, and board for ESP8266

Access Point Code

    #include <ESP8266WiFi.h>

    const char* ssid = "ESP01_AP";
    const char* password = "12345678";

    void setup() {
    Serial.begin(115200);

    // Configure as Access Point
    Serial.print("Setting up Access Point: ");
    Serial.println(ssid);

    WiFi.mode(WIFI_AP);
    WiFi.softAP(ssid, password);

    Serial.println("Access Point created successfully");
    Serial.print("IP Address: ");
    Serial.println(WiFi.softAPIP());
    }

    void loop() {
    // AP logic can be added here
    delay(1000);
    }

Client Code

    #include <ESP8266WiFi.h>

    // Define LED pins (GPIO 0 and GPIO 2 are available on ESP-01)
    const int blueLedPin = 2; // GPIO2 for blue LED
    const int redLedPin = 0;  // GPIO0 for red LED

    // Wi-Fi credentials
    const char* ssid = "ESP01_AP";
    const char* password = "12345678";

    // Threshold for signal strength (dBm)
    const int weakThreshold = -70; // Adjust as needed
    const int strongThreshold = -50; // Adjust as needed

    void setup() {
    // Initialize serial communication
    Serial.begin(115200);

    // Initialize LED pins
    pinMode(blueLedPin, OUTPUT);
    pinMode(redLedPin, OUTPUT);

    // Connect to Wi-Fi
    Serial.println("Connecting to Wi-Fi...");
    WiFi.begin(ssid, password);

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to Wi-Fi");

    // Print the IP address
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
    }

    void loop() {
    // Measure Wi-Fi signal strength
    int32_t rssi = WiFi.RSSI();

    // Print signal strength to Serial Monitor
    Serial.print("Signal Strength (RSSI): ");
    Serial.println(rssi);

    // Control LEDs based on signal strength
    if (rssi >= strongThreshold) {
        // Strong signal
        digitalWrite(redLedPin, HIGH); // Red LED on
        digitalWrite(blueLedPin, LOW); // Blue LED off
    } else if (rssi <= weakThreshold) {
        // Weak signal
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, HIGH); // Blue LED on
    } else {
        // Intermediate signal strength
        digitalWrite(redLedPin, LOW);  // Red LED off
        digitalWrite(blueLedPin, LOW); // Blue LED off
    }

    // Delay before the next measurement
    delay(1000);
    }

Last update: August 4, 2024