Introduction: Writing the Arduino Code

Picture of Writing the Arduino Code

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 Arduino code portion!

Step 1: Introduction

In this section you are going to write and save a very short Arduino program in Arduino IDE to start serial communication between the Arduino Uno board and the computer. Our version of the potentiometer circuit is in the Workplane, just for your reference.

Let's get started!

  1. Continue to the next step.

Step 2: Open Serial Communcation

Picture of Open Serial Communcation

In setup(), you’ll start serial communication, just as you did earlier when looking at the values from an attached sensor. The Processing program you write will have the same serial baud rate as your Arduino.

  1. Copy the code below into Arduino IDE. void setup(){ Serial.begin(9600); }

  2. Continue to the next step.

Step 3: Send the Sensor Value

Picture of Send the Sensor Value

In the loop() function, you’re going to read the analog pin A0 and use the Serial.write() command to send its value to the computer.

Serial.write() can only send a value between 0 and 255. To make sure you’re sending values that fit within that range, divide the analog reading by 4.

We also added a Serial.println() command so you can verify your code using the Arduino IDE serial monitor.

  1. Copy the code below into Arduino IDE. void loop(){ Serial.write(analogRead(A0)/4); Serial.println(analogRead(A0)/4); delay(1); }

  2. It's a good idea to add a short delay after this step. The analog to digital converter needs one millisecond to do its work.

  3. Continue to the next step.

Step 4: Upload and Test the Sketch

Picture of Upload and Test the Sketch

After finishing the code, compile your program and upload it to the Arduino Uno.

  1. Upload the code to your Arduino Uno board.
  2. You can open up the serial monitor and watch the data change as you turn the potentiometer. The first character in the line represents the raw serial data. The number next to it is the sensor value divided by 4 -- you should see that number range from 0 to 225.
  3. Once you are satisfied that the program works, you can set your Arduino Uno and breadboard aside while you work on the next step: writing the Processing code.
  4. Continue to the next lesson to write the Processing code.

Next Lesson:Writing the Processing Code

Comments

About This Instructable

211views

1favorite

License:

Bio: Circuit lessons for Tinkercad Circuits!
More by circuits:IntroductionProject 15: Hacking ButtonsProject 14: Tweak the Arduino Logo
Add instructable to: