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:
Tackle Coding Problems:Ā Iāll start small, solving simple problems to build my confidence, then work up to more complex ones. š©āš»āØ
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