# Precision Temperature Measurement

In an effort to resume previous work [A, B, C, D] on developing a crystal oven for radio frequency transmitter / receiver stabilization purposes, the first step for me was to create a device to accurately measure and log temperature. I did this with common, cheap components, and the output is saved to the computer (over 1,000 readings a second). Briefly, I use a LM335 precision temperature sensor (\$0.70 on mouser) which outputs voltage with respect to temperature. It acts like a Zener diode where the breakdown voltage relates to temperature. 2.95V is 295K (Kelvin), which is 22ºC / 71ºF. Note that Kelvin is just ºC + 273.15 (the difference between freezing and absolute zero). My goal was to use the ADC of a microcontroller to measure the output. The problem is that my ADC (one of 6 built into the ATMEL ATMega8 microcontroller) has 10-bit resolution, reporting steps from 0-5V as values from 0-1024. Thus, each step represents 0.0049V (0.49ºC / 0.882ºF). While ~1ºF resolution might be acceptable for some temperature measurement or control applications, I want to see fractions of a degree because radio frequency crystal temperature stabilization is critical. Here’s a video overview.

This is the circuit came up with. My goal was to make it cheaply and what I had on hand. It could certainly be better (more stable, more precise, etc.) but this seems to be working nicely. The idea is that you set the gain (the ratio of R2/R1) to increase your desired resolution (so your 5V of ADC recording spans over just several ºF you’re interested in), then set your “base offset” temperature that will produce 0V. In my design, I adjusted so 0V was room temperature, and 5V (maximum) was body temperature. This way when I touched the sensor, I’d watch temperature rise and fall when I let go.  Component values are very non-critical. LM324 is powered 0V GND and +5V Vcc. I chose to keep things simple and use a single rail power supply. It is worth noting that I ended-up using a 3.5V Zener diode for the positive end of the potentiometer rather than 5V.  If your power supply is well regulated 5V will be no problem, but as I was powering this with USB I decided to go for some extra stability by using a Zener reference.

On the microcontroller side, analog-to-digital measurement is summed-up pretty well in the datasheet. There is a lot of good documentation on the internet about how to get reliable, stable measurements. Decoupling capacitors, reference voltages, etc etc. That’s outside the scope of today’s topic. In my case, the output of the ADC went into the ATMega8 ADC5 (PC5, pin 28). Decoupling capacitors were placed at ARef and AVcc, according to the datasheet. Microcontroller code is at the bottom of this post.

To get the values to the computer, I used the USART capability of my microcontroller and sent ADC readings (at a rate over 1,000 a second) over a USB adapter based on an FTDI FT232 chip. I got e-bay knock-off FTDI evaluation boards which come with a USB cable too (they’re about \$6, free shipping). Yeah, I could have done it cheaper, but this works effortlessly. I don’t use a crystal. I set fuse settings so the MCU runs at 8MHz, and thanks to the nifty online baud rate calculator determined I can use a variety of transfer speeds (up to 38400). At 1MHz (if DIV8 fuse bit is enabled) I’m limited to 4800 baud. Here’s the result, it’s me touching the sensor with my finger (heating it), then letting go.

Touching the temperature sensor with my finger, voltage rose exponentially. When removed, it decayed exponentially – a temperature RC circuit, with capacitance being the specific heat capacity of the sensor itself. Small amounts of jitter are expected because I’m powering the MCU from unregulated USB +5V.

I spent a while considering fancy ways to send the data (checksums, frame headers, error correction, etc.) but ended-up just sending it old fashioned ASCII characters. I used to care more about speed, but even sending ASCII it can send over a thousand ADC readings a second, which is plenty for me. I ended-up throttling down the output to 10/second because it was just too much to log comfortable for long recordings (like 24 hours). In retrospect, it would have made sense to catch all those numbers and do averaging on the on the PC side.

I keep my house around 70F at night when I’m there, and you can see the air conditioning kick on and off. In the morning the AC was turned off for the day, temperature rose, and when I got back home I turned the AC on and it started to drop again.

On the receive side, I have nifty Python with PySerial ready to catch data coming from the microcontroller. It’s decoded, turned to values, and every 1000 receives saves a numpy array as a NPY binary file. I run the project out of my google drive folder, so while I’m at work I can run the plotting program and it loads the NPY file and shows it – today it allowed me to realize that my roomate turned off the air conditioning after I left, because I saw the temperature rising mid-day. The above graph is temperature in my house for the last ~24 hours. That’s about it! Here’s some of the technical stuff.

AVR ATMega8 microcontroller code:

```#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

/*
8MHZ: 300,600,1200,2400,4800,9600,14400,19200,38400
1MHZ: 300,600,1200,2400,4800
*/
#define USART_BAUDRATE 38400
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

/*
{
PORTD^=255;
}
*/

void USART_Init(void){
UBRRL = BAUD_PRESCALE;
UBRRH = (BAUD_PRESCALE >> 8);
UCSRB = (1<<TXEN);
UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0); // 9N1
}

void USART_Transmit( unsigned char data ){
while ( !( UCSRA & (1<<UDRE)) );
UDR = data;
}

void sendNum(long unsigned int byte){
if (byte==0){
USART_Transmit(48);
}
while (byte){
USART_Transmit(byte%10+48);
byte-=byte%10;
byte/=10;
}

}

}

}

int main(void){
//DDRD=255;
USART_Init();
for(;;){
USART_Transmit('\n');
_delay_ms(100);
}
}```

Here is the Python code to receive the data and log it to disk:

```import serial, time
import numpy
ser = serial.Serial("COM15", 38400, timeout=100)

t1=time.time()
lines=0

data=[]

while True:

if "," in line:
line=line.split(",")
for i in range(len(line)):
line[i]=line[i][::-1]
else:
line=[line[::-1]]
temp=int(line[0])
lines+=1
data.append(temp)
print "#",
if lines%1000==999:
numpy.save("DATA.npy",data)
print
print line
print "%d lines in %.02f sec (%.02f vals/sec)"%(lines,
time.time()-t1,lines/(time.time()-t1))```

Here is the Python code to plot the data that has been saved:

```import numpy
import pylab

print data
data=data*.008 #convert to F
xs=numpy.arange(len(data))/9.95  #vals/sec
xs=xs/60.0# minutes
xs=xs/60.0# hours

pylab.plot(xs,data)
pylab.grid(alpha=.5)
pylab.axis([None,None,0*.008,1024*.008])
pylab.ylabel(r'\$\Delta\$ Fahrenheit')
pylab.xlabel("hours")
pylab.show()```

If you recreate this project, or have any questions, feel free to email me!

Scott W Harden

Scott Harden has had a lifelong passion for computer programming and electrical engineering, and recently has become interested in its relationship with biomolecular sciences. He has run a personal website since he was 15, which has changed names from HardenTechnologies.com, to KnightHacker.com, to ScottIsHot.com, to its current SWHarden.com. Scott has been in college for 10 years, with 3 more years to go. He has an AA in Biology (Valencia College), BS in Cell Biology (Union University), MS in Molecular Biology and Microbiology (University of Central Florida), and is currently in a combined DMD (doctor of dental medicine) / PhD (neuroscience) program through the collaboration of the College of Dentistry and College of Medicine (Interdisciplinary Program in Biomedical Science, IDP) at the University of Florida in Gainesville, Florida. In his spare time Scott builds small electrical devices (with an emphasis on radio frequency) and enjoys writing cross-platform open-source software.

1. ##### DM0

Great project.
Fantastic explanation.

2. ##### Nejm

I think in this case, better option will be rail-to-rail op-amp.

3. ##### ojh

Nice work, well documented.
If you’re not really interested in the absolute frequency of your oven crystal, you could probably just use a silicon diode as a temperature reference, and control the oven heater directly from there. See . o.

1. ##### ojh

clarification – I mean if you’re not interested in the crystals absolute frequency (f0), only that it’s terribly stable (df0/dt~0)

4. ##### Anonymous

I’m not super familiar with this but if the crystal responds to temperature changes, couldn’t you use *it* as the temperature sensor in you’re feedback loop?

1. ##### Scott Harden

Perhaps, but frequency response is parabolic. Frequency might fall as temperature increases or decreases significantly. It’s not a linear response, so it’s hard to use to measure frequency. Furthermore, to accurately measure frequency you need a stable time base to compare it to. Chicken and egg problem!

6. ##### smau

Nice project Scott!
Just two questions about the circuit:

The LM335 datasheet says that you can get a temperature error @25ºC of up to 1ºC when uncalibrated. Are you calibrating it to fit your specs? Because in that little explanation you make on the schematic it seems you’re considering the sensor as ideal, and you would lose all precision if the temp sensor isn’t doing its job accurately.

Aaand couldn’t you get the temp. sensor op amp out of the circuit? I mean, you could drive the rightmost op amp directly with the sensor output as it has a huge input impedance and won’t affect the measurement.

1. ##### Scott W Harden

Nice insight Samu. I am unconcerned with calibration, as I’m only interested in keeping relative temperature constant (and am less concerned with specifically what temperature it is).

I chose to use a buffer stage for the temperature sensor because I wanted to try things like using the output to directly power a transistor, voltage divider, and/or read voltage with a microcontroller. Since I was uncertain of my load demand, and had extra gates of the LM324 free, I went ahead and buffered it. Although for simple applications, you’re right, it’s likely unnecessary.

7. ##### Agen Poker

It’s laborious to seek out knowledgeable individuals on this matter, but you sound like you know what you’re talking about! Thanks

8. ##### Oswaldo Wengerd

You could certainly see your expertise within the paintings you write. The arena hopes for even more passionate writers like you who are not afraid to mention how they believe. All the time follow your heart. “Billy Almon has all of his inlaw and outlaws here this afternoon.” by Jerry Coleman.