Getting Started with Arduino! – Chapter Two

This is part of a series titled “Getting Started with Arduino!” – A tutorial on the Arduino microcontrollers. The first chapter is here.

I hope you have been enjoying these posts and learning and creating and making many things. Today’s post has several things: taking temperatures, sending data from the arduino back to your PC, opening a library, and some exercises that will help to consolidate your previous knowledge and help revise it.

Note – Using LCD screens has moved to Chapter 24.

First of all, we shall investigate another analogue sensor – a temperature sensor. As you can imagine, there are many applications for such a thing, from just telling you the current temperature, to an arduino-based thermostat control system. And it is much easier to create than most people would think – so get ready to impress some people!

Let’s say hello to the Analog Devices TMP36 Low-voltage temperature sensor:


Tiny, isn’t it? It looks just like a standard transitor (e.g. a BC548) due the use of the same TO-92 case style. The TMP36 is very simple in its use – looking at the flat face, pin 1 is for +5V supply (you can connect this to the 5V socket on your arduino), pin 2 is the output voltage (the reading), and pin three is ground/earth (connect this to the GND socket on your arduino). Furthermore, have a look at the data sheet, it is quite easy to read and informative. TMP36 data sheet

The TMP36 will return a voltage that is proportional to temperature. 10 mV for each degree Celsius, with a range of -40 to 125 degrees.

There isn’t any need for extra resistors or other components – this sensor must be the easiest to use out there. However there is one situation that requires some slight complexity – remote positioning of the sensor. It is all very well to have the sensor on your breadboard, but you might want it out the window, in your basement wine cellar, or in your chicken coop out back… As the voltage output from the sensor is quite low, it is susceptible to outside interference and signal loss. Therefore a small circuit needs to be with the sensor, and shielded cable between that circuit and the home base. For more information on long runs, see page fifteen of the data sheet.

At this point we’re going to have some mathematics come into the lesson – sorry about that. Looking again at page eight of the data sheet, it describes the output characteristics of the sensor. With our TMP36, the output voltages increases 10 millivolts for every degree Celsius increase; and that the output voltage for 25 degrees Celsius is 750 mV; and that there is an offset voltage of 400 mV. The offset voltage needs to be subtracted from the analogRead() result, however it is not without vain – having the offset voltage allows the sensor to return readings of below freezing without us having to fool about with negative numbers.

Quick note: A new type of variable. Up until now we have been using int for integers (whole numbers)… but now it is time for real numbers! These are floating point decimals, and in your sketches they are defined as float.

Now we already know how to measure an analogue voltage with our arduino using analogRead(), but we need to convert that figure into a meaningful result. Let’s look at that now…

analogRead() returns a value between 0 and 1023 – which relates to a voltage between 0 and 5V (5000 mV). It is easier on the mind to convert that to a voltage first, then manipulate it into temperature. So, our raw analogRead() result from the TMP36 multiplied by (5000/1024) will return the actual voltage [we’re working in millivolts, not volts] from the sensor. Now it’s easy – subtract 400 to remove the offset voltage; then divide it by 10 [remember that the output is 10 mV per degree Celsius]. Bingo! Then we have a result in degrees Celsius.

If you live in the Fahrenheit part of the world, you need to multiply the Celsius value by 1.8 and add 32.

Quick note: You may have seen in earlier sketches that we sent a value to the serial output in order for the arduino software to display it in the serial monitor box. Please note that you cannot use digital pins 0 or 1 if using serial commands. We used Serial.begin(9600); in the void setup(); part of the sketch. You can also send text to the serial monitor, using Serial.print(); and Serial.println();. For example, the following commands:

would create the following line in the serial monitor (assuming the value of temperature is 23.73):

The temperature is 23.73 degrees Celsius

