My first (kind of) arduino project

March 2024

In my fourth semester in Mechanical engineering degree, I took a mechatronic class. Mechatronic is discipline where you basiclly combine mechanical engineering, electrical engineering and computer programming.

So I decided to learn embbeded system programming using a microcontroller. The most popular microcontroller for student is Arduino. The reason Arduino is so popular becasue it is a lot easier to program because the Abstraction that come with the Arduino IDE and the programming language. It also affordable.

I built my first arduino project using sensor Ultrasonic HC-SR04 and a couple of LEDs. My goal is to make a program where the microcontroller receive a data from a sensor (HC-SR04) and give an output based on the data.

Here is how the project look like

Arduino and ultrasonic sensor

Figure 1. Hardware

Before I programmed the arduino, I need to plug the wire and the component first, and here is how the schematic of the project. I designed the schematic using TinkerCad.

TinkerCAD wiring diagram

Figure 2. Wiring Diagram

After I done with the wiring then time to jump right into the code.

int trig = 9;
int echo = 10;
long duration, cm;
 
int8_t LED1 = 8;
int8_t LED2 = 7;
int8_t LED3 = 6;
int8_t LED4 = 5;
 
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
}

As you can see in the code above, first we need to setup variable for LED and the sensor and "activated" the variable in setup function. I also start a serial communication for debuggin purpose.

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  cm = (duration/2) / 29.1;
 
  Serial.print(cm);
  Serial.println("cm");
 
  if (distance >= 20) {
    digitalWrite(LED1, HIGH);
  } else {
    digitalWrite(LED1, LOW);
  }
 
  if (distance < 10) {
    digitalWrite(LED2, HIGH);
  } else {
    digitalWrite(LED2, LOW);
  }
 
  if (distance < 20 && distance >= 10) {
    digitalWrite(LED3, HIGH);
  } else {
    digitalWrite(LED3, LOW);
  }
 
  Serial.println(distance);
  delay(250);
}

After we are done we the setup, then program the logic inside the loop function. The program work first by receiving input from the sensor about how far an object from the sensor is, after we got the data, then we turn on an LED based on the distance of the object in front of the sensor.

If the object is more than 20 cm away from the sensor green LED is turn on.

If the object is less than 20 cm but at the same time more than 10 cm from the sensor yellow LED is turn on.

Lastly, if the object less than 10 cm away from the sensor red LED is turn on.