Skip to content

5. Input & Output device

This Weeks’ Task:

1- Measure something: add a sensor to a microcontroller board and read it.

2- Add an output device to a microcontroller board and program it to do something.

3- Document your work

Input: Toch Sensor

Firstly trying to connect an input device with a microcontroller I have used a touch sensor, it’s coded so when you toch the sensor it’s writing “Touched!” on the screen as you can see through this video:

// Define the pin for the touch sensor
const int touchPin = 9; 

void setup() {
  // Start serial communication at 9600 baud rate
  Serial.begin(9600);

  // Set the touch pin as an input
  pinMode(touchPin, INPUT);
}

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

  // Print the sensor value to the Serial Monitor
  if (sensorValue == HIGH) {
    Serial.println("Touched!");
  } else {
    Serial.println("Not Touched");9
  }

  // Delay for a short period for stability
  delay(500);
}

Output: Servo Motor

Secondly trying to connect an output device with a microcontroller I have used a servo motor, it’s coded so the motor rotate from 0 degree to 180 degree and return repeatedly as you can see through this video:

#include <Arduino.h>
#include <Servo.h>

Servo myServo;  // Create a Servo object

// Define the pin for the servo
const int servoPin = 6; 

void setup() {
  myServo.attach(servoPin);  // Attach the servo control pin
}

void loop() {
  // Sweep from 0 to 180 degrees
  for (int pos = 0; pos <= 180; pos += 1) { // Move to the right
    myServo.write(pos);             // Tell servo to go to position in variable 'pos'
    delay(15);                       // Wait for the servo to reach the position
  }
  // Sweep back from 180 to 0 degrees
  for (int pos = 180; pos >= 0; pos -= 1) { // Move to the left
    myServo.write(pos);             // Tell servo to go to position in variable 'pos'
    delay(15);                       // Wait for the servo to reach the position
  }
}

Combining Servo Motor and Toch Sensor

#include <Servo.h>

// Create Servo object
Servo myServo;

// Define pins
const int touchPin = 9; // Pin for the touch sensor
const int servoPin = 8; // Pin for the servo motor

void setup() {
  myServo.attach(servoPin); // Attach the servo control pin
  pinMode(touchPin, INPUT); // Set touch pin as input
}

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

  // If the sensor is touched
  if (sensorValue == HIGH) {
    myServo.write(90); // Rotate the servo to 90 degrees
    delay(1000); // Hold position for 1 second
    myServo.write(0); // Rotate the servo back to 0 degrees
  }

  delay(100); // Short delay to avoid rapid firing
}

Last update: August 1, 2024