The personal website of Scott W Harden
December 28th, 2010

Full-Auto Rapidfire Mouse Modification

I did this purely for the fun of it, and am aware there are many ways to accomplish the same thing. I was playing Counter Strike Source (you should buy it and play with me, name "swharden") and my fingers are really cold from the winter weather, and wondered if I could have a button help with the rapid firing of pistols. I mentioned it on the microphone, and one of the players ("{Ẋpli¢it} shadow") said I should go for it. Because it was a fun little project, I documented it so I could share it. Check out the cool photos and video!

There's a summary of the project in video form. Some details of the project are below...

Here you can see the original circuit board in the mouse. The microchip on the bottom right of the image seems to do the data processing, so I investigated it a bit and found the pin that the left-click button goes to.

Here's the underside. It helped me identify good locations to grab +5V and GND solder points.

This is the microcontroller I decided to use for the project. It's an ATTiny25, $1.33 USD (10+ quantity from Mouser), and has a built in 8MHz oscillator (which can run at 1MHz thanks to the DIV/8 clock prescaler.

I slap the chip in the homebrew development board (a glorified AVR-ISP mkII) and it's ready for programming. Code and schematics are at the bottom.

After programming, I glued the microchip upside-down in the mouse case and soldered wires directly to the pins. I used small (about 28AWG) magnet wire because it's a lot easier than stripping wires. Just heat the tip with a soldering iron, the coating melts away, and you can stick it wherever you need to with a dab of solder. Not too many people use this method, but I recommend you try it at least once! It can be very useful at times, and is about as cheap as you can get. (eBay has good prices)

BIG PROBLEM! It didn't work AT ALL. Why? Didn't know... I checked the o-scope and saw everything seemed to be working fine. It turns out that 50 clicks per second was too fast to register, and when I reduced the speed to 25 clicks per second it worked fine. Unfortunately I had to add extra wires to allow myself to program the chip while it was in the mouse - a major pain that complicated the project more than I wished!

Here's a good view of the transistor. Simply put, when the microcontroller sends power to the "base" pin of the 2n2222 transistor, the "collector" is drained through the "emitter", and the transistor acts like a switch. It's shorting the pin, just like would happen if you physically pressed the left click mouse button. When the mouse microchip is positive (+5V), it's "no click", but when it goes to ground (shorted by the click button), a click is detected. I biased the "base" pin toward ground by connecting it to GND through a high value resistor. This makes sure it doesn't accidentally fire when it's not supposed to.

Here you can clearly see the programmer pins I added. This lets me quickly access the chip and reprogram it if I decide to add/modify functionality.

When it's all said and done, it's surprisingly slick and functional. I'm using it right now to write my blog, and the button isn't really in the way. I think it's one of those el-cheapo buttons you get in a pack of 10 from RadioShack, but I would highly recommend eBay as RadioShack is ridiculously overpriced on components.

There's the schematic. Grabbing 5v and GND from a usb mouse is trivial. Heck, most of the circuity/code is trivial! Now that I think about it, this represents are really great starter project for anyone interested in microcontrollers.

Use this diagram of the pin functions for reference.

Remember there's more than one way to skin a cat! For example, if you don't want to program a microcontroller, a 555 timer is a simple method and there are tutorials out there demonstrating how to do this. I chose a microcontroller because I can precisely control the rate of firing and the duration. If you decide to do something similar, send me photos and I'd be happy to share them on the site! I love doing tangible projects, however silly they are.

And finally, the code!

#define F_CPU 1000000UL // frequency (20MHz)
#include <avr/io.h>
#include <util/delay.h>

void on()
{
    PORTB |= 1 << PB3; //led
    PORTB |= 1 << PB2; //heater
}
void off()
{
    PORTB &= ~(1 << PB3); //led
    PORTB &= ~(1 << PB2); //heater
}

void main()
{
    DDRB |= (1 << PB3) | (1 << PB2);
    int ticks;

    for (;;)
    { //FOREVER
        while ((PINB & _BV(PB4)) == 0)
        {
        }                                     // NOT PRESSED, DO NOTHING
        for (ticks = 0; ticks < 125; ticks++) // CLICK FOR 5 seconds
        {
            on();
            _delay_ms(20);
            off();
            _delay_ms(20);
        } // CLICK TAKES 1/50'th second
    }
}
Markdown source code last modified on January 18th, 2021
---
title: Full-Auto Rapidfire Mouse Modification
date: 2010-12-28 01:52:09
tags: circuit, microcontroller, old
---

# Full-Auto Rapidfire Mouse Modification

__I did this purely for the fun of it, and am aware there are many ways to accomplish the same thing.__ I was playing [Counter Strike Source](http://store.steampowered.com/css) (you should buy it and play with me, name "swharden") and my fingers are really cold from the winter weather, and wondered if I could have a button help with the rapid firing of pistols.  I mentioned it on the microphone, and one of the players ("{Ẋpli¢it} shadow") said I should go for it.  Because it was a fun little project, I documented it so I could share it. Check out the cool photos and video!

![](https://www.youtube.com/embed/pxHLXyPt6N8)

__There's a summary of the project in video form.__ Some details of the project are below...

<div class="text-center img-border">

[![](rapidfire_mouse_mod-1_thumb.jpg)](rapidfire_mouse_mod-1.jpg)

</div>

__Here you can see the original circuit board in the mouse. __The microchip on the bottom right of the image seems to do the data processing, so I investigated it a bit and found the pin that the left-click button goes to.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-2_thumb.jpg)](rapidfire_mouse_mod-2.jpg)

</div>

__Here's the underside.__ It helped me identify good locations to grab +5V and GND solder points.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-3_thumb.jpg)](rapidfire_mouse_mod-3.jpg)

</div>

__This is the microcontroller I decided to use for the project.__ It's an ATTiny25, $1.33 USD (10+ quantity from Mouser), and has a built in 8MHz oscillator (which can run at 1MHz thanks to the DIV/8 clock prescaler.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-4_thumb.jpg)](rapidfire_mouse_mod-4.jpg)

</div>

__I slap the chip in the homebrew development board__ (a glorified AVR-ISP mkII) and it's ready for programming. Code and schematics are at the bottom.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-5_thumb.jpg)](rapidfire_mouse_mod-5.jpg)

</div>

__After programming, I glued the microchip__ upside-down in the mouse case and soldered wires directly to the pins. I used small (about 28AWG) magnet wire because it's a lot easier than stripping wires. Just heat the tip with a soldering iron, the coating melts away, and you can stick it wherever you need to with a dab of solder. Not too many people use this method, but I recommend you try it at least once! It can be very useful at times, and is about as cheap as you can get. (eBay has good prices)

<div class="text-center img-border">

[![](rapidfire_mouse_mod-6_thumb.jpg)](rapidfire_mouse_mod-6.jpg)

</div>

__BIG PROBLEM!__ It didn't work *AT ALL*. Why? Didn't know... I checked the o-scope and saw everything seemed to be working fine.  It turns out that 50 clicks per second was too fast to register, and when I reduced the speed to 25 clicks per second it worked fine. Unfortunately I had to add extra wires to allow myself to program the chip while it was in the mouse - a major pain that complicated the project more than I wished!

<div class="text-center img-border">

[![](rapidfire_mouse_mod-7_thumb.jpg)](rapidfire_mouse_mod-7.jpg)

</div>

__Here's a good view of the transistor. __ Simply put, when the microcontroller sends power to the "base" pin of the 2n2222 transistor, the "collector" is drained through the "emitter", and the transistor acts like a switch. It's shorting the pin, just like would happen if you physically pressed the left click mouse button. When the mouse microchip is positive (+5V), it's "no click", but when it goes to ground (shorted by the click button), a click is detected. I biased the "base" pin toward ground by connecting it to GND through a high value resistor. This makes sure it doesn't accidentally fire when it's not supposed to.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-8_thumb.jpg)](rapidfire_mouse_mod-8.jpg)

</div>

__Here you can clearly see the programmer pins I added.__ This lets me quickly access the chip and reprogram it if I decide to add/modify functionality.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-9_thumb.jpg)](rapidfire_mouse_mod-9.jpg)

</div>

__When it's all said and done, it's surprisingly slick and functional. __ I'm using it right now to write my blog, and the button isn't really in the way. I think it's one of those el-cheapo buttons you get in a pack of 10 from RadioShack, but I would highly recommend eBay as RadioShack is ridiculously overpriced on components.

<div class="text-center img-border">

[![](rapidfire_mouse_mod-10_thumb.jpg)](rapidfire_mouse_mod-10.jpg)

</div>

__There's the schematic.__  Grabbing 5v and GND from a usb mouse is trivial. Heck, most of the circuity/code is trivial!  Now that I think about it, this represents are really great starter project for anyone interested in microcontrollers.

<div class="text-center">

![](ATtiny25-45-85V.jpg)

</div>

__Use this diagram of the pin functions for reference.__

__Remember there's more than one way to skin a cat!__ For example, if you don't want to program a microcontroller, a 555 timer is a simple method and there are tutorials out there demonstrating how to do this.  I chose a microcontroller because I can precisely control the rate of firing and the duration. If you decide to do something similar, send me photos and I'd be happy to share them on the site!  I love doing tangible projects, however silly they are.

__And finally, the code!__

```c
#define F_CPU 1000000UL // frequency (20MHz)
#include <avr/io.h>
#include <util/delay.h>

void on()
{
    PORTB |= 1 << PB3; //led
    PORTB |= 1 << PB2; //heater
}
void off()
{
    PORTB &= ~(1 << PB3); //led
    PORTB &= ~(1 << PB2); //heater
}

void main()
{
    DDRB |= (1 << PB3) | (1 << PB2);
    int ticks;

    for (;;)
    { //FOREVER
        while ((PINB & _BV(PB4)) == 0)
        {
        }                                     // NOT PRESSED, DO NOTHING
        for (ticks = 0; ticks < 125; ticks++) // CLICK FOR 5 seconds
        {
            on();
            _delay_ms(20);
            off();
            _delay_ms(20);
        } // CLICK TAKES 1/50'th second
    }
}
```
November 28th, 2010

Crystal Oven Experiments

Now that I've finished my 6-channel data logger (previous post), it's time to put it to the test! I'm using a handful of LM335 temperature sensors to measure temperature, and a 20 Ohm resistor to act as a heater. When 1A of current passes through it, it gets quite toasty! First, I'll make some temperature probes...

UPDATE: Those photos show a partially completed sensor. Obviously the third wire is required between the resistor and the LM335 to allow for measurement! Here's a more completed sensor before the shrink tube was massaged over the electrical elements:

Then I mounted the sensors on a block of steel with the heater on one side. This way I can use one temperature to measure the heater temperature, and the other to measure the temperature of the metal chassis. I then put the whole thing in a small Styrofoam box.

When I fire the heater, that sucker gets pretty darn hot. In 40 minutes it got almost 250F (!) at which time I pulled the plug on the heater and watched the whole thing cool. Notice how the metal chassis lags behind the temperature of the heater. I guess it's a bit of a "thermal low-pass filter". Also, yes, I'm aware I spelled chassis incorrectly in the graphs.

But how do we use this to build a thermo-stable crystal oven for a MEPT (radio transmitter)? I tried a lot of code, simply "if it's too cold, turn heater on / if it's too hot, turn heater off" but because the chassis always swung behind the heater, and even the heater itself had a bit of a delay in heating up, the results were always slowly oscillating temperatures around 10F every 20 min. That's worse than no heater! My best luck was a program to hold temperature stable at 100F with the following rules:

  • 1.) If heater > 155F, turn heater off (prevent fire)
  • 2.) If chassis < 100F, turn heater on
  • 3.) if (heater-target) > (target-chassis), turn heater off

What a great job! That thing is practically stable in 20 minutes. The advantage of this over an analog method is that I can set the temperature in software (or provide an interface to change temperature) and my readings are analytical, such that they can be conveyed in a radio message. Again, my best results came when I implemented rule 3 in the code above. More experiments to come!

Markdown source code last modified on January 18th, 2021
---
title: Crystal Oven Experiments
date: 2010-11-28 17:06:18
tags: circuit, microcontroller, old
---

# Crystal Oven Experiments

__Now that I've finished my__ 6-channel data logger (previous post), it's time to put it to the test!  I'm using a handful of LM335 temperature sensors to measure temperature, and a 20 Ohm resistor to act as a heater.  When 1A of current passes through it, it gets quite toasty!  First, I'll make some temperature probes...

<div class="text-center img-border">

[![](IMG_4581_thumb.jpg)](IMG_4581.jpg)
[![](IMG_4588_thumb.jpg)](IMG_4588.jpg)

</div>

__UPDATE:__ Those photos show a partially completed sensor. Obviously the third wire is required between the resistor and the LM335 to allow for measurement! Here's a more completed sensor before the shrink tube was massaged over the electrical elements:

<div class="text-center img-border">

[![](IMG_4591_thumb.jpg)](IMG_4591.jpg)

</div>

__Then I mounted the sensors__ on a block of steel with the heater on one side.  This way I can use one temperature to measure the heater temperature, and the other to measure the temperature of the metal chassis.  I then put the whole thing in a small Styrofoam box. 

<div class="text-center img-border">

[![](IMG_4606_thumb.jpg)](IMG_4606.jpg)
[![](IMG_4615_thumb.jpg)](IMG_4615.jpg)

</div>

__When I fire the heater,__ that sucker gets pretty darn hot. In 40 minutes it got almost 250F (!) at which time I pulled the plug on the heater and watched the whole thing cool. Notice how the metal chassis lags behind the temperature of the heater. I guess it's a bit of a "thermal low-pass filter".  Also, yes, I'm aware I spelled chassis incorrectly in the graphs.

<div class="text-center">

[![](howhot_thumb.jpg)](howhot.png)
[![](quicktest_thumb.jpg)](quicktest.png)

</div>

__But how do we use this to build a thermo-stable crystal oven for a MEPT (radio transmitter)?__ I tried a lot of code, simply "if it's too cold, turn heater on / if it's too hot, turn heater off" but because the chassis always swung behind the heater, and even the heater itself had a bit of a delay in heating up, the results were always slowly oscillating temperatures around 10F every 20 min. That's worse than no heater!  My best luck was a program to hold temperature stable at 100F with the following rules:

* `1.) If heater > 155F, turn heater off (prevent fire)`
* `2.) If chassis < 100F, turn heater on`
* `3.) if (heater-target) > (target-chassis), turn heater off`

<div class="text-center">

[![](heaterworks_thumb.jpg)](heaterworks.png)

</div>

__What a great job!__ That thing is practically stable in 20 minutes. The advantage of this over an analog method is that I can set the temperature in software (or provide an interface to change temperature) and my readings are analytical, such that they can be conveyed in a radio message. Again, my best results came when I implemented rule 3 in the code above. More experiments to come!
November 24th, 2010

ATMega48 + LM335 + MAX232 = Serial Port Multi-Channel Temperature Measurement

While working to perfect my temperature-controlled manned experimental propagation transmitter (MEPT), I developed the need to accurately measure temperature inside my Styrofoam enclosure (to assess drift) and compare it to external temperature (to assess insulation effects). I accomplished this utilizing the 8 ADC channels of the ATMega48 and used its in-chip USART capabilities to send this data to a PC for logging. I chose the ATMega48 over the ATTiny2313 (which has USART but no ADCs) and the ATTiny44a (which has ADCs but no USART). From when I see, no ATTiny series ATMEL AVR has both! Lucky for me, the ATMega48 is cheap at $2.84 USD. Here's my basic circuit idea:

EDIT: the voltage reference diagram is wrong at the bottom involving the zener diode. Reference the picture to the right for the CORRECT way to use such a diode as a voltage reference. (stupid me!)

MULTIPLE SENSORS - Although in this demonstration post I only show a single sensor, it's possible to easily have 8 sensors in use simultaneously since the ATMega48 has 8 ADC pins, and even more (infinitely) if you want to design a clever way to switch between them.

LM335 Temperature Sensor - selected because it's pretty cheap (< $1) and quantitative. In other words, every 10mV drop in voltage corresponds to a change of 1ºC. If I wanted to be even cheaper, I would use thermistors (<$0.10) which are more qualitative, but can be calibrated I guess.

Notes on power stability - The output of the sensor is measured with the ADC (analog to digital converter) of the microcontroller. The ADC has a 10-bit resolution, so readings are from 0 to 2^10 (1024). AREF and AVCC can be selected as a voltage reference to set what the maximum value (1024) should be. If the ADC value is 1V (for example) and AREF is 1V, the reading will be 1024. If AREF becomes 5V, the reading will be 1024/5. Make sense? If AREF is fluctuating like crazy, the same ADC voltage will be read as differing vales which is not what we want, therefore care should be taken to ensure AREF is ripple-free and constant. Although I did it by adding a few capacitors to the lines of the power supply (not very precise), a better way would be to use a zener diode (perhaps 4.1V?) as a voltage reference.

Here is my circuit. I'm clocking the chip at 9.21MHz which works well for 19200 baud for serial communication. Refer to my other MAX232 posts for a more detailed explanation of how I chose this value. The temperature sensor (blurry) is toward the camera, and the max232 is near the back. Is that an eyelash on the right? Gross!

The data is read by a Python script which watches the serial port for data and averages 10 ADC values together to produce a value with one more significant digit. This was my way of overcoming continuously-fluctuating values.

Here you can see me testing the device by placing an ice cube on the temperature sensor. I had to be careful to try to avoid getting water in the electrical connections. I noticed that when I pressed the ice against the sensor firmly, it cooled at a rate different than if I simply left the ice near it.NOTICE THE PROGRAMMER in the background (slightly blurry). The orange wires connect the AVR programmer to my circuit, and after the final code is completed and loaded onto the microcontroller these orange wires will be cut away.

Here is some actual data from the device. The LM335 readout is in Kelvin, such that 3.00V implies 300K = 80ºF = 27ºC (room temperature). The data is smooth until I touch it with the soldering iron (spike), then it gets cool again and I touch it with a cold piece of metal (wimpy dip), then later I put an ice cube on it (bigger dip). Pretty good huh? Remember, 0.01V change = 1ºC change. The bottom of the dip is about 2.8V = 280K = 44ºF = 7ºC. If I left the cube on longer, I imagine it would reach 0ºC (273K, or 2.73V).For everyone's reference, here's the pinout diagram of the ATMega48:

import socket
import sys
import serial

ser = serial.Serial('COM1', 19200, timeout=1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

chunk=""
i=0
data = ser.readline()
while True:
    i+=1
    data = ser.readline()
    data=data.replace("n","")
    data=data.replace("r","")
    data="["+data[:-1]+"]"
    data=eval(data)
    val=sum(data)/float(len(data))
    print i,data,val
    chunk=chunk+"%.01f,"%val
    if i==100:
        print "nSAVING"
        i=0
        f=open("data.txt","a")
        f.write(chunk)
        f.close()
        chunk=""

and the code to PLOT the data file:


import matplotlib.pyplot as plt
import numpy

def smoothTriangle(data,degree,dropVals=False):
        """performs moving triangle smoothing with a variable degree."""
        """note that if dropVals is False, output length will be identical
        to input length, but with copies of data at the flanking regions"""
        triangle=numpy.array(range(degree)+[degree]+range(degree)[::-1])+1
        smoothed=[]
        for i in range(degree,len(data)-degree*2):
                point=data[i:i+len(triangle)]*triangle
                smoothed.append(sum(point)/sum(triangle))
        if dropVals: return smoothed
        smoothed=[smoothed[0]]*(degree+degree/2)+smoothed
        while len(smoothed)<len(data):smoothed.append(smoothed[-1])
        return smooth

print "loading..."
f=open("data.txt")
raw="["+f.read()+"]"
f.close()
data=eval(raw)

print "converting..."
data=numpy.array(data)
data=data/1024.0*5 #10-bit resolution, 5V max

print "graphing"
plt.plot(data)

plt.grid(alpha=.5)
plt.title("ATMega48 LM335 Temperature Sensor")
plt.ylabel("Voltage (V)")
plt.xlabel("Time (5/sec)")
plt.show()

Also, the AVR-GCC code loaded on the ATMega48:

#define F_CPU 9210000UL

#include <avr/io.h>
#include <util/delay.h>

void init_usart(unsigned long);

unsigned int readADC(char times){
    unsigned long avg=0;
    for (char i=0; i<times; i++){
        ADCSRA |= (1<<ADSC); // reset value
        while (ADCSRA & ( 1<<ADSC)) {}; // wait for measurement
        avg=avg+ADC;
    }
    avg=avg/times;
    return avg;
}

int main (void){

    ADMUX = 0b0100101; // AVCC ref on ADC5
    ADCSRA = 0b10000111; //ADC Enable, Manual Trigger, Prescaler 128
    ADCSRB = 0;

    DDRD=255;

    init_usart(19200);
    for(;;){
        for(char j=0;j<10;j++){
            sendNum(readADC(10)>>6); // shift to offset 10bit 16bit
            send(44); // COMMA
            PORTD=255;_delay_ms(10);
            PORTD=0;_delay_ms(10);
            }
        send(10);send(13); // LINE BREAK
        }
    }

void sendNum(unsigned int num){
        char theIntAsString[7];
        int i;
        sprintf( theIntAsString, "%u", num );
        for (i=0; i < strlen(theIntAsString); i++)
        {send(theIntAsString[i]);}
}

void send (unsigned char c){
        while((UCSR0A & (1<<UDRE0)) == 0) {}
        UDR0 = c;
}

void init_usart (unsigned long baud)
{
    /////////////////////////
    //        Baud Generation
    unsigned int UBRR_2x_off;
    unsigned int UBRR_2x_on;
    unsigned long closest_match_2x_off;
    unsigned long closest_match_2x_on;
    unsigned char off_2x_error;
    unsigned char on_2x_error;

    UBRR_2x_off = F_CPU/(16*baud) - 1;
    UBRR_2x_on = F_CPU/(8*baud) - 1;

    closest_match_2x_off = F_CPU/(16*(UBRR_2x_off + 1));
    closest_match_2x_on = F_CPU/(8*(UBRR_2x_on + 1));

    off_2x_error = 255*(closest_match_2x_off/baud - 1);
    if (off_2x_error <0) {off_2x_error *= (-1);}
    on_2x_error = 255*(closest_match_2x_on/baud -1);
    if (on_2x_error <0) {on_2x_error *= (-1);}

    if(baud > F_CPU / 16)
    {
        UBRR0L = 0xff & UBRR_2x_on;
        UBRR0H = 0xff & (UBRR_2x_on>>8);
        UCSR0A |= (1<<U2X0);
    } else {

        if (off_2x_error > on_2x_error)
        {
            UBRR0L = 0xff & UBRR_2x_on;
            UBRR0H = 0xff & (UBRR_2x_on>>8);
            UCSR0A |= (1<<U2X0);
        } else {
            UBRR0L = 0xff & UBRR_2x_off;
            UBRR0H = 0xff & (UBRR_2x_off>>8);
            UCSR0A &= ~(1<<U2X0);
        }
    }
    /////////////////////////
    //    Configuration Registers
    UCSR0B = (0<<RXCIE0) |//We don't want this interrupt
    (0<<TXCIE0) |//We don't want this interrupt
    (0<<UDRIE0) |//We don't want this interrupt
    (1<<RXEN0) |//Enable RX, we wont use it here but it can't hurt
    (1<<TXEN0) |//Enable TX, for Talkin'
    (0<<UCSZ02);//We want 8 data bits so set this low

    UCSR0A |= (0<<U2X0) |//already set up, so don't mess with it
    (0<<MPCM0) ;//We wont need this

    UCSR0C = (0<<UMSEL01) | (0<<UMSEL00) |//We want UART mode
    (0<<UPM01) | (0<<UPM00) |//We want no parity bit
    (0<<USBS0) |//We want only one stop bit
    (1<<UCSZ01) | (1<<UCSZ00) |//We want 8 data bits
    (0<<UCPOL0) ;//This doesn't effect UART mode
}

UPDATE: A day later I added multiple sensors to the device. I calibrated one of them by putting it in a plastic bag and letting it set in ice water, then I calibrated the rest to that one. You can see as my room temperature slowly falls for the night, the open air sensor (red) drops faster than the insulated one in a Styrofoam box. Also, I did a touch of math to convert voltage to kelvin to Fahrenheit. You can also see spikes where it quickly approached 90+ degrees from the heat of my fingers as I handled the sensor. Cool!

UPDATE: a day and a half later, here's what the fluctuations look like. Notice the cooling of night, the heating of day, and now (near the end of the graph) the scattered rain causes more rapid fluctuations. Also, although one sensor is in an insulated styrofoam box, it still fluctuates considerably. This measurement system is prepped and ready to go for crystal oven tests!

Markdown source code last modified on January 18th, 2021
---
title: Serial Port Multi-Channel Temperature Measurement
date: 2010-11-24 08:17:03
tags: circuit, microcontroller, python, old
---

# ATMega48 + LM335 + MAX232 = Serial Port Multi-Channel Temperature Measurement

__While working to perfect my temperature-controlled manned experimental propagation transmitter (MEPT), I developed the need to accurately measure temperature inside my Styrofoam enclosure (to assess drift) and compare it to external temperature (to assess insulation effects).__ I accomplished this utilizing the 8 ADC channels of the ATMega48 and used its in-chip USART capabilities to send this data to a PC for logging.  I chose the ATMega48 over the ATTiny2313 (which has USART but no ADCs) and the ATTiny44a (which has ADCs but no USART).  From when I see, no ATTiny series ATMEL AVR has both!  Lucky for me, the [ATMega48 is cheap](http://search.digikey.com/scripts/DkSearch/dksus.dll?Detail&name=ATMEGA48-20PU-ND) at $2.84 USD. Here's my basic circuit idea: 

<div class="text-center img-border"> 

[![](IMG_4559_thumb.jpg)](IMG_4559.jpg)

</div>

EDIT: the voltage reference diagram is wrong at the bottom involving the zener diode. Reference the picture to the right for the CORRECT way to use such a diode as a voltage reference. (stupid me!)

<div class="text-center"> 

![](aref.jpg)

</div>

__MULTIPLE SENSORS__ - Although in this demonstration post I only show a single sensor, it's possible to easily have 8 sensors in use simultaneously since the ATMega48 has 8 ADC pins, and even more (infinitely) if you want to design a clever way to switch between them.

__LM335 Temperature Sensor__ - selected because it's pretty cheap (< $1) and quantitative. In other words, every 10mV drop in voltage corresponds to a change of 1ºC.  If I wanted to be even cheaper, I would use thermistors (<$0.10) which are more qualitative, but can be calibrated I guess.

Notes on power stability  - The output of the sensor is measured with the ADC (analog to digital converter) of the microcontroller. The ADC has a 10-bit resolution, so readings are from 0 to 2^10 (1024).  AREF and AVCC can be selected as a voltage reference to set what the maximum value (1024) should be.  If the ADC value is 1V (for example) and AREF is 1V, the reading will be 1024.  If AREF becomes 5V, the reading will be 1024/5. Make sense?  If AREF is fluctuating like crazy, the same ADC voltage will be read as differing vales which is not what we want, therefore care should be taken to ensure AREF is ripple-free and constant.  Although I did it by adding a few capacitors to the lines of the power supply (not very precise), a better way would be to use a <a href="http://en.wikipedia.org/wiki/Zener_diode">zener diode (perhaps 4.1V?) as a voltage reference.

<div class="text-center img-border">

[![](IMG_4575_thumb.jpg)](IMG_4575.jpg)

</div>

<b>Here is my circuit.</b> I'm clocking the chip at 9.21MHz which works well for 19200 baud for serial communication. Refer to my other MAX232 posts for a more detailed explanation of how I chose this value. The temperature sensor (blurry) is toward the camera, and the max232 is near the back. Is that an eyelash on the right? Gross!

<div class="text-center img-border"> 

![](logger.jpg)

</div>

<b>The data is read by a Python script</b> which watches the serial port for data and averages 10 ADC values together to produce a value with one more significant digit. This was my way of overcoming continuously-fluctuating values.

<div class="text-center img-border"> 

[![](IMG_4564_thumb.jpg)](IMG_4564.jpg)

</div>

<b>Here you can see me testing the device</b> by placing an ice cube on the temperature sensor. I had to be careful to try to avoid getting water in the electrical connections. I noticed that when I pressed the ice against the sensor firmly, it cooled at a rate different than if I simply left the ice near it.<b>NOTICE THE PROGRAMMER</b> in the background (slightly blurry). The orange wires connect the AVR programmer to my circuit, and after the final code is completed and loaded onto the microcontroller these orange wires will be cut away.

<div class="text-center"> 

[![](lm335-microcontroller-graph-annotated_thumb.jpg)](lm335-microcontroller-graph-annotated.png)

</div>

<b>Here is some actual data from the device.</b> The LM335 readout is in Kelvin, such that 3.00V implies 300K = 80ºF = 27ºC (room temperature). The data is smooth until I touch it with the soldering iron (spike), then it gets cool again and I touch it with a cold piece of metal (wimpy dip), then later I put an ice cube on it (bigger dip). Pretty good huh? Remember, 0.01V change = 1ºC change. The bottom of the dip is about 2.8V = 280K = 44ºF = 7ºC. If I left the cube on longer, I imagine it would reach 0ºC (273K, or 2.73V).<b>For everyone's reference, here's the pinout diagram of the ATMega48:</b>

<div class="text-center img-medium"> 

[![](atmega48pinout_thumb.jpg)](atmega48pinout.png)

</div>

```python
import socket
import sys
import serial

ser = serial.Serial('COM1', 19200, timeout=1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

chunk=""
i=0
data = ser.readline()
while True:
    i+=1
    data = ser.readline()
    data=data.replace("n","")
    data=data.replace("r","")
    data="["+data[:-1]+"]"
    data=eval(data)
    val=sum(data)/float(len(data))
    print i,data,val
    chunk=chunk+"%.01f,"%val
    if i==100:
        print "nSAVING"
        i=0
        f=open("data.txt","a")
        f.write(chunk)
        f.close()
        chunk=""

```

<b>and the code to PLOT the data file:</b>

```python

import matplotlib.pyplot as plt
import numpy

def smoothTriangle(data,degree,dropVals=False):
        """performs moving triangle smoothing with a variable degree."""
        """note that if dropVals is False, output length will be identical
        to input length, but with copies of data at the flanking regions"""
        triangle=numpy.array(range(degree)+[degree]+range(degree)[::-1])+1
        smoothed=[]
        for i in range(degree,len(data)-degree*2):
                point=data[i:i+len(triangle)]*triangle
                smoothed.append(sum(point)/sum(triangle))
        if dropVals: return smoothed
        smoothed=[smoothed[0]]*(degree+degree/2)+smoothed
        while len(smoothed)<len(data):smoothed.append(smoothed[-1])
        return smooth

print "loading..."
f=open("data.txt")
raw="["+f.read()+"]"
f.close()
data=eval(raw)

print "converting..."
data=numpy.array(data)
data=data/1024.0*5 #10-bit resolution, 5V max

print "graphing"
plt.plot(data)

plt.grid(alpha=.5)
plt.title("ATMega48 LM335 Temperature Sensor")
plt.ylabel("Voltage (V)")
plt.xlabel("Time (5/sec)")
plt.show()
```

<b>Also, the AVR-GCC code loaded on the ATMega48:</b>

```c
#define F_CPU 9210000UL

#include <avr/io.h>
#include <util/delay.h>

void init_usart(unsigned long);

unsigned int readADC(char times){
    unsigned long avg=0;
    for (char i=0; i<times; i++){
        ADCSRA |= (1<<ADSC); // reset value
        while (ADCSRA & ( 1<<ADSC)) {}; // wait for measurement
        avg=avg+ADC;
    }
    avg=avg/times;
    return avg;
}

int main (void){

    ADMUX = 0b0100101; // AVCC ref on ADC5
    ADCSRA = 0b10000111; //ADC Enable, Manual Trigger, Prescaler 128
    ADCSRB = 0;

    DDRD=255;

    init_usart(19200);
    for(;;){
        for(char j=0;j<10;j++){
            sendNum(readADC(10)>>6); // shift to offset 10bit 16bit
            send(44); // COMMA
            PORTD=255;_delay_ms(10);
            PORTD=0;_delay_ms(10);
            }
        send(10);send(13); // LINE BREAK
        }
    }

void sendNum(unsigned int num){
        char theIntAsString[7];
        int i;
        sprintf( theIntAsString, "%u", num );
        for (i=0; i < strlen(theIntAsString); i++)
        {send(theIntAsString[i]);}
}

void send (unsigned char c){
        while((UCSR0A & (1<<UDRE0)) == 0) {}
        UDR0 = c;
}

void init_usart (unsigned long baud)
{
    /////////////////////////
    //        Baud Generation
    unsigned int UBRR_2x_off;
    unsigned int UBRR_2x_on;
    unsigned long closest_match_2x_off;
    unsigned long closest_match_2x_on;
    unsigned char off_2x_error;
    unsigned char on_2x_error;

    UBRR_2x_off = F_CPU/(16*baud) - 1;
    UBRR_2x_on = F_CPU/(8*baud) - 1;

    closest_match_2x_off = F_CPU/(16*(UBRR_2x_off + 1));
    closest_match_2x_on = F_CPU/(8*(UBRR_2x_on + 1));

    off_2x_error = 255*(closest_match_2x_off/baud - 1);
    if (off_2x_error <0) {off_2x_error *= (-1);}
    on_2x_error = 255*(closest_match_2x_on/baud -1);
    if (on_2x_error <0) {on_2x_error *= (-1);}

    if(baud > F_CPU / 16)
    {
        UBRR0L = 0xff & UBRR_2x_on;
        UBRR0H = 0xff & (UBRR_2x_on>>8);
        UCSR0A |= (1<<U2X0);
    } else {

        if (off_2x_error > on_2x_error)
        {
            UBRR0L = 0xff & UBRR_2x_on;
            UBRR0H = 0xff & (UBRR_2x_on>>8);
            UCSR0A |= (1<<U2X0);
        } else {
            UBRR0L = 0xff & UBRR_2x_off;
            UBRR0H = 0xff & (UBRR_2x_off>>8);
            UCSR0A &= ~(1<<U2X0);
        }
    }
    /////////////////////////
    //    Configuration Registers
    UCSR0B = (0<<RXCIE0) |//We don't want this interrupt
    (0<<TXCIE0) |//We don't want this interrupt
    (0<<UDRIE0) |//We don't want this interrupt
    (1<<RXEN0) |//Enable RX, we wont use it here but it can't hurt
    (1<<TXEN0) |//Enable TX, for Talkin'
    (0<<UCSZ02);//We want 8 data bits so set this low

    UCSR0A |= (0<<U2X0) |//already set up, so don't mess with it
    (0<<MPCM0) ;//We wont need this

    UCSR0C = (0<<UMSEL01) | (0<<UMSEL00) |//We want UART mode
    (0<<UPM01) | (0<<UPM00) |//We want no parity bit
    (0<<USBS0) |//We want only one stop bit
    (1<<UCSZ01) | (1<<UCSZ00) |//We want 8 data bits
    (0<<UCPOL0) ;//This doesn't effect UART mode
}

```

<b>UPDATE:</b> A day later I added multiple sensors to the device. I calibrated one of them by putting it in a plastic bag and letting it set in ice water, then I calibrated the rest to that one. You can see as my room temperature slowly falls for the night, the open air sensor (red) drops faster than the insulated one in a Styrofoam box. Also, I did a touch of math to convert voltage to kelvin to Fahrenheit. You can also see spikes where it quickly approached 90+ degrees from the heat of my fingers as I handled the sensor. Cool!

<div class="text-center"> 

[![](3traces_thumb.jpg)](3traces.png)

</div>

<b>UPDATE:</b> a day and a half later, here's what the fluctuations look like. Notice the cooling of night, the heating of day, and now (near the end of the graph) the scattered rain causes more rapid fluctuations. Also, although one sensor is in an insulated styrofoam box, it still fluctuates considerably. This measurement system is prepped and ready to go for crystal oven tests!

<div class="text-center"> 

[![](insulated3_thumb.jpg)](insulated3.png)

</div>
September 7th, 2010

Simple method to send data from ANY microcontroller to a serial port

This weekend I had a need, and I met it with parts I had on hand. Simply put, I wanted to assess whether or not my temperature-controlled crystal heater is doing its job in keeping temperature rock-stable. I wanted to measure temperature by measuring the ADC (analog-to-digital) value at the middle of a voltage divider with a resistor and a thermistor. Using a computer to plot this data, I can see if temperature fluctuates as my apartment AC turns on/off, or if it's perfectly stable (my goal). The problem is that my only MCU (micro-controller unit) with USART (universal asynchronous receiver/transmitter) built-in is an ATTiny2313, which has no ADC capabilities. I had a lot of ATTiny44A chips on hand, so I had to figure out a way to get the data from my an ATTiny44A to an ATTiny2313 then to a MAX232 chip (voltage driver) so it can be sent to a PC's serial port.

This is my bare-bones solution to easily sending data from ANY microcontroller to a PC's serial port using 3 pins to send data to an ATTiny2313 which is interpreted, converted to decimal, then sent to my PC's serial port. I will keep this little board and use it often to peek at variables inside my microcontroller projects in real time, with minimal coding!

Above is the bare-bones schematic required to send data from an ATTiny2313 to a PC via a serial port. This schematic is improved and documented better on this page than on my previous post Simple Case AVR/PC Serial Communication via MAX232. Note that I'm designing this to be functional, perhaps not well enough to be used in mission-critical systems. Although some schematics suggest extra capacitors, I found that the only one required is between pins 4 and 5 of the MAX232. The role of the MAX232 chip is to act as a voltage pump and relay the incoming signal at increased voltage which the PC's serial port can read. It doesn't actually change the data.

UPDATE: in a later project working with an ATMega48 I found that a capacitor was needed between pin 6 and ground - don't know why! If it's not working for you (you're getting garbage) start adding capacitors as shown in this MAX232 circuit

Power supply: Since the thing runs on 5V, we're golden! Just grab a USB cable, hook up the black (ground) and red (+5V) wires, and you're good to go! If you want you can add a few capacitors of different values in parallel to the power supply to stabilize fluctuations in voltage, but I've been doing just fine without this extra precaution.

Display: The two LEDs are totally optional, but they let me see what's going on. One of them flashes when the device is waiting for data (to let me know it's on), and the other one turns on every time a [CLOCK] signal is detected (which is any time data is being sent)

Notes on frequency and crystals. The UBRRL value in the code must be set depending on your micro-controller speed and desired baud rate. I set-up an Excel spreadsheet and did some math determining UBRRL for a combination of different frequencies/rates. The UBRRL values closest to whole numbers are those which should be used to minimize errors. External crystals are often used to increase and stabalize the clock speed of micro-controllers, but I was able to send serial data without a crystal. I set the fuse for "internal 8mhz" clocking, and enabled the "div8" fuse so it actually ran at 1mhz. With these settings at 4800 baud, UBRR [according to the equation UBRR=(freq/(16*baud))-1] is 12.02 (pretty close to 12), so I set UBRRL=12 in the code and it sent data to a PC beautifully without a crystal. However, I had the desire to run the MCU faster to watch for incoming signals. I therefore used a 9.21MHz crystal (I had to set the fuses to enable the external crystal), which can send serial data to a PC reliably at 19200 baud.

Sending data to the ATTiny2313 to be relayed to the PC: Not every MCU has SPI, USI, I2C, TWI, USART, or other "standard" communication methods. If I want to have a Texas Instruments or PIC or PICaxe chip send data to a PC, I have to decipher the datasheet and spend half a day to figure out how (yuk!). Therefore, I developed an ULTRA-SIMPLE protocol of data transfer which can be used by ANY microcontroller. Here's an example of a sensor microcontroller. Although it's not shown, there's a thermistor (or some analog voltage being measured) somewhere. It reads the sensor, then sends its data over the 3 wires [CLOCK], [A], and [B].

Pulling-down the clock: Note that the 100k resistor shown pulling the [CLOCK] line to ground is critical. It doesn't have to be 100k, it can be virtually any value, it just makes sure that if current is not being sent on the clock line, it quickly goes to 0V. Without this resistor, the clock line might flicker on and off even though no data is being sent.

Sending data this way is easy! The clock line is almost always low. When [clock] goes high, data is read. When data is read, the ATTiny2313 determines the state of [A] and [B]. If A=0 and B=0, a ZERO is sent. If A=1 and B=0, a ONE is sent. If A=0 and B=1, a SPACE is sent (between values). If A=1 and B=1, a LINE BREAK is sent. Values are sent in binary, and when a space or line break is detected, the binary value is converted to decimal and sent to the PC's serial port. It's not dependent on speed, so send data as fast (within reason) or slowly as you want from any microcontroller and it will end-up on your computer screen! It's that easy!

FLAME ALERT: A lot of people will be mad at me for suggesting this method. There are fancier, faster, and more stable ways to data transfer between micro-controllers, but this works well at moderate speeds (maybe 10 measurements a second?) and I can implement this on any microcontroller in seconds, without puzzling over the datasheet.

BREADBOARDED PROTOTYPE

Remember that I'm powering this entirely from USB power. The layout is simple: ATTiny44A measuring ADC of a thermistor on the left (see the little red thing?) sending data with 3 wires (top 3) to an ATTiny2313 intermediate chip (center), which converts this binary data to decimal and sends it to a MAX232 chip (right) where it gets converted to levels suitable for transmission to a serial port.

CODE (AVR-GCC)

This is what runs on the ATTiny2313 intermediate chip:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define B PB2
#define A PB1
#define clk PB0
unsigned int times = 0;

// THIS RUNS ON THE ATTINY2313
// FUSES SET FOR INTERNAL 8MHZ, DIV/8=TRUE
// LISTENS ON PINS 12 (CLOCK), 13 (DATA), AND 14 (TRANSMIT)
// OUTPUTS TO A MAX232 THEN TO SERIAL PORT
// PC TERMINAL SET TO LISTEN AT 4800 BAUD

int main(void)
{
    UBRRL = 29;                          // value determined for 9.21MHz crystal at 19200 baud
    UCSRB = (1 << RXEN) | (1 << TXEN);   // fire-up USART
    UCSRC = (1 << UCSZ1) | (1 << UCSZ0); // fire-up USART
    DDRB = 0;                            // set all of port b to input
    DDRD = 255;                          // set all of port d to output
    char last = 255;
    int var = 0;
    char pos = 0;
    char i = 0;
    for (;;)
    {
        while
            bit_is_clear(PINB, clk) { blink(); }
        PORTD |= (1 << PD5);
        PORTD &= ~(1 << PD4);
        if (bit_is_set(PINB, A) && bit_is_clear(PINB, B))
        {
            var = (var << 1) + 1;
        } //ONE
        if (bit_is_clear(PINB, A) && bit_is_clear(PINB, B))
        {
            var = (var << 1);
        } //ZERO
        if (bit_is_clear(PINB, A) && bit_is_set(PINB, B))
        {
            show(var);
            var = 0;
            send(32);
        } //SPACE
        if (bit_is_set(PINB, A) && bit_is_set(PINB, B))
        {
            show(var);
            var = 0;
            send(10);
            send(13);
        } //BREAK
        while
            bit_is_set(PINB, clk) { blink(); }
        PORTD &= ~(1 << PD5);
        PORTD |= (1 << PD4);
    }
}
void blink()
{
    // just hanging out
    times++;
    if (times == 10000)
    {
        times == 0;
        PORTD |= (1 << PD3);
    }
    if (times == 20000)
    {
        times == 0;
        PORTD &= ~(1 << PD3);
        times = 0;
    }
}

unsigned int rev(unsigned int b)
{
    unsigned char result = 0;
    while (b)
    {
        result <<= 1;
        result |= b % 2;
        b >>= 1;
    }
    return result;
}

void show(unsigned int val)
{
    // SHOW INDIVIDUAL 1s and 0s?
    // for (char i=0;i<16;i++){
    //   if (val&(1<<i)){send(49);}
    //   else {send(48);}
    // }
    // send(61);

    val = rev(val);
    if (val == 0)
    {
        send(48);
    }
    else
    {
        char started = 0;
        int div = 10000;
        for (char i = 0; i < 5; i++)
        {
            if (val > div)
            {
                started = 1;
            }
            if (started)
            {
                send(val / div + 48);
                val = val - (val / div) * div;
            }
            div = div / 10;
        }
    }
    return;
}

void send(unsigned char data)
{
    while (!(UCSRA & (1 << UDRE)))
        ;       // wait for buffer to be empty
    UDR = data; // send that sucker
}

This is what runs on my ATTiny44a sensor chip. This is what you can replace with ANYTHING, as long as it twiddles the [clock], [a], and [b] pins similarly.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define dtaprt PORTA
#define clk PA1
#define A PA2
#define B PA0
#define delayms 100 // increase to slow it down

void wait() { _delay_ms(delayms); }
void clockNow()
{
    dtaprt |= (1 << clk);
    wait();
    dtaprt &= ~(1 << clk);
    wait();
}
void sendSpace()
{
    dtaprt = (1 << B);
    clockNow();
}
void sendLine()
{
    dtaprt = (1 << B) | (1 << A);
    clockNow();
}
void sendOne()
{
    dtaprt = (1 << A);
    clockNow();
}
void sendZero()
{
    dtaprt = 0;
    clockNow();
}

// TAKE A READING FROM ADC7 AND SEND IT TO SERIAL CHIP

int main(void)
{
    DDRA |= (1 << clk);
    DDRA |= (1 << A);
    DDRA |= (1 << B);
    ADMUX = (1 << REFS1) | (1 << MUX2) | (1 << MUX1) | (1 << MUX0);    // ADC on ADC7 to 1.1v ref
    ADCSRA = (1 << ADEN) | (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2); // enable, prescale
    for (;;)
    {
        int data = ReadADC();
        sendData(data);
        sendSpace();
        sendData(data);
        sendLine();
        _delay_ms(1000);
    }
}

void sendData(int data)
{
    char datalen = 16;
    for (char pos = 0; pos < datalen; pos++)
    {
        if ((data >> pos) & 1)
        {
            sendOne();
        }
        else
        {
            sendZero();
        }
    }
}

int ReadADC()
{
    ADCSRA |= (1 << ADSC); // reset value
    while (ADCSRA & (1 << ADSC))
        ; // wait for measurement
    return ADC;
}

UPDATE

I found a simpler way to convert binary numbers into strings ready to be sent in ASCII via USART serial port:

void sendNum(unsigned int num)
{
    char theIntAsString[7];
    int i;
    sprintf(theIntAsString, "%u", num);
    for (i = 0; i < strlen(theIntAsString); i++)
    {
        send(theIntAsString[i]);
    }
}
Markdown source code last modified on January 18th, 2021
---
title: Simple method to send data from ANY microcontroller to a serial port
date: 2010-09-07 08:37:13
tags: microcontroller, old
---

# Simple method to send data from ANY microcontroller to a serial port

__This weekend I had a need, and I met it with parts I had on hand.__ Simply put, I wanted to assess whether or not my temperature-controlled crystal heater is doing its job in keeping temperature rock-stable. I wanted to measure temperature by measuring the ADC (analog-to-digital) value at the middle of a voltage divider with a resistor and a thermistor. Using a computer to plot this data, I can see if temperature fluctuates as my apartment AC turns on/off, or if it's perfectly stable (my goal).  The problem is that my only MCU (micro-controller unit) with USART (universal asynchronous receiver/transmitter) built-in is an ATTiny2313, which has no ADC capabilities.  I had a lot of ATTiny44A chips on hand, so I had to figure out a way to get the data from my an ATTiny44A to an ATTiny2313 then to a MAX232 chip (voltage driver) so it can be sent to a PC's serial port.

<div class="text-center img-border img-medium">

[![](IMG_3919_thumb.jpg)](IMG_3919.jpg)

</div>

This is my bare-bones solution to easily sending data from ANY microcontroller to a PC's serial port using 3 pins to send data to an ATTiny2313 which is interpreted, converted to decimal, then sent to my PC's serial port. I will keep this little board and use it often to peek at variables inside my microcontroller projects in real time, with minimal coding!

<div class="text-center img-medium">

[![](schematic_fixed2_thumb.jpg)](schematic_fixed2.jpg)

</div>

__Above is the bare-bones__ schematic required to send data from an ATTiny2313 to a PC via a serial port.  This schematic is improved and documented better on this page than on my previous post [Simple Case AVR/PC Serial Communication via MAX232](http://www.swharden.com/blog/2009-05-14-simple-case-avrpc-serial-communication-via-max232/). Note that I'm designing this to be functional, perhaps not well enough to be used in mission-critical systems. Although some schematics suggest extra capacitors, I found that the only one required is between pins 4 and 5 of the MAX232.  The role of the [MAX232 chip](http://en.wikipedia.org/wiki/MAX232) is to act as a voltage pump and relay the incoming signal at increased voltage which the PC's serial port can read. It doesn't actually change the data.

UPDATE: in a later project working with an ATMega48 I found that a capacitor was needed between pin 6 and ground - don't know why! If it's not working for you (you're getting garbage) start adding capacitors as shown in <a href="http://www.coolcircuit.com/circuit/rs232_driver/max232.gif">this MAX232 circuit</a>

__Power supply:__ Since the thing runs on 5V, we're golden!  Just grab a USB cable, hook up the black (ground) and red (+5V) wires, and you're good to go!  If you want you can add a few capacitors of different values in parallel to the power supply to stabilize fluctuations in voltage, but I've been doing just fine without this extra precaution.

__Display:__ The two LEDs are totally optional, but they let me see what's going on. One of them flashes when the device is waiting for data (to let me know it's on), and the other one turns on every time a [CLOCK] signal is detected (which is any time data is being sent)

__Notes on frequency and crystals.__ The UBRRL value in the code must be set depending on your micro-controller speed and desired baud rate. I set-up an Excel spreadsheet and did some math determining UBRRL for a combination of different frequencies/rates.  The UBRRL values closest to whole numbers are those which should be used to minimize errors.  External crystals are often used to increase and stabalize the clock speed of micro-controllers, but I was able to send serial data without a crystal.  I set the fuse for "internal 8mhz" clocking, and enabled the "div8" fuse so it actually ran at 1mhz. With these settings at 4800 baud, UBRR [according to the equation UBRR=(freq/(16*baud))-1] is 12.02 (pretty close to 12), so I set UBRRL=12 in the code and it sent data to a PC beautifully without a crystal. However, I had the desire to run the MCU faster to watch for incoming signals.  I therefore used a 9.21MHz crystal (I had to set the fuses to enable the external crystal), which can send serial data to a PC reliably at 19200 baud.

__Sending data to the ATTiny2313 to be relayed to the PC:__ Not every MCU has SPI, USI, I2C, TWI, USART, or other "standard" communication methods.  If I want to have a Texas Instruments or PIC or PICaxe chip send data to a PC, I have to decipher the datasheet and spend half a day to figure out how (yuk!).  Therefore, I developed an ULTRA-SIMPLE protocol of data transfer which can be used by ANY microcontroller.  Here's an example of a sensor microcontroller.  Although it's not shown, there's a thermistor (or some analog voltage being measured) somewhere.  It reads the sensor, then sends its data over the 3 wires [CLOCK], [A], and [B].

__Pulling-down the clock:__ Note that the 100k resistor shown pulling the [CLOCK] line to ground is critical.  It doesn't have to be 100k, it can be virtually any value, it just makes sure that if current is not being sent on the clock line, it quickly goes to 0V.  Without this resistor, the clock line might flicker on and off even though no data is being sent.

<div class="text-center">

![](serial_example.jpg)

</div>

<div class="text-center img-border">

[![](IMG_3907_thumb.jpg)](IMG_3907.jpg)

</div>

<strong>Sending data this way is easy!</strong> The clock line is almost always low. When \[clock\] goes high, data is read. When data is read, the ATTiny2313 determines the state of \[A\] and \[B\]. If A=0 and B=0, a ZERO is sent. If A=1 and B=0, a ONE is sent. If A=0 and B=1, a SPACE is sent (between values). If A=1 and B=1, a LINE BREAK is sent. Values are sent in binary, and when a space or line break is detected, the binary value is converted to decimal and sent to the PC's serial port. It's not dependent on speed, so send data as fast (within reason) or slowly as you want from any microcontroller and it will end-up on your computer screen! It's that easy!</blockquote>

__FLAME ALERT:__ A lot of people will be mad at me for suggesting this method. There are fancier, faster, and more stable ways to data transfer between micro-controllers, but this works well at moderate speeds (maybe 10 measurements a second?) and I can implement this on any microcontroller in seconds, without puzzling over the datasheet.

## BREADBOARDED PROTOTYPE

Remember that I'm powering this entirely from USB power. The layout is simple: ATTiny44A measuring ADC of a thermistor on the left (see the little red thing?) sending data with 3 wires (top 3) to an ATTiny2313 intermediate chip (center), which converts this binary data to decimal and sends it to a MAX232 chip (right) where it gets converted to levels suitable for transmission to a serial port.


<div class="text-center img-border img-micro">

[![](IMG_3905_thumb.jpg)](IMG_3905.jpg)
[![](IMG_3891_thumb.jpg)](IMG_3891.jpg)
[![](IMG_3899_thumb.jpg)](IMG_3899.jpg)
[![](IMG_3904_thumb.jpg)](IMG_3904.jpg)
[![](IMG_3907_thumb.jpg)](IMG_3907.jpg)
[![](IMG_3922_thumb.jpg)](IMG_3922.jpg)
[![](IMG_3919_thumb.jpg)](IMG_3919.jpg)

</div>

### CODE (AVR-GCC)

This is what runs on the ATTiny2313 intermediate chip:

```c
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define B PB2
#define A PB1
#define clk PB0
unsigned int times = 0;

// THIS RUNS ON THE ATTINY2313
// FUSES SET FOR INTERNAL 8MHZ, DIV/8=TRUE
// LISTENS ON PINS 12 (CLOCK), 13 (DATA), AND 14 (TRANSMIT)
// OUTPUTS TO A MAX232 THEN TO SERIAL PORT
// PC TERMINAL SET TO LISTEN AT 4800 BAUD

int main(void)
{
    UBRRL = 29;                          // value determined for 9.21MHz crystal at 19200 baud
    UCSRB = (1 << RXEN) | (1 << TXEN);   // fire-up USART
    UCSRC = (1 << UCSZ1) | (1 << UCSZ0); // fire-up USART
    DDRB = 0;                            // set all of port b to input
    DDRD = 255;                          // set all of port d to output
    char last = 255;
    int var = 0;
    char pos = 0;
    char i = 0;
    for (;;)
    {
        while
            bit_is_clear(PINB, clk) { blink(); }
        PORTD |= (1 << PD5);
        PORTD &= ~(1 << PD4);
        if (bit_is_set(PINB, A) && bit_is_clear(PINB, B))
        {
            var = (var << 1) + 1;
        } //ONE
        if (bit_is_clear(PINB, A) && bit_is_clear(PINB, B))
        {
            var = (var << 1);
        } //ZERO
        if (bit_is_clear(PINB, A) && bit_is_set(PINB, B))
        {
            show(var);
            var = 0;
            send(32);
        } //SPACE
        if (bit_is_set(PINB, A) && bit_is_set(PINB, B))
        {
            show(var);
            var = 0;
            send(10);
            send(13);
        } //BREAK
        while
            bit_is_set(PINB, clk) { blink(); }
        PORTD &= ~(1 << PD5);
        PORTD |= (1 << PD4);
    }
}
void blink()
{
    // just hanging out
    times++;
    if (times == 10000)
    {
        times == 0;
        PORTD |= (1 << PD3);
    }
    if (times == 20000)
    {
        times == 0;
        PORTD &= ~(1 << PD3);
        times = 0;
    }
}

unsigned int rev(unsigned int b)
{
    unsigned char result = 0;
    while (b)
    {
        result <<= 1;
        result |= b % 2;
        b >>= 1;
    }
    return result;
}

void show(unsigned int val)
{
    // SHOW INDIVIDUAL 1s and 0s?
    // for (char i=0;i<16;i++){
    //   if (val&(1<<i)){send(49);}
    //   else {send(48);}
    // }
    // send(61);

    val = rev(val);
    if (val == 0)
    {
        send(48);
    }
    else
    {
        char started = 0;
        int div = 10000;
        for (char i = 0; i < 5; i++)
        {
            if (val > div)
            {
                started = 1;
            }
            if (started)
            {
                send(val / div + 48);
                val = val - (val / div) * div;
            }
            div = div / 10;
        }
    }
    return;
}

void send(unsigned char data)
{
    while (!(UCSRA & (1 << UDRE)))
        ;       // wait for buffer to be empty
    UDR = data; // send that sucker
}
```

**This is what runs on my ATTiny44a sensor chip.** This is what you can replace with ANYTHING, as long as it twiddles the [clock], [a], and [b] pins similarly.

```c
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define dtaprt PORTA
#define clk PA1
#define A PA2
#define B PA0
#define delayms 100 // increase to slow it down

void wait() { _delay_ms(delayms); }
void clockNow()
{
    dtaprt |= (1 << clk);
    wait();
    dtaprt &= ~(1 << clk);
    wait();
}
void sendSpace()
{
    dtaprt = (1 << B);
    clockNow();
}
void sendLine()
{
    dtaprt = (1 << B) | (1 << A);
    clockNow();
}
void sendOne()
{
    dtaprt = (1 << A);
    clockNow();
}
void sendZero()
{
    dtaprt = 0;
    clockNow();
}

// TAKE A READING FROM ADC7 AND SEND IT TO SERIAL CHIP

int main(void)
{
    DDRA |= (1 << clk);
    DDRA |= (1 << A);
    DDRA |= (1 << B);
    ADMUX = (1 << REFS1) | (1 << MUX2) | (1 << MUX1) | (1 << MUX0);    // ADC on ADC7 to 1.1v ref
    ADCSRA = (1 << ADEN) | (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2); // enable, prescale
    for (;;)
    {
        int data = ReadADC();
        sendData(data);
        sendSpace();
        sendData(data);
        sendLine();
        _delay_ms(1000);
    }
}

void sendData(int data)
{
    char datalen = 16;
    for (char pos = 0; pos < datalen; pos++)
    {
        if ((data >> pos) & 1)
        {
            sendOne();
        }
        else
        {
            sendZero();
        }
    }
}

int ReadADC()
{
    ADCSRA |= (1 << ADSC); // reset value
    while (ADCSRA & (1 << ADSC))
        ; // wait for measurement
    return ADC;
}
```

### UPDATE

I found a simpler way to convert binary numbers into strings ready to be sent in ASCII via USART serial port:

```c
void sendNum(unsigned int num)
{
    char theIntAsString[7];
    int i;
    sprintf(theIntAsString, "%u", num);
    for (i = 0; i < strlen(theIntAsString); i++)
    {
        send(theIntAsString[i]);
    }
}
```
August 27th, 2010

Hacking Together a Crystal Oven Part 2

With the last post's promising results, I set out to finish my crystal oven prototype and affix it to my QRSS MEPT prototype. If everything works well, I'm ready to publish the final schematic and parts lists! (and make several MEPTs for people who were interested in having one). I'm not confident my approach to the heater was the best, and am already thinking of ways I could have improved on its performance, but I think this just might work! I'll test it overnight (Styrofoam-enclosed vs. open air) and see how it does. I wonder if this is good enough to be used outside?

Markdown source code last modified on January 18th, 2021
---
title: Hacking Together a Crystal Oven Part 2
date: 2010-08-27 19:21:25
tags: circuit, qrss, old, microcontroller
---

# Hacking Together a Crystal Oven Part 2

__With the last post's promising results,__ I set out to finish my crystal oven prototype and affix it to my QRSS MEPT prototype. If everything works well, I'm ready to publish the final schematic and parts lists! (and make several MEPTs for people who were interested in having one). I'm not confident my approach to the heater was the best, and am already thinking of ways I could have improved on its performance, but I think this just might work! I'll test it overnight (Styrofoam-enclosed vs. open air) and see how it does. I wonder if this is good enough to be used outside?

![](https://www.youtube.com/embed/uVluqDqQZX0)

<div class="text-center img-border">

[![](IMG_3805_thumb.jpg)](IMG_3805.jpg)
[![](IMG_3824_thumb.jpg)](IMG_3824.jpg)
[![](IMG_3829_thumb.jpg)](IMG_3829.jpg)
[![](IMG_3832_thumb.jpg)](IMG_3832.jpg)
[![](IMG_3838_thumb.jpg)](IMG_3838.jpg)
[![](IMG_3848_thumb.jpg)](IMG_3848.jpg)

</div>

</li></ul>

Pages