top of page

Blog 2: Arduino Programing

  • amuhsin23
  • Dec 7, 2024
  • 11 min read

Updated: Dec 8, 2024

(Some images are not loading properly)


WELCOME BACK!!!!!šŸ„³šŸŽ‰


Welcome to the chaotic adventure where I tryĀ to code! šŸ˜… As you'll see in this blog, coding is like my nemesis, but I had to do it for this post. So, to be honest, around 90% of the codeĀ you’ll see here wasn’t even written by me — it’s all thanks to my trusty sidekick, ChatGPT! šŸ¤–šŸ’»

I spent an embarrassingly long time just trying to understand the code šŸ¤¦ā€ā™‚ļø so I could explain it properly. But hey, I tried my best, and that's what counts, right? šŸ˜… So, without further ado, Lettuce 🄬 begin!

Task 1: using an LDR as an input device


Firstly we need to know what a LDR is. A Light Dependent Resistor (LDR), as the name suggests, is a resistor that changes its resistance based on how much light hits it. Imagine an LDR as a magical flower 🌺. When the sun shines brightly šŸŒž, the flower opens its petals wide, soaking up the light and allowing energy to flow easily through it (low resistance). But when it's dark šŸŒ‘, the flower closes its petals, making it harder for electricity to pass through (high resistance). the LDR adjusts its resistance to the amount of light it receives just like the flower.





For this task, I used a video tutorialĀ šŸ“ŗ to help me with the wiring setup. Once the wiring was sorted, I just asked ChatGPT: "Can you please write code to interface an LDR to an Arduino board?" 🧐

After that, it was just a matter of putting together the circuit šŸ› ļø and recording the setup, which you can see below šŸ‘‡:



Video demonstration of the code


Code Used

const int LDR_PIN = A0;

void setup() {
  Serial.begin(9600);
  Serial.println("LDR Signal Measurement Started...");
}

void loop() {
  int ldrValue = analogRead(LDR_PIN);
  Serial.print("LDR Value: ");
  Serial.println(ldrValue);
  delay(500);
}


Code

Explanation

const int LDR_PIN = A0;

Defines a constant integer LDR_PINĀ to specify the analog pin (A0) connected to the Light Dependent Resistor (LDR).

void setup() {

Declares the setupĀ function, which runs once at the beginning of the program.

Serial.begin(9600);

Initializes serial communication at a baud rate of 9600 for communication with the Serial Monitor.

Serial.println("...");

Sends a message ("LDR Signal Measurement Started...") to the Serial Monitor for debugging or status indication.

void loop() {

Declares the loopĀ function, which runs repeatedly after setupĀ finishes.

int ldrValue = analogRead(LDR_PIN);

Reads the analog voltage from the LDR connected to pin LDR_PINĀ and stores it in ldrValue.

Serial.print("LDR Value: ");

Prints a text label "LDR Value: " to the Serial Monitor.

Serial.println(ldrValue);

Prints the numeric value of ldrValueĀ on the Serial Monitor on a new line.

delay(500);

Pauses the execution of the program for 500 milliseconds for better readability of the output.

So in summary a lower LDR valueĀ corresponds to higher light intensityĀ (less resistance in the LDR), while a higher valueĀ indicates lower light intensityĀ (higher resistance in the LDR). The LDR values can be observed in the Serial Monitor.

Task 2: using LEDs as an output device


For this task, I programmed an Arduino to control three LEDs: Red 🟄, Green 🟩, and Yellow 🟨, lighting them up in a cool sequence! 🚦 But wait, there’s more! I also made a push button šŸ•¹ļø that could start and stop the action whenever I wanted. Pretty neat, right? šŸ˜„


To get started, I followed a super handy video tutorial šŸŽ„. It provided the basic framework for making the LEDs work their magic, and I even downloaded the example code from the video’s description. (Yay for resources! šŸ™Œ)

The challenge? The original code didn’t include the push button functionality. 😱 But no worries! Thanks to my prior Arduino programming knowledge šŸ’”, I added in the missing push button feature myself. Now, with a press of a button, the LED sequence can start and stop like a pro! šŸŽ‰



However, I did face a bit of a struggle when connecting everything šŸ› ļø. It was a bit confusing at first šŸ˜µā€šŸ’«. I thought I was all done and ready to go, but when I ran the code, I realized I forgot to add resistorsĀ to the LEDs! 😱 This led to the chaos you can see in the video. šŸŽ„šŸ”Œ

The corrected circuit with resistorsĀ added, and the full code that ties it all together is below. šŸ’”šŸ‘‡


Ā Ā Video demonstration of the code working



Code


int LED1 = 13;
int LED2 = 12;
int LED3 = 11;
int buttonPin = 2;
bool isRunning = false;

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(buttonPin) == LOW) {
    delay(50);
    if (digitalRead(buttonPin) == LOW) {
      isRunning = !isRunning;
      while (digitalRead(buttonPin) == LOW);
    }
  }

  if (isRunning) {
    digitalWrite(LED1, HIGH);
    delay(200);
    digitalWrite(LED2, HIGH);
    delay(200);
    digitalWrite(LED3, HIGH);
    delay(200);
    digitalWrite(LED1, LOW);
    delay(300);
    digitalWrite(LED2, LOW);
    delay(300);
    digitalWrite(LED3, LOW);
    delay(300);
  }
}

