Writing the Code


Introduction: 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 meter code!

Step 1: Introduction

In this lesson, you'll program the Arduino to figure out how warm the temperature sensor is, then light up the 3 LEDs like a bar graph. All three LEDs light up if you hand is really warm!

In the next lesson, you will learn how to change the sensitivity of the sensor so it works well for you.

Open up the Code Editor and let's get started!

  1. Open up the Code Editor window and continue to the next step.

Step 2: A Pair of Useful Constants

As usual, you will start off the code by creating some definitions.

Constants are similar to variables in that they allow you to uniquely name things in the program, but unlike variables they cannot change. Name the analog input for easy reference, and create another named constant to hold the baseline (or reference) temperature.

The baseline is how we configure the temperature sensor: For every 2 degrees above this baseline, an LED will turn on.

  1. Copy the code into the Code Editor: //define the constants const int sensorPin = A0; const float baselineTemp = 20.0; //20 degrees celsius, or room temperature
  2. The "int" datatype is used here to identify which pin the sensor is on. The temperature is being stored as a "float," or floating-point number. This type of number has a decimal point.
  3. You can change the baseline temperature later, if needed, to make the sensor work better for you and your friends.
  4. Continue to the next step.

Step 3: Initialize the Serial Port

In the setup() function, you’re going to use a new command, Serial.begin(). This opens up a connection between the Arduino and the computer, so you can see the values from the analog input on your computer screen.

The argument 9600 is the speed at which the Arduino will communicate, 9600 bits per second. You will use the Arduino IDE’s serial monitor to view the information you choose to send from your microcontroller.

The beginning of the setup() function is shown below.

  1. Copy the code into the Code Editor:

    void setup(){
    	//open a serial port

  2. Continue to the next step.

Step 4: Initialize the Digital Pins

Next up is a for() loop to set some pins as outputs. These are the LED pins. Instead of giving them unique names and typing out the pinMode() function for each one, you can use a for() loop to go through them all quickly. This is a handy trick if you have a large number of similar things you wish to iterate through in a program. Tell the for() loop to run through pins 2 to 4 sequentially.

In the code pictured below notice that the pin modes, INPUT and OUTPUT are color-coded.

  1. Copy the code into the Code Editor, including comments:
    	//start with pin 2. Add 1 and repeat the loop.
    	for (int pinNumber = 2; pinNumber < 5; pinNumber++)
    		pinMode(pinNumber, OUTPUT);
    		digitalWrite(pinNumber, LOW);
  2. The above code starts by setting pin 2 as an output pin and giving it a value of LOW. Then it increases the pinNumber to 3 and starts again. The for() loop keeps repeating, adding 1 to the pinNumber each time (using the ++ operator) as long as the pinNumber is under 5.
  3. The last bracket } that you add is not part of the for loop: it is used to end the setup() function.
  4. Continue to the next step.
  5. Stuck? HINT: See arduino.cc/for to get more information about "for loops."

Step 5: Read the Temperature Sensor

In the loop() function, you’ll use a local variable named sensorVal to store the reading from your sensor. To get the value from the sensor, you call a function called analogRead().

analogRead() takes one argument: what pin it should take a voltage reading on. The input data that the analog pin A0 interprets will be a number between 0 and 1023.

  1. Copy the code into the Code Editor:
    //loop  void loop(){ 
    	int sensorVal = analogRead(sensorPin);
  2. A "local variable" is defined and used within one of the functions (loop(), for example) in the program. A "global variable" would be used for the entire program.
  3. Continue to the next step.

Step 6: Send Temperature Values to the Computer

The function Serial.print() sends information from the Arduino to a connected computer. You will see this information in your serial monitor. If you give Serial.print() an argument in quotation marks, it will print out the text you typed. If you give it a variable as an argument, it will print out the value of that variable.

  1. Copy the code into the Code Editor:
    	Serial.print("Sensor Value: "); 
  2. The text that appears in the serial monitor will look like this, with the text and sensor value in the same line. Sensor Value: 153
  3. Continue to the next step.

Step 7: Convert Sensor Reading to Voltage

With a little math, it’s possible to figure out what the real voltage on the pin is. The voltage will be a value between 0 and 5 volts, and it will have a fractional part (for example, it might be 2.5 volts), so you’ll need to store it inside a "float" variable.

Create a variable named voltage to hold this number. We'll simply re-scale the 0-1023 number to a voltage on a 0-5 volt scale. Divide sensorVal by 1024.0 and multiply by 5.0.

Like you did with the sensor value, you’ll print the voltage value to the serial monitor.

  1. Copy the code, including comments, into the Code Editor:
    	//convert the ADC reading to voltage 
    	float voltage = (sensorVal/1024.0)*5.0;  
    	//print new value to serial monitor 
    	Serial.print(", Volts: "); 
  2. Including the data collected in the previous step, the information in the serial monitor will look like this:
    Sensor Value: 153, Volts: 0.75
  3. Continue to the next step.
  4. Stuck? HINT: When doing mathematical operations in Arduino IDE, use * for multiplication, and / for division. Remember that the order of operations matters!

Step 8: Convert Voltage to Temperature

If you examine the sensor’s datasheet, there is information about the range of the output voltage. Datasheets are like manuals for electronic components. They are written by engineers, for other engineers.

