6. Input & Output device¶
Objective: To complete the assignments on Input & Output Devices by testing various types of input and output electronics using the ESP32 Kids IoT STEM Microcontroller with the Arduino IDE.
Hardware Devices Used
Output Devices¶
An output device is hardware that receives data from a source (such as a computer or microcontroller) and converts it into a usable form. Output devices are categorized based on the type of data they output as follows:
Output Device Type | Description | Examples |
---|---|---|
Audio Output Devices | Convert data into sound. | Speakers, Buzzers, Headphones |
Visual Output Devices | Display data as text, images, or videos. | Monitors/Displays, LEDs, LCD/OLED Screens |
Physical Output Devices | Produce mechanical or physical actions. | Motors, Printers, Actuators |
Output Device1: 130DC Fan Motor¶
The 130 DC Fan Motor is a compact, efficient 12V DC motor commonly used in small fans and various applications. The term “130” refers to the motor’s size, indicating a small, lightweight design ideal for portable and space-constrained devices. Known for low power consumption and durability, it uses a brush and commutator system to convert DC power into mechanical motion.
With adjustable speed control, the 130 DC fan motor is ideal for applications where compact size, efficiency, and low power usage are essential.
↪ Running a Fan Motor¶
This code controls the speed and direction of a 130 DC fan motor using an H-Bridge (a commonly used circuit for controlling the direction of motors). The control is done via an Arduino board, with the motor’s speed managed through PWM (Pulse Width Modulation) and its direction controlled by two digital pins. The motor gradually accelerates, runs at full speed, decelerates, and also runs in reverse with the same behavior.
Code Results:¶
Code Overview:¶
This code simulates a motor running through a controlled fade-in and fade-out effect in both forward and reverse directions.
- The motor accelerates gradually in the forward direction, holds at maximum speed, then decelerates.
- After a pause, the motor runs in reverse with the same behavior (gradually accelerating and decelerating).
- The motor is stopped after each cycle and paused before starting the next one.
- The motor is controlled using Pulse Width Modulation (PWM) for speed regulation and direction pins for forward/reverse motion.
Code:¶
// Pin definitions
#define MOTOR_PWM_PIN 12 // PWM pin to control motor speed (ENA) [Pin 12]
#define MOTOR_DIR1_PIN 13 // Input 1 for motor forward direction (IN1) [Pin 13]
#define MOTOR_DIR2_PIN 14 // Input 2 for motor reverse direction (IN2) [Pin 14]
// Speed settings (0-255)
int motorSpeed = 0;
int minSpeed = 50; // Starting at a low speed for smooth motor startup
int maxSpeed = 200; // Maximum motor speed (between 0-255)
int inc = 20; // Speed increment per step
void setup() {
// Set motor control pins as outputs
pinMode(MOTOR_PWM_PIN, OUTPUT);
pinMode(MOTOR_DIR1_PIN, OUTPUT);
pinMode(MOTOR_DIR2_PIN, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
Serial.println("130 DC Fan Motor Control Initialized");
}
void loop() {
// Fade from low to slightly higher speed (increase speed)
for (motorSpeed = minSpeed; motorSpeed <= maxSpeed; motorSpeed += inc) {
controlMotor(motorSpeed, true); // Run forward
delay(100); // Wait a little to see the change in speed
}
// Hold at maximum speed for 2 seconds
delay(2000);
// Gradually reduce speed back to low (decrease speed)
for (motorSpeed = maxSpeed; motorSpeed >= minSpeed; motorSpeed -= inc) {
controlMotor(motorSpeed, true); // Run forward
delay(100); // Wait a little to see the change in speed
}
// Pause motor for 2 seconds before reversing
stopMotor();
delay(2000);
// Fade from low to high speed again, but in reverse direction
for (motorSpeed = minSpeed; motorSpeed <= maxSpeed; motorSpeed += inc) {
controlMotor(motorSpeed, false); // Run reverse
delay(100); // Wait a little to see the change in speed
}
// Hold at maximum reverse speed for 2 seconds
delay(2000);
// Gradually reduce speed back to low (decrease speed) in reverse direction
for (motorSpeed = maxSpeed; motorSpeed >= minSpeed; motorSpeed -= inc) {
controlMotor(motorSpeed, false); // Run reverse
delay(100); // Wait a little to see the change in speed
}
// Pause motor for 2 seconds before the next cycle
stopMotor();
delay(2000);
}
// Function to control the motor speed and direction
void controlMotor(int speed, bool forward) {
analogWrite(MOTOR_PWM_PIN, speed); // Set motor speed (PWM signal)
if (forward) {
digitalWrite(MOTOR_DIR1_PIN, HIGH); // Motor rotates forward
digitalWrite(MOTOR_DIR2_PIN, LOW);
} else {
digitalWrite(MOTOR_DIR1_PIN, LOW); // Motor rotates reverse
digitalWrite(MOTOR_DIR2_PIN, HIGH);
}
}
// Function to stop the motor
void stopMotor() {
digitalWrite(MOTOR_DIR1_PIN, LOW); // Stop the motor by disabling direction pins
digitalWrite(MOTOR_DIR2_PIN, LOW);
analogWrite(MOTOR_PWM_PIN, 0); // Set PWM to 0 to stop the motor
}
Output Device2: A-Buzzer¶
Buzzer Control with ESP32
A buzzer converts electrical energy into sound using a piezoelectric crystal that vibrates when an alternating current is applied. It is typically controlled by generating a square wave at a specific frequency, often with a microcontroller.
To control a buzzer with an ESP32, connect it to a digital pin. By toggling the pin between high and low states at a set frequency, the buzzer produces sound.
↪Simple On and Off Buzzer delay¶
Code Results:¶
Code Overview:¶
- This simple Arduino code is used to control a buzzer connected to pin 26. It makes the buzzer turn on and off in a 1-second interval, creating a regular on/off sound pattern.
- The buzzer is turned on for 1 second, then off for 1 second, and this cycle repeats indefinitely. The code uses the digitalWrite() function to control the buzzer and delay() to set the timing of each action.
Code:¶
const int buzzerPin = 26; // Pin connected to the buzzer
void setup() {
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
}
void loop() {
digitalWrite(buzzerPin, HIGH); // Turn the buzzer on
delay(1000); // Wait for 1 second
digitalWrite(buzzerPin, LOW); // Turn the buzzer off
delay(1000); // Wait for 1 second
}
↪Heartbeat Simulation Buzzer Code¶
Code Results:¶
Code Overview:¶
This code is an effective way to simulate a variable heartbeat sound using an Arduino and a buzzer, with randomized characteristics to make the heartbeat sound more natural and less repetitive.
- Simulated heartbeat pattern: The program simulates a heartbeat sound by generating a tone at 1000 Hz for a random duration between 80 ms and 120 ms followed by a random pause between 200 ms and 400 ms.
- Repeat: This pattern repeats 5 times (5 “thumps”), and after the 5th beat, the program waits for 1 second before starting the cycle again.
- The randomness of the duration of each heartbeat and the pause between beats makes the sound feel more natural and irregular, like a real heartbeat.
Key Points:¶
- Tone Frequency: The tone is generated at a fixed frequency of 1000 Hz for each heartbeat.
- Randomization: Both the duration of the tone and the pause are randomized to create a more lifelike, variable heartbeat sound.
- Repetition: The heartbeat sound is repeated 5 times in each cycle, and there’s a longer pause after each cycle.
Code :¶
const int buzzerPin = 26; // Pin connected to the buzzer
void setup() {
// No setup needed for tone
}
void loop() {
// Simulate a variable heartbeat sound
for (int i = 0; i < 5; i++) { // Repeat the heartbeat pattern 5 times
int duration = random(80, 120); // Random duration for the heartbeat thump
int pause = random(200, 400); // Random pause duration
tone(buzzerPin, 1000); // Play a tone at 1000 Hz
delay(duration); // Short beep
noTone(buzzerPin); // Stop the tone
delay(pause); // Pause between beats
}
// Longer pause before repeating the heartbeat pattern
delay(1000);
}
Output Device3: RGB LED¶
An RGB LED is a module that can produce virtually any color by combining the three primary additive colors: red, green, and blue. The basic design of an RGB LED consists of three separate light-emitting diodes (LEDs), each representing one of the primary colors, all encased together under a clear protective lens.
↪RGB LED - Color Change¶
Code Results:¶
Code Overview:¶
The code generates random color values and sets the brightness of the RGB LED accordingly, continuously changing its color at 500 ms intervals.
- When the program starts, it initializes the pins for the RGB LED in the
setup()
function. - In the
loop()
, it continuously: - Generates three random values for Red, Green, and Blue intensities.
- Sets the RGB LED color to these random values using PWM control (
analogWrite()
).analogWrite()
is used to set the brightness levels for each color channel (red, green, blue). - Waits for 500 milliseconds before generating a new color.
- This process repeats indefinitely, causing the RGB LED to constantly change colors at random.
Key Concepts:¶
- PWM (Pulse Width Modulation): This technique is used to simulate varying levels of voltage (and thus brightness) by rapidly switching the pins on and off at a high frequency. The
analogWrite()
function is used to send PWM signals to the RGB LED. - Random Color Generation: By using the
random(0, 256)
function, the code creates random values for each of the three color components (Red, Green, and Blue), resulting in random colors. - Delay Function: The
delay(500)
function pauses the program for 500 milliseconds, allowing time for the RGB LED to display the current color before changing again.
Code:¶
// Define the pins for the RGB LED
const int redPin = 12; // Pin connected to the red leg
const int greenPin = 13; // Pin connected to the green leg
const int bluePin = 14; // Pin connected to the blue leg
void setup() {
// Set the RGB LED pins as outputs
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Generate random colors
int redValue = random(0, 256); // Random value for red (0-255)
int greenValue = random(0, 256); // Random value for green (0-255)
int blueValue = random(0, 256); // Random value for blue (0-255)
// Set the RGB LED to the random color
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
// Wait for a short period before changing the color
delay(500); // Adjust the delay for faster or slower color changes
}
Input Devices¶
Input devices are hardware components that allow users to interact with a system by sending data or commands. These devices capture information from the user or the environment and convert it into a format that the system can process.
Common Types of Input Devices:
-
Keyboard: For inputting text and commands.
-
Mouse: For pointing and interacting with the screen.
-
Touchscreen: For direct interaction with content on the screen.
-
Microphone: For capturing audio.
-
Camera: For capturing visual data.
-
Sensors: For collecting physical data like temperature, pressure, and motion.
Input Device1: Potentiometer¶
A potentiometer is a three-terminal variable resistor used to adjust voltage levels in electronic circuits. It consists of a resistive element and a movable contact (wiper) that changes the resistance. Commonly found in applications like volume controls and tuning circuits, it allows users to fine-tune electronic signals by varying the output voltage based on the wiper’s position.
↪Potentiometer Input with ESP32¶
This code reads the value from a potentiometer connected to pin 4 of the ESP32 microcontroller.
Code Results:¶
Code Overview:¶
In the setup() function, serial communication is initialized at a baud rate of 9600. The loop() function continuously reads the analog value from the potentiometer, which ranges from 0 to 1023, and sends the value to the serial monitor for display. A 500-millisecond delay between readings helps regulate the output frequency, making it useful for monitoring real-time user input.
This setup is ideal for projects that need to track the adjustment of a potentiometer or gather user input data.
Code:¶
const int potPin = 4; // Pin connected to the potentiometer
void setup() {
Serial.begin(9600); // Start the Serial communication at 9600 baud rate
}
void loop() {
int potValue = analogRead(potPin); // Read the potentiometer value (0-1023)
// Print the potentiometer value to the Serial Monitor
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
delay(500); // Wait for half a second before the next reading
}
Input Device2: Film Pressure Sensor¶
A film pressure sensor is a flexible sensor that detects pressure changes by measuring variations in resistance, capacitance, or voltage. It is commonly used in applications such as touchscreens, pressure mapping, and medical devices due to its sensitivity and lightweight design.
↪Film Pressure Sensor Input with ESP32¶
This code reads the value from a Film Pressure Sensor connected to pin 4 of the ESP32 microcontroller.
Code Results:¶
As I press the Film Pressure Sensor, the values on the serial monitor decrease from 400 to lower readings.
Code Overview:¶
This code continuously reads the pressure sensor’s value from the ESP32 and prints it to the Serial Monitor. The value is updated every 500 milliseconds, providing a simple way to monitor pressure changes detected by the Film Pressure Sensor.
Key Concepts:¶
- Sensor Pin: The Film Pressure Sensor is connected to pin 4 of the ESP32.
- Analog Read:
analogRead(pressurePin)
reads the pressure value (0-4095). - Serial Communication:
Serial.begin(9600)
sends data to the Serial Monitor. - Printing Values: The sensor value is displayed using
Serial.print()
andSerial.println()
. - Delay:
delay(500)
introduces a 500ms pause between readings.
Code:¶
// Define the pin where the Film Pressure Sensor is connected
const int pressurePin = 4;
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
}
void loop() {
// Read the analog value from the Film Pressure Sensor (0 to 4095)
int pressureValue = analogRead(pressurePin);
// Print the sensor value to the Serial Monitor
Serial.print("Pressure Sensor Value: ");
Serial.println(pressureValue);
// Add a small delay for better readability
delay(500); // 500 ms delay
}
An Input & An Output¶
↪1.Potentiometer + RGB LED¶
This code reads the value from a potentiometer connected to pin 4 and adjusts the color of an LED connected to pin 12 using PWM (Pulse Width Modulation).
Code Results:¶
Code Overview:¶
- In the setup() function, the LED pin is set as an output, and serial communication is initialized for debugging.
- The loop() function continuously:
- Reads the analog value from the potentiometer (ranging from 0 to 1023).
- Maps this value to a range suitable for controlling the LED brightness (0 to 255).
- Adjusts the LED brightness using the analogWrite() function.
- Prints both the potentiometer value and LED brightness to the Serial Monitor for debugging.
- Waits for 100 milliseconds before repeating.
This setup allows real-time control of the LED brightness based on the potentiometer’s position.
Code:¶
const int potPin = 4; // Pin connected to the potentiometer (analog input pin A0)
const int ledPin = 12; // Pin connected to the LED (PWM pin)
void setup() {
// Set the LED pin as output
pinMode(ledPin, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the potentiometer value (range 0 to 1023)
int potValue = analogRead(potPin);
// Map the potentiometer value (0-1023) to a range of 0-255 for PWM
int ledBrightness = map(potValue, 0, 1023, 0, 255);
// Output the brightness value to the LED using PWM
analogWrite(ledPin, ledBrightness);
// Print the potentiometer value and LED brightness for debugging
Serial.print("Potentiometer Value: ");
Serial.print(potValue);
Serial.print(" LED Brightness: ");
Serial.println(ledBrightness);
// Wait a short time before reading again
delay(100);
}
↪2.Film pressure sensor & 130DC Fan Motor¶
This code controls a fan motor based on the readings from a pressure sensor. If the pressure sensor detects a value below a specified threshold, the fan will turn on. If the pressure exceeds the threshold, the fan will turn off.
Code Results:¶
Code Overview:¶
This Arduino code reads a pressure sensor and controls a fan motor based on the pressure. If the pressure is below a set threshold, the fan turns on. If the pressure exceeds the threshold, the fan turns off. The pressure value is also printed to the Serial Monitor for monitoring.
Components:¶
- Pressure Sensor: The sensor connected to analog pin 4 reads pressure values.
- Fan Motor: The fan is controlled through digital pin 27. It turns on or off based on the pressure reading.
- Arduino Core Library:
#include <Arduino.h>
is the core library for Arduino sketches and provides essential functions likepinMode
,analogRead
, anddigitalWrite
.
Code:¶
#include <Arduino.h>
const int sensorPin = 4; // Analog pin connected to the pressure sensor
const int fanPin = 27; // Digital pin connected to the fan motor
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(fanPin, OUTPUT); // Set fan pin as output
}
void loop() {
int sensorValue = analogRead(sensorPin); // Read sensor value
// Map sensor value to a pressure range (adjust as needed)
float pressure = map(sensorValue, 0, 1023, 0, 100);
// Check if pressure exceeds a threshold (adjust threshold as needed)
if (pressure < 300) { // Example: Turn on fan when pressure exceeds a threshold
digitalWrite(fanPin, HIGH); // Turn on the fan
} else {
digitalWrite(fanPin, LOW); // Turn off the fan
}
// Serial output (optional)
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println(" units");
delay(100); // Delay between readings
}