Code section

Explanation

int LED1 = 13;
int LED2 = 12;
int LED3 = 11;
int buttonPin = 2;

Declares LED pins and buttonPin, assigns them to respective pin numbers for the LEDs and button.

bool isRunning = false;

Initializes a boolean flag isRunningĀ to track whether the LED sequence is running.

void setup() 

Defines the setup()Ā function, executed once when the program

pinMode(LED1, OUTPUT); pinMode(buttonPin, INPUT_PULLUP);

Configures pin modes for LEDs (output) and button (input with internal pull-up resistor).

void loop()

Defines the loop()Ā function, which runs repeatedly.

if (digitalRead(buttonPin) == LOW) { delay(50); isRunning = !isRunning; while (digitalRead(buttonPin) == LOW); }

Detects button press, debounces it, toggles isRunningĀ state, and waits for button release.

if (isRunning)

Checks if the LED sequence should run based on the isRunningĀ state.

digitalWrite(LED1, HIGH); delay(200); digitalWrite(LED2, HIGH); digitalWrite(LED3, HIGH); digitalWrite(LED1, LOW); digitalWrite(LED2, LOW); digitalWrite(LED3, LOW); delay(300);

Runs the LED sequence: turns LEDs on and off with delays for timing.

Honestly, though, this task ended up being pretty fun šŸŽ‰. I actually got to understand the codeĀ I was writing! It felt like I was getting the hang of things, and that made it all worthwhile. šŸ˜Ž

Moving on we have our Practical 2: Arduino Programming.

Practical 2: Arduino ProgrammingšŸ¤–šŸŽ¶


For Practical 2, we had to power our SHARK from ICPDĀ using a servoĀ to move its jaw and add some fun extras, like LED lightsĀ to make its eyes glow šŸ‘€šŸ’”. I volunteered to handle all the codingĀ šŸ–„ļø, while my awesome group focused on the aesthetics šŸŽØ and the connections between the ArduinoĀ and the shark 🦈. So, in this blog, I’ll be diving deep into the coding side of things!


I’ll be honest though šŸ˜…ā€”the code I wrote still confuses me! It’s like a giant puzzle 🧩, and I’m still trying to figure it out. Here’s the thing: an ArduinoĀ can be thought of as a brain with just one big brain cell 🧠. It’s powerful, but it can’t juggle too many tasks at once, because, well... it's just one brain cellĀ šŸ§ šŸ’„.

At first, I was fine because I only needed to do two tasks: move the servo and blink the LED. That worked like a charm! ✨ But when I tried to add a push buttonĀ to start and stop the action, things went south 🚧. The poor Arduino just couldn’t handle it! 😫

That’s when I turned to the Google Gemini APIĀ for help šŸ”šŸ’”. With a little bit of tinkering , I got the code to work.


But you know me, I’m a high achieverĀ šŸ’Ŗ, so I didn’t stop there. Oh no! I decided to include the buzzerĀ šŸŽ¶ to play a song while all the actions were happening. šŸŽµšŸ’„


Now for the music to be played šŸŽµ, you need to find a song online that’s ready to be played on an Arduino buzzer, or you can do what this video shows—converting the MIDI file of the song into Arduino code! šŸ˜Ž Just a quick tangent, but I had no idea what MIDI files were before this. But now? They are AMAZING! 🤯 Like, you can view and edit music, and they’ve been adopted so much that any music released recently will almost always have a MIDI file available online for you to mess with. šŸŽ¶ Anyway, back to coding! šŸ’»


So, now that I had my song of choice šŸŽ¼, I still needed to make it play with the code. And this part? Honestly, I don’t understand exactly how it works šŸ¤” because, as mentioned before, the Arduino is like a single brain cell 🧠 (well, actually, it's just a single core). So, running four tasks—moving the servo, blinking the LEDs, playing music, and turning on/off with the button press—is impossible šŸ˜…. However, I had an idea šŸ’”ā€”why not make the tasks run with the same input? Like, the servo moves to the beat of the music šŸŽµ and the lights blink in sync with the sound šŸ”†. I had no idea how to implement this though šŸ¤·ā€ā™‚ļø. But then, I just sent it to Google Gemini, and boom! It worked! šŸš€

I don’t know exactlyĀ how it works, so bear with me as I try to explain it below šŸ‘‡:

Here is the code below

#include <Servo.h>

#define BUZZER_PIN 8
#define BUTTON_PIN 2
#define LED_PIN 5
#define SERVO_PIN 9

Servo myservo;

int melody[] = {
  587, -4, 659, -4, 440, 4,
  659, -4, 740, -4, 880, 16, 784, 16, 740, 8,
  587, -4, 659, -4, 440, 2,
  440, 16, 440, 16, 494, 16, 587, 8, 587, 16,
  587, -4, 659, -4, 440, 4,
  659, -4, 740, -4, 880, 16, 784, 16, 740, 8,
  587, -4, 659, -4, 440, 2,
  440, 16, 440, 16, 494, 16, 587, 8, 587, 16,
  0, 4, 494, 8, 554, 8, 587, 8, 587, 8, 659, 8, 554, -8,
  494, 16, 440, 2, 0, 4,
  0, 8, 494, 8, 494, 8, 554, 8, 587, 8, 494, 4, 440, 8,
  880, 8, 0, 8, 880, 8, 659, -4, 0, 4,
  494, 8, 494, 8, 554, 8, 587, 8, 494, 8, 587, 8, 659, 8, 0, 8,
  0, 8, 554, 8, 494, 8, 440, -4, 0, 4,
  0, 8, 494, 8, 494, 8, 554, 8, 587, 8, 494, 8, 440, 4,
  659, 8, 659, 8, 659, 8, 740, 8, 659, 4, 0, 4,
  587, 2, 659, 8, 740, 8, 587, 8,
  659, 8, 659, 8, 659, 8, 740, 8, 659, 4, 440, 4,
  0, 2, 494, 8, 554, 8, 587, 8, 494, 8,
  0, 8, 659, 8, 740, 8, 659, -4, 440, 16, 494, 16, 587, 16, 494, 16,
  740, -8, 740, -8, 659, -4, 440, 16, 494, 16, 587, 16, 494, 16,
  659, -8, 659, -8, 587, -8, 554, 16, 494, -8, 440, 16, 494, 16, 587, 16, 494, 16,
  587, 4, 659, 8, 554, -8, 494, 16, 440, 8, 440, 8, 440, 8,
  659, 4, 587, 2, 440, 16, 494, 16, 587, 16, 494, 16,
  740, -8, 740, -8, 659, -4, 440, 16, 494, 16, 587, 16, 494, 16,
  880, 4, 554, 8, 587, -8, 554, 16, 494, 8, 440, 16, 494, 16, 587, 16, 494, 16,
  587, 4, 659, 8, 554, -8, 494, 16, 440, 4, 440, 8,
  659, 4, 587, 2, 0, 4
};

int tempo = 90;
int notes = sizeof(melody) / sizeof(melody[0]) / 2;
int currentNote = 0;
int wholenote = (60000 * 4) / tempo;
int noteDuration = 0;

bool isPlaying = true;
int servoPos = 20;
int servoTarget = 150;
int servoStep = 25;
bool servoDirection = true;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  myservo.attach(SERVO_PIN);
  myservo.write(servoPos);
}

void loop() {
  static bool lastButtonState = HIGH;
  bool buttonState = digitalRead(BUTTON_PIN);

  if (lastButtonState == HIGH && buttonState == LOW) {
    isPlaying = !isPlaying;
    if (!isPlaying) {
      noTone(BUZZER_PIN);
      digitalWrite(LED_PIN, LOW);
      myservo.write(20);
      currentNote = 0;
    }
  }
  lastButtonState = buttonState;

  if (isPlaying) {
    playMusic();
    moveServo();
  }
}

void playMusic() {
  if (currentNote < notes * 2) {
    int divider = melody[currentNote + 1];
    if (divider > 0) {
      noteDuration = wholenote / divider;
    } else {
      noteDuration = (wholenote / abs(divider)) * 1.5;
    }

    tone(BUZZER_PIN, melody[currentNote], noteDuration * 0.9);

    digitalWrite(LED_PIN, HIGH);
    delay(noteDuration / 2);
    digitalWrite(LED_PIN, LOW);

    delay(noteDuration * 0.1);
    noTone(BUZZER_PIN);
    currentNote += 2;
  } else {
    currentNote = 0;
  }
}

void moveServo() {
  if (servoDirection) {
    if (servoPos < servoTarget) {
      servoPos += servoStep;
      myservo.write(servoPos);
    } else {
      servoDirection = false;
    }
  } else {
    if (servoPos > 20) {
      servoPos -= servoStep;
      myservo.write(servoPos);
    } else {
      servoDirection = true;
    }
  }
  delay(10);
}


Code Segment

Explanation

#include <Servo.h>

Includes the Servo library to control the servo motor.

#define BUZZER_PIN 8, BUTTON_PIN 2, LED_PIN 5, SERVO_PIN 9;

Defines pins for the buzzer, button, LED, and servo motor.

Servo myservo;

Creates a ServoĀ object to control the servo motor.

int melody[] = {...};

Defines the melody notes and their durations for the buzzer.

int tempo = 90; int notes = sizeof(melody) / sizeof(melody[0]) / 2; int wholenote = (60000 * 4) / tempo;

Sets the tempo, calculates the number of notes in the melody, and the duration of a whole note.

void setup() {...}

Initializes pins, attaches the servo, and sets the initial servo position.

void loop() {...}

Main loop that checks the button state, plays music, and moves the servo based on isPlayingĀ state.

void playMusic() {...}

Function that plays the melody using the buzzer and synchronizes the LED blink.

void moveServo() {...}

Function to move the servo back and forth based on the servoDirectionĀ flag, controlling the servo position.

bool isPlaying = true; int servoPos = 20; int servoTarget = 150; int servoStep = 25; bool servoDirection = true;

Initializes variables for controlling music playback, servo position, and servo movement direction.

