Skip to content

5. Input and Output device

This week I worked on input and output devices.
Input devices are used to send data to a computer or microcontroller. They allow users to provide information and commands to the system.
Examples for inputs: microphone, mouse and keyboard.

Output devices receive data from a computer or microcontroller and present it to the user or another system. They convert electronic signals into perceptible forms.
Examples for output: monitor, printer, speakers.

Testing output

I tried to connect several outputs to a microcontroller and turn them on using a button. I used thonny while working, python language.
components used:
1 microcontroller
2 buzzer
3 LED
4 RGB “three light”
5 button
6 Fan
7 wires for connection

I used this code

from machine import Pin, Timer
import time

# Pin definitions
button_pin = 27
led_pin = 26
rgb_pins = [12, 13, 14]
motor_pins = [2]
buzzer_pins = [17, 18, 19]

# Setup the button as an input with pull-up resistor
button = Pin(button_pin, Pin.IN, Pin.PULL_UP)

# Setup the LED as an output
led = Pin(led_pin, Pin.OUT)

# Setup RGB LEDs as outputs
rgb_leds = [Pin(pin, Pin.OUT) for pin in rgb_pins]

# Setup motor as outputs
motor = [Pin(pin, Pin.OUT) for pin in motor_pins]

# Setup buzzer as outputs
buzzer = [Pin(pin, Pin.OUT) for pin in buzzer_pins]

# RGB LED colors (common cathode configuration, 0 means LED is on)
COLORS = [
    (1, 1, 1),   # off (all pins high)
    (0, 1, 1),   # red (R pin low)
    (1, 0, 1),   # green (G pin low)
    (1, 1, 0),   # blue (B pin low)
    (0, 0, 1),   # yellow (R and G pins low)
    (1, 0, 0),   # cyan (G and B pins low)
    (0, 1, 0),   # purple (R and B pins low)
    (0, 0, 0)    # white (all pins low)
]

# Initialize state
current_color_index = 0

# Timer for color change every 2 seconds
color_timer = Timer(-1)

# Function to change RGB LED color
def change_color(timer):
    global current_color_index
    # Turn off current color
    set_rgb_led(COLORS[current_color_index])
    current_color_index = (current_color_index + 1) % len(COLORS)
    # Turn on new color
    set_rgb_led(COLORS[current_color_index])

# Function to set RGB LED color
def set_rgb_led(rgb_state):
    for pin, state in zip(rgb_pins, rgb_state):
        rgb_leds[pin - 12].value(state)

# Initialize RGB LED to off state
set_rgb_led(COLORS[current_color_index])

# Start timer to change color every 2 seconds
color_timer.init(period=2000, mode=Timer.PERIODIC, callback=change_color)

# Main loop
while True:
    # Check if the button is pressed (button is active low due to pull-up)
    if button.value() == 0:  # Button is pressed
        # Turn on the LED
        led.on()

        # Activate motor
        for pin in motor:
            pin.on()

        # Activate buzzer
        for pin in buzzer:
            pin.on()

        # Wait for 2 seconds (change RGB LEDs during this time)
        time.sleep(2)

        # Turn off the motor and buzzer after 2 seconds
        for pin in motor:
            pin.off()
        for pin in buzzer:
            pin.off()

    else:
        # Turn off the LED if the button is not pressed
        led.off()

    # Add a small delay to debounce and prevent rapid toggling
    time.sleep(0.1)

Final result

Motion detector test

Components used:

1 Bread board

2 Wires

3 RGB LED

4 Motion Detector

5 Microcontroller

We connected everything together and used Arduino for the coding.
The code makes the RGB goes green if there is no motion detected, but when it senses motion it will change to red.

The code used

// Define the pin where the PIR sensor is connected
const int pirSensor = 3;

// Define the pins for the RGB LED
const int redPin = 4;
const int greenPin = 5;
const int bluePin = 6;

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

  // Set the PIR sensor pin as input
  pinMode(pirSensor, INPUT);

  // Set the RGB LED pins as output
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

  // Ensure the RGB LED is initially off
  digitalWrite(redPin, LOW);
  digitalWrite(greenPin, LOW);
  digitalWrite(bluePin, LOW);
}

void loop() {
  // Read the sensor value
  int sensorValue = digitalRead(pirSensor);

  if (sensorValue == HIGH) {
    // Motion detected
    Serial.println("Motion detected!");

    // Turn on the red LED and turn off the green LED
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
    digitalWrite(bluePin, LOW); // Ensure blue is off
  } else {
    // No motion detected
    Serial.println("No motion detected.");

    // Turn on the green LED and turn off the red LED
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
    digitalWrite(bluePin, LOW); // Ensure blue is off
  }

  // Delay for a moment to avoid spamming the serial monitor
  delay(1000);
}

Touch sensor test

Components used
1 Bread Board

2 microcontroller

3 touch sensor

4 RGB LED

5 Wires

the code is used to make the LED goes green if there is no one touching the sensor, and blue when it senses a touch.

This is the code i used

// Define the pin where the touch sensor is connected
const int touchSensorPin = 7;

// Define the pins for the LEDs
const int led1Pin = 1;  // For when touch sensor is triggered
const int led2Pin = 6;  // For when touch sensor is not triggered

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

  // Set the touch sensor pin as input
  pinMode(touchSensorPin, INPUT);

  // Set the LED pins as output
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);

  // Ensure all LEDs are initially off
  digitalWrite(led1Pin, LOW);
  digitalWrite(led2Pin, LOW);
}

void loop() {
  // Read the state of the touch sensor
  int touchState = digitalRead(touchSensorPin);

  if (touchState == HIGH) {
    // Touch sensor is triggered
    Serial.println("Touch detected!");

    // Turn on LED1 (pin 1)
    digitalWrite(led1Pin, HIGH);

    // Ensure LED2 (pin 6) is off
    digitalWrite(led2Pin, LOW);
  } else {
    // No touch detected
    // Uncomment the line below if you want to print when no touch is detected
    // Serial.println("No touch detected.");

    // Turn on LED2 (pin 6)
    digitalWrite(led2Pin, HIGH);

    // Ensure LED1 (pin 1) is off
    digitalWrite(led1Pin, LOW);
  }

  // Add a small delay to debounce and reduce sensor reading frequency
  delay(100);
}

Group Project Progress

We were able to make few tests for the hot’n’cold game;
The Idea is to make a main body hidden somewhere, and trackers kept with the players; it shows them how far or close they are from the main body.

Code used

 ## 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 

<iframe src="https://drive.google.com/file/d/1Qpz3UOxIZcjp-n1m-LxQQspQPjxgcuD7/preview" width="640" height="480" allow="autoplay"></iframe>


## programming Esp01

Last update: August 1, 2024