Writing the Code

About: Learn electronics and Arduino with Tinkercad Circuits!

The following information is a single lesson in a larger project. Find more great projects here.

Return to Previous Lesson: Setting Up the Circuit

Lesson Overview:

Now we'll write our code!

Step 1: Getting Started

In this lesson you're going to program the Arduino to blink the flashlight on and off in the simulator, or alternate whatever output your own button controls.

The code is similar to the first project you made with the Arduino. In the next lesson we will challenge you to modify the program for another application: turning on a sound recording device. Let's get started!

  1. Continue to the next step.

Step 2: Name a Constant

Create a constant for the optocoupler control pin. We have it connected to pin 2, so the program is going to alternate between setting pin 2 HIGH and LOW.

  1. Copy the code into the Code Editor.

    const int optoPin = 2;

  2. Continue to the next step.

Step 3: Configure the Pin Direction

In the setup() function, set the optocoupler pin as an output.

  1. Copy the code below into the Code Editor.
    void setup() { 
    	pinMode(optoPin, OUTPUT); 
  2. This is the entire setup() function!
  3. Continue to the next step.

Step 4: Pull the Pin High and Low

The loop() function alternates between turning optoPin HIGH and LOW, blinking your output device. As written, the delay() function causes the switch to spend one second on and one second off.

  1. Copy the code below into the Code Editor.

    void loop() { 
    	digitalWrite(optoPin, HIGH);  
    	digitalWrite(optoPin, LOW);  

  2. Continue to the next step.

Step 5: Use It!

Now you are ready to try your hacked device!

  1. In the circuit simulator, press the "Upload & Run" button to start the simulation. The flashlight should blink on and off.

  2. If you are using your physical device, compile and load your Arduino code, then watch the output turn on and off.

Step 6: Review

Congratulations, you have successfully hacked a button!

Optocouplers are a great way to control devices because the two circuits involved are not electrically connected - instead they are connected by light inside the optocoupler. This means it's ok if your control circuit (our Arduino) and the hacked device (flashlight, for example) have completely different power requirements.

In the example in the simulator, the Arduino supplies 5 volts to the control circuit while the flashlight runs on a 9V battery.

  1. Continue to the next lesson for a project challenge.

Next Lesson:Next Lesson



    • Paper Contest

      Paper Contest
    • Organization Contest

      Organization Contest
    • Sweet Treats Challenge

      Sweet Treats Challenge