static bool lastButtonState = HIGH; bool buttonState = digitalRead(BUTTON_PIN); if (lastButtonState == HIGH && buttonState == LOW) {...}

Detects button press to toggle isPlayingĀ state, stop buzzer, LED, and servo if stopped, and resets note counter.

tone(BUZZER_PIN, melody[currentNote], noteDuration * 0.9); digitalWrite(LED_PIN, HIGH); delay(noteDuration / 2); digitalWrite(LED_PIN, LOW); delay(noteDuration * 0.1);

Plays a note, blinks the LED, and handles note timing.

myservo.write(servoPos); delay(10);

Moves the servo motor by adjusting its position and adds a short delay for smooth movement.


This code creates a system that plays a melody using a buzzer šŸ”Š while controlling a servo motor šŸ¤– and an LED šŸ’”. The melody consists of notes and rests with specified durations ā±, and the tempo ā° determines how fast the music is played. When the

system is running, the buzzer plays each note sequentially šŸŽ¶, the LED blinks in sync with the notes šŸ’”šŸŽµ, and the servo motor moves back and forth between two positions ā†”ļø. The button allows the user to start and stop the music šŸŽ¶ and the servo movement šŸ¤–. When the music is stopped āø, the buzzer stops playing šŸ›‘, the LED turns off šŸ’”āŒ, and the servo returns to its starting position šŸ. The servo moves incrementally, alternating its direction after reaching its target position ā†”ļø. The program continuously checks the button state šŸ”˜, plays the melody šŸŽ¼, and moves the servo in real-time! ⚔

(at least that's what ChatGPT saysšŸ’€šŸ’€šŸ’€)





Finally the video demonstration of the code working. It took so much time to get there but it was all worth it in the end. Also the code that is in this blog does not play the song in the video. If you want to know what song it it you will need to play the code on to your Arduino.


(Explaining my code to my teacher)


Well, now that the fun part is over, let’s dive into the learning reflection! šŸ“šāœØ


Learning Reflection 🌟


At the start of this project, I genuinely felt like coding just wasn’t for me. 😩 I’d look at a blank code editor and think, What am I even doing here?Ā But as I dug into this Arduino project, I realized something amazing: I CAN code!Ā šŸ§‘ā€šŸ’» Sure, it takes me longer than most people to figure things out, but the important part is that I canĀ do it. šŸ’Ŗ

In fact, writing this blog has been a whole journey in itself. I started it when the sun was rising šŸŒ…, and by the time I was done, it had already set šŸŒ‡. (Yes, that long—help šŸ˜­šŸ’€šŸ’€šŸ’€). But hey, at least I’ve made progress!

What stood out to me the most was how much room there is to grow. When I compared my code to what others have written, it was clear that mine was… let’s say a little rough around the edges. 😬 It gets the job done, but it’s far from efficient. Right now, my two main tools for improvement are either handing my code over to ChatGPT for optimization šŸ¤–āœØ or practicing more coding challenges until it starts to click. Both options seem like the way forward!

Looking Ahead šŸš€

Since my CA1 project will require more Arduino coding, I know I need to level up my skills. šŸ§ šŸ”§ This means diving into the vast world of Arduino tutorials, exploring libraries, and understanding how to write clean, efficient code. I plan to set aside time to:

  1. Tackle Coding Problems:Ā I’ll start small, solving simple problems to build my confidence, then work up to more complex ones. šŸ‘©ā€šŸ’»āœØ


  2. Analyze Other People’s Code:Ā By looking at how experienced coders structure their programs, I can pick up tips and tricks to improve mine. šŸ§šŸ’”



While I have a long way to go, I’m proud of the progress I’ve made so far. Coding might not come naturally to me, but with persistence (and a little help from technology), I can make it happen. šŸš€šŸ‘¾ Here’s to brighter days and cleaner code! 🌟



Anyway that's all from me byeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee


Comments


bottom of page