The datasheet for this sensor explains that every 10 millivolts of change from the sensor is equivalent to a temperature change of 1 degree Celsius. It also says that the sensor can read temperatures below 0 degrees. Because of this, you’ll need to create an offset for values below freezing (0 degrees C).

If you take the voltage, subtract 0.5, and multiply by 100, you get the accurate temperature in degrees Celsius. Store this new number in a floating point (float) variable called temperature.

You will print the real temperature to the serial monitor, too.

  1. Copy the code into the Code Editor:
    	//convert the voltage to temperature in degrees
    	float temperature = (voltage - .5)*100; 
    	Serial.print(", degrees C: "); 
  2. Including the previous two steps, the serial output will look like this:
    Sensor Value: 153, Volts: 0.75, degrees C: 24.7
  3. Since the temperature variable is the last thing you're going to be printing out in this loop, you're going to use a slightly different command: Serial.println(). This command will create a new line in the serial monitor after it sends the value, making the data easier to read. The string of data in the serial monitor will look like this:
    Sensor Value: 153, Volts: 0.75, degrees C: 24.7  
    Sensor Value: 153, Volts: 0.75, degrees C: 24.7  
    Sensor Value: 155, Volts: 0.76, degrees C: 25.6
  4. Continue to the next step.
  5. Stuck?


    In the previous step, notice that the sensorVal is always an integer. We defined this variable as datatype int. On the other hand, voltage and temperature are "floating point" numbers, so they can be expressed as a decimal.

Step 9: Turn Off LEDS for a Low Temperature

With the real temperature, you can set up an if()...else statement to light the LEDs. Using the baseline temperature as a starting point, you’ll turn on one LED on for every 2 degrees of temperature increase above that baseline. You’re going to be looking for a range of values as you move through the temperature scale.

Start by turning all of the LEDs off if the temperature is below the baseline.

  1. Copy the code to the Code Editor, including comments:
    	if(temperature < baselineTemp){ 
    		//temperature is below baseline 
    		digitalWrite(2, LOW); 
    		digitalWrite(3, LOW); 
    		digitalWrite(4, LOW); 
  2. Recall that the baseline temperature is currently set to 20 degrees Celsius. You can change this later, if needed!
  3. Continue to the next step.

Step 10: Turn on One LED for a Low Temperature

We want one LED to turn on if the temperature is at a low value - between 22 and 24 degrees Celsius.

The && operator means “and”, in a logical sense. You can check for multiple conditions.

In pseudocode the commands sound like this: “if the temperature is 2 degrees greater than the baseline, AND it is less than 4 degrees above the baseline, then turn on the first LED.”

  1. Copy the code into the Code Editor:
    //low temperature 
    	else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){  
    		digitalWrite(2, HIGH); 
    		digitalWrite(3, LOW); 
    		digitalWrite(4, LOW); 
  2. When you have a sequence of multiple if() statements, you need to use the else if() command.
  3. Continue to the next step.

Step 11: Turn on Two LEDs for a Medium Temperature

We want two LEDs to turn on if the temperature is at a medium value - between 24 and 26 degrees Celsius.

If the temperature is between two and four degrees above the baseline, this block of code turns on the LEDs at digital pins 2 and 3.

  1. Copy the code into the Code Editor:

    	//medium temperature 
    	else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){ 
    		digitalWrite(2, HIGH); 
    		digitalWrite(3, HIGH); 
    		digitalWrite(4, LOW); 

  2. Continue to the next step.

Step 12: Turn on Three LEDs for a High Temperature

Now let's turn on all three LEDs if the temperature is above 26 degrees C, or 6 degrees above the baseline.

The Analog-to-Digital Converter can only read so fast, so you should put a small delay at the very end of your loop(). If you read from it too frequently, your values will appear erratic.

  1. Copy the code into the Code Editor:

    	//high temperature 
    	else if(temperature >= baselineTemp+6){ 
    		digitalWrite(2, HIGH); 
    		digitalWrite(3, HIGH); 
    		digitalWrite(4, HIGH); 

  2. Don't forget to include the last curly bracket. This closes the loop() function!

  3. This is the end of the program! Continue to the next step.

Step 13: Use It! (simulator)

Now try uploading the code to the Arduino in the Workplane.

  1. Compile and upload the code by clicking the "Upload & Run" button in the simulator. The simulation will automatically start.
  2. Change the temperature by clicking the on the temperature sensor and moving the slider back and forth. What is the range of possible temperatures? (see hint.)
  3. Next, click the serial monitor icon. You should see a stream of values coming out, formatted like this: Sensor: 137, Volts: .67, degrees C: 17
  4. Continue to the next step.
  5. Stuck? HINT: In the simulator, the temperature sensor can respond to temperatures between -40 and 125 degrees C.

Step 14: Use It! (Arduino Kit)

If you are using the Arduino kit, plug in your board and compile and upload the program. The sensor will respond to your skin temperature.

  1. On your breadboard, try squeezing the temperature sensor between your fingers, and see if the LED bar graph changes.
  2. Like you did in the simulator, you can open up the serial monitor and watch the change in the sensor input, voltage, and temperature.
  3. It's ok if you don't see a change in the bar graph yet. Continue to the next step to learn how to configure the sensor!

Next Lesson:Configuring the Sensor



    • Make it Move Contest

      Make it Move Contest
    • Woodworking Contest

      Woodworking Contest
    • Microcontroller Contest

      Microcontroller Contest

    We have a be nice policy.
    Please be positive and constructive.