Skip to content

5. Input & output device

more practice on Thonny

Here we try to control the speed of the fan by the potentiometer

you can find the video and the code below

from machine import Pin, ADC, PWM
import time

# Setup ADC (Analog to Digital Converter) for reading potentiometer
pot = ADC(Pin(4))  # Create ADC object on GPIO4 (pin 4)
pot.width(ADC.WIDTH_10BIT)  # 10-bit resolution (0-1023)
pot.atten(ADC.ATTN_11DB)    # 11dB attenuation (for 3.3V range)

# Setup PWM for controlling motor speed
motor_pwm = PWM(Pin(27), freq=1000, duty=0)  # GPIO27 (pin 27), frequency 1000Hz, initially 0% duty cycle

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

    # Map potentiometer value (0-1023) to PWM duty cycle (0-1023)
    duty_cycle = pot_value

    # Update motor speed
    motor_pwm.duty(duty_cycle)

    # Print potentiometer value and duty cycle for debugging
    print("Potentiometer:", pot_value, "   Duty Cycle:", duty_cycle)

    time.sleep(0.1)  # Adjust delay as needed



Here we try to control the Traffic by touch

you can find the video and the code below

from machine import Pin
import time

# Define GPIO pins
pin_red = Pin(17, Pin.OUT)    # Red LED, GPIO17
pin_yellow = Pin(18, Pin.OUT) # Yellow LED, GPIO18
pin_green = Pin(19, Pin.OUT)  # Green LED, GPIO19
pin_sensor = Pin(26, Pin.IN, Pin.PULL_UP)  # Touch sensor, GPIO26 with internal pull-up resistor

# Main loop for traffic light control
while True:
    # Red light is on by default
    pin_red.on()
    pin_yellow.off()
    pin_green.off()

    # Wait for touch sensor press (active LOW)
    while pin_sensor.value() == 0:  # Wait while sensor is not pressed (active LOW)
        time.sleep(0.1)

    # When touch sensor is pressed, switch to yellow for 2 seconds
    pin_red.off()
    pin_yellow.on()
    pin_green.off()
    print("Traffic light switched to YELLOW")

    time.sleep(2)  # Yellow light stays on for 2 seconds

    # After 2 seconds, switch to green until touch sensor is released
    pin_yellow.off()
    pin_green.on()
    print("Traffic light switched to GREEN")

    while pin_sensor.value() == 1:  # Wait while sensor is pressed (active LOW)
        time.sleep(0.1)

    # When touch sensor is released, continue to next iteration (red light on)

Here we try to test the sensor motion

you can find the video and the code below

// 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);
}

Last update: August 5, 2024