and send a carriage return to start a new line. That is the difference between the Serial.print(); and Serial.println(); commands, the extra -ln creates a carriage return (that is, sends the cursor to the start of the next line. Did you notice the 2 in the Serial.print(); above? You can specify the number of decimal places for float variables; or if you are using an integer, you can specify the base of the number being displayed, such as DEC, HEX, OCT, BIN, BYTE – decimal, hexadecimal, octal, binary, or byte form. If you don’t use the second paramater of Serial.print();, it defaults to decimal numbers for integers, or two decimal places for floating-point variables.

Now let’s read some temperatures! All you need to do is connect the TMP36 up to the arduino board. pin 1 to 5v, pin 2 to analog 0, pin 3 to GND. Here is a shot of the board setup:


And here is the sketch:

And there’s nothing like a video, so here it is. The measurements start at room temperature, then an ice cube in a plastic bag is pushed against the TMP36 for a moment, them held between two fingers to warm up again…

Quick note: the while() command. Sometimes you want a sketch to wait for user input, or wait for a sensor to reach a certain state without the sketch moving forward. The solution to this problem is the use of the while() command. It can cause a section of a sketch to loop around until the expression in the while command becomes true.

For example:


Anyhow, back to the next exercise – it’s now your turn to make something!

Exercise 2.1

Recently the cost of energy has spiralled, and we need to be more frugal with our heating and cooling devices. Unfortunately some members of the family like to use the air conditioner or central heating when it is not really necessary; many arguments are caused by the need for the heating/cooling to be on or off. So we need an adjudicator that can sit on the lounge room shelf and tell us whether it’s ok to use the heating or cooling.

So, create a device  that tells us when it is ok to use the air conditioner, heater, or everything is fine. Perhaps three LEDs, or a single RGB LED. Red for turn on the heat, blue for turn on the air conditioner, and green or white for “You’re fine, you don’t need anything on”. You will need to define your own temperature levels. Living here in north-east Australia, I’m going to have the air conditioner on above 28 degrees C; and the heat can come on at 15 degrees C.

Hopefully you are thinking about the voltmeter we made in chapter one, that should give you a starting point. If not, go back now and have a look. Otherwise, hop to it…
Anyway, here is my board layout…
You will need:
  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Either three LEDs or an RGB LED
  • 3 x 560 ohm 0.25 W resistors. They are to reduce the current to protect the LEDs.
  • a breadboard and some connecting wire
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • a camera (optional) – to document your success!
And a sketch to solve the exercise:

And of course a video. For demonstration purposes, I have altered the values by making them very close, so it’s easier to show you the LEDs changing. The plastic bag used in the video is full of ice water.

Well that was interesting, I hope you enjoyed it and have some ideas on how to put temperature sensors to use. But now it is time to look at a library or two…
Quick note: As you know, there are several commands in the processing language to control your arduino and its thoughts. However, as time  goes on, people can write more commands and make them available for other arduino users. They do this by creating the software that allows the actual Atmel microcontroller interpret the author’s new commands. And these commands are contained in libraries. Furthermore, as Arduino is open-source, you can write your own libraries and publish them for the world (or keep ’em to yourself…) In the arduino IDE software, have a look at the Sketch>>Import Library… menu option. Also, check out here for more libraries! Now to put one to good use…

Update – LCDs were orginally explaned at this point, however they are now explained in their own article – chapter 24. Don’t forget to return to try out the examples and the rest of this chapter!
Exercise 2.2

This is our most complex project to date, but don’t let that put you off. You have learned and practised all the commands and hardware required for this exercise. You only need a little imagination and some time. Your task is to build a digital thermometer, with LCD readout. As well as displaying the current temperature, it can also remember and display on request the  minimum and maximum temperatures – all of which can be reset. Furthermore, the thermometer works in degrees C or F.

First of all, don’t worry about your hardware or sketch. Have a think about the flow of the operation, that is, what do you want it to do? For a start, it needs to constantly read the temperature from our TMP36 sensor. You can do that. Each reading will need to be compared against a minimum and maximum value. That’s just some decision-making and basic maths. You can do that. The user will need to press some buttons to display and reset stored data. You can do that – it’s just taking action if a digital input is high. I will leave the rest up to you.

So off you go!

You will need (this may vary depending on your design, but this is what we used):

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Water (you need to stay hydrated)
  • 2 x 10k 0.25 W resistors. They work with the buttons to the arduino
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • 2 little push buttons
  • a breadboard and some connecting wire
  • 16×2 character LCD module and a 10k linear potentiometer or trimpot (For LCD contrast)
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • a camera (optional) – to document your success!

For inspiration, here is a photo of my board layout:

… and a video clip of the digital thermometer in action.

And here is the sketch for my example – Exercise 2.2 sketch example. I hope you had fun, and learned something. Now it’s time for Chapter Three.


Have fun and keep checking into Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The following two tabs change content below.

John Boxall

Founder, owner and managing editor of

40 Responses to “Getting Started with Arduino! – Chapter Two”

  1. Ty Tower says:

    What happens if you feed the TMP36 ess than the expected 5V

    Most USB run arduinos are in fact only getting about 4.2V so is the 1023 calculation still valid?

    • John Boxall says:

      Thank you for your question. I just rebuilt example 2.1, and noted that my Arduino Duemilanove was giving exactly 5.00V to the TMP36, using either USB or a 9VDC plugpack. You had me worried that my sketch was incorrect a little there, so I also tried ladyada’s sketch from and the same temperature readings occured. Of course if you are giving your TMP36 less supply voltage, please adjust the calculations accordingly. Please let me know how you go. Cheers, John

  2. Josh says:

    It is important to note the associated overheads with using floating point numbers and maths on an 8 bit processor.

    The libraries involved use a lot of space and the functions are quite processor intensive.

    This is not so important when working on a smaller project like this, however as the project gets larger the program space becomes valuable.

    • John Boxall says:

      Thanks for your comment.
      This is true. I suppose there is the Arduino Mega for the larger projects. Hopefully over time people would evolve from Arduino to more suitable microcontroller systems.

  3. Saurabh says:

    I am experiencing the problem with Temperature reading.I am using LM35 instead of TMP36.The sketch gets uploaded but when I click Serial Monitor it hangs and gives me an error.It asks me to check the serial port I have chosen from the tools menu.
    Before carrying out this temperature program,other LED programs work smooothly giving no serial port problems.This specific sketch is giving problems.

    • John Boxall says:

      It is hard to say why this is happening. If you can upload sketches, your USB port is working, and the serial monitor should be selected to the same port. Also check your serial monitor speed is the same as your Serial.begin() speed in void setup().

  4. Saurabh says:

    Also please tell me how to ensure that serial monitor speed is the same as serial.begin(),because it has not been used in the sketch as per the book.

  5. Ed says:

    Love the arduino, and love the tutorials on your site. Keep ’em coming!


  6. James Craig says:

    Very good of you to post these tutorials. Very nicely done.

  7. Chinedu Koggu says:

    Dear John,
    I must commend your excellent site and the VERY impressive information and research that goes into putting up something like this for the benefit of most of us. Your site has inspired me to once again pick up electronics. My major challenge is the acquisition of the parts required for most of these projects – I am located in Nigeria and it is quite a challenge to order these parts from here. I cannot thank you enough for your kindness and sacrifice in putting up these series of projects over the course of time. I remain very grateful that you find the time to share this body of knowledge with us – THANK YOU SO VERY MUCH!

  8. Avi says:

    Hi John,
    I would say your blog is an excellent resource for people who want to learn hardware.

    I have a question though. I am trying to use the temperature sensor to read the soil temperature. I get how the circuitry of the sensor works and I understand to get the temperature I could make some sort of extension of wire that dips into soil and sends the temperature to the middle pin of tmp36. But I am not able to implement this. Could you please guide me on this by providing some rough schematic or just explain me how to make such an extension.


  9. Susan zr says:

    You are a magnificent tutor. So appreciate this site. Thank you. Thank toy.

  10. Rob M says:

    I’m interested in taking the temperature of a liquid (specifically, beer while it is being fermented), but I have some questions about how I should go about this.

    Can I simply connect a thermistor to my Arduino using 2-3 feet of wire, then waterpoof and submerge it? Will the readings be affected by either longer wiring or a related issue?

    Is this a good application for a thermocouple or would a thermistor work fine? Is ther any additional waterpoofing that is necessary to prevent shorting out the circuit?

    • John Boxall says:

      Hello Rob
      There are a few ways to go about it, depending on the sensor you want to use. Some people use a liquid thermocouple and a MAX6675 IC. After a bit of poking around I found someone who sells sensor tubes for the home brew community, which would house a DS18B20 temperature sensor nicely. This sensor also works well with Arduino. Have a look at:
      have fun

  11. Chandrachudh says:

    what if i need two analog inputs ?
    and i have to display both on my PC .

  12. hemu says:

    hello john,
    i want to know wht is the process bootloader atmega16 or other controller ??

  13. jorge says:

    se puede registrar desde la pc la temperetura de tres heladeras que contienen vacunas y escuchar una alarma de aviso cuando los valores de temperatura han variado de lo normal aconsejable para su conservacion, utilizando una placa arduino y sus componentes?

  14. Danny says:

    I can successfully use Serial.print(celsius, 2) with two decimal places but I am also sending my variable, float celsius to my lcd. I get my value plus 4 decimal places. I am confused about this and am wondering if you can comment on truncating the float variable to he lcd.?
    Thanks Danny

    • John Boxall says:

      Just tried it myself, e.g.
      float pi = 3.141592654;
      lcd.print(“pi: “);
      lcd.print(pi,3); // use three decimal places
      resulted in “pi: 3.142” on the LCD.
      Using the standard #include library

      • Danny says:

        john, thanks again.. I removed a section of my code that I used for smoothing my output from my sensor. I can’t say for sure, but there was some part of the code that was causing things to act funny. I removed it and retested and lcd.print(variable,x) is now working properly for proper signifcant figure after the decimal point.
        Your website is great! Thanks for all your work in helping us arduinians build somethng useful.

      • John Boxall says:

        Great news,thanks for letting me know.

  15. andrew rooney says:

    Hi, i have the circuit working pretty well and i am also printing the temp to the serial monitor, the problem is the green led is not lighting up in between the upper and lower limits. Its very strange, led is working perfectly.
    any ideas…

    thanks for the site by the way, its the best site i have found to learn arduino projects…really simple and useful.


    • John Boxall says:

      Hi Andrew
      Thank you for your positive comments. It’s hard to say why it doesn’t work without being there, for example please check the LED is wired correctly.

  16. Mansel says:

    I have a arduino UNO and when doing exercise 2 (displaying temperature in degrees C and degrees F) and my readings (in Degrees C) vary from -15 to -7 in a room that is more about 15 degrees C (positive).
    I have copied the code but i did originally have it in backwards and it recorded a temperature of 229 degrees C
    so i touched it and it was very hot so instintively i let go and unplugged it

  17. Xavi says:

    I tested your sketch but I think you make a little mistake. TMP36 goes from -40 degrees C (0mv) to +125 degrees C in steps of 10mV per degree. This means that 0 degrees is equal of 400mV. The offset voltage may be -400 to set the correct temperature.
    Is it right?

  18. RobR says:

    Thanks. I’m very much enjoying your tutorials and (hopefully) learning heaps.
    so (just because I know you want everything to be perfect) here’s the most minute correction…
    For the list of parts needed for Ex 2.1 you have listed everything but the actual sensor.
    Thanks again for doing these great tutorials.

  19. Alex says:

    Dear John, thank you very much for the great tutorials!
    By the way, a part of this article about adding libraries appears to have vanished…

  20. Koli says:

    Hello John,
    thanks to your interesting tutorial I started “sketching” yesterday. I have reached example 2 now(!), tried to program it on my own without looking at your version.
    The result:

    /* Temperaturmessung mit TMP36 */
    int temppin=0;
    float rawval;
    /* this made “int” leads to a wrong temperature value (no compiler error!) */
    float temperature;
    int Ub=4660; //in mV. Should be 5000mV, must be adjusted if not 😉
    int offset=500; //voltage of the TMP386 at 0°C in mV
    int scalefactor=10; //output scale factor of the TMP36 in mV/°C

    void setup()
    { Serial.begin(9600);

    void loop()
    { rawval=analogRead(temppin);
    /*here the sketch fails if rawval is of type “int”! */
    Serial.print (“Binaerwert :”);
    /* single quotes here lead to the output of strange numbers */
    Serial.println (rawval);
    Serial.print (“Temperature :”);
    Serial.print (temperature,1);
    Serial.println (” deg C”);

    … and afterwards I found some interesting details:

    – In my sketch the offset is 500 mV according to the data sheet of the TMP36 (750mV at 25°C and 10mV/°C –> 500mV at 0°C.) In my case this leads to reasonable temperature values. (I don’t talk about the necessary correction of the 5V value any more, you have already mentioned it.)

    – When I played around I tried the following obvious errors:
    – tempin=1.1; –> no error message from the compiler!
    – int tempin=0.1; –> dito
    – Serial.print (‘ the binary value is: ‘); –> outputs garbage, but again no error message!

    – Though the function analogRead produces is an integer value, declaring the variable rawval an int makes the sketch produce wrong temperature values.
    To my mind it is very, very hard to find such mistakes in arduino sketches. Who is so cruel (and lazy?) to write a compiler which leaves the novice totally alone with type mismatches and many breaches of the C syntax? Is there a hidden compiler switch to turn error checking on?
    You do everything to make Arduino programming fun! Thank you for that. It’s not your fault that it often is hell instead. But it is.
    If you know about a simple to use but better programming environment please tell all your friends.

    Best regards



Leave a Reply

Subscribe via email

Receive notifications of new posts by email.

The Arduino Book

Arduino Workshop

Für unsere deutschen Freunde

Dla naszych polskich przyjaciół ...

Australian Electronics!

Buy and support Silicon Chip - Australia's only Electronics Magazine.

Use of our content…

%d bloggers like this: