Task 3: Writing the Code


Once you’ve set up your project board, it’s time to write the code to make it work.

Here are some important steps to keep in mind:

Starting a New Sketch: Remember what we’ve learned in previous lessons. When you start writing a new sketch (that’s what we call a program in Arduino), what’s the first thing you need to do in the Arduino IDE? You’ll want to choose variable names that make sense, not just to you but also for what they’re supposed to do. Naming things right is important!

Pin Configuration: Next, you’ll need to tell the microcontroller (that’s the brain of your Arduino) which pins you’re using and whether they’ll be used as inputs or outputs. It’s like telling your Arduino which wires connect to what. This is crucial to make sure everything works as planned.

Buzzer Control: Think about how you can tell the program to turn the buzzer on and then off. You’ll need to figure out when the buzzer should be on and when it should be off.

Timing: Determine how long the buzzer should be on and off. This is like deciding how long a note should play in a song. It’s all about timing.

Verify and Upload: After you’ve written your code, verify it to check for errors. If there are any mistakes, fix them and verify again. Once the code is correct, upload it to your Arduino so it can run your program.

In a nutshell: name variables clearly, configure the pins, control the buzzer's behavior and timing, verify your code, and upload it to bring your project to life!


            // Lesson 7
            // Variables
            
            int buzzPin = 8;
            int dtOn = 500;
            int dtOff = 100;
            
            void setup() {
              // put your setup code here, to run once:
              pinMode(buzzPin, OUTPUT);
            }
            
            void loop() {
              //put your main code here, to run repeatedly:
              digitalWrite(buzzPin, HIGH);
              delay(dtOn);
              digitalWrite(buzzPin, LOW);
              delay(dtOff);
            }        

Did your buzzer buzz?

If everything went well and your buzzer is playing some beautiful music (even though it might sound a bit annoying), then it’s time to start experimenting!

If you ran into problems and are getting errors, don’t worry! Refer to Lesson 3 where we discuss what to do when your code is not working.

What happens when you change the delay times?

Is there a way to make different sounds?

Is there a way to tell the microcontroller what frequency to play without using delay times to alter the frequency?