The personal website of Scott W Harden
June 13th, 2009

UCF Tailgate June 2009

This morning I woke up at 4:45am, hopped out of bed, and raced to the university parking lot for field day. It's pretty much a flea market with an emphasis in ham radio and associated electronics. This is a panorama of the parking lot the tailgate was held in, taken from the roof of a parking garage at about 9am. The UCF ARC (the amateur radio club which sponsored the event) is stationed under the white tent.

My goal was to purchase a [working] oscilloscope, and I lucked-out. I ended-up purchasing two, and I'm glad I did! The 1st one (the one with the green circular screen) crapped-out on me after literally 1 minute. (By crapped-out I mean it started spurring thick gray smoke and made my whole apartment smell like a burned marshmallow). At $5, I'm not crying over it. The second one is a 1969 Tektronix 561A 10 MHz oscilloscope. Just think, these things just started started being produced the same year Neil Armstrong walked on the moon. I tested it and it seems to be functioning well. At $10, I'm very happy!

Here you can see it attached to my prime number generator described in agonizingly-boring detail over the last several weeks' posts. It's attached to one of the microcontroller pins responsible for multiplexing the LED display. Finally, a way to assess high speed power output as a function of time. The output of the microcontroller isn't performing like I expected, and since it's a series of pulses I can't use a volt meter to measure its output. Thus, the need [more like desire] for an oscilloscope.

Markdown source code last modified on January 18th, 2021
---
title: UCF Tailgate June 2009
date: 2009-06-13 17:14:08
---

# UCF Tailgate June 2009

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

[![](ucf_tailgate_2009_thumb.jpg)](ucf_tailgate_2009.jpg)

</div>

__This morning I woke up at 4:45am__, hopped out of bed, and raced to the university parking lot for field day. It's pretty much a flea market with an emphasis in ham radio and associated electronics. This is a panorama of the parking lot the tailgate was held in, taken from the roof of a parking garage at about 9am. The [UCF ARC](www.k4ucf.ucf.edu/) (the amateur radio club which sponsored the event) is stationed under the white tent.

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

[![](scopes_thumb.jpg)](scopes.jpg)

</div>

__My goal was to purchase a \[working\] oscilloscope__, and I lucked-out. I ended-up purchasing two, and I'm glad I did! The 1st one (the one with the green circular screen) crapped-out on me after literally 1 minute. (By crapped-out I mean it started spurring thick gray smoke and made my whole apartment smell like a burned marshmallow). At $5, I'm not crying over it. The second one is a [1969 Tektronix 561A 10 MHz oscilloscope](http://www.barrytech.com/tektronix/vintage/tek561a.html). Just think, these things just started started being produced the same year Neil Armstrong walked on the moon. I tested it and it seems to be functioning well. At $10, I'm very happy!

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

[![](scope_box_thumb.jpg)](scope_box.png)

</div>

__Here you can see it attached to my prime number generator__ described in agonizingly-boring detail over the last several weeks' posts. It's attached to one of the microcontroller pins responsible for multiplexing the LED display. Finally, a way to assess high speed power output as a function of time. The output of the microcontroller isn't performing like I expected, and since it's a series of pulses I can't use a volt meter to measure its output. Thus, the need \[more like desire\] for an oscilloscope.

Python-Powered Frequency Activity Logger

I'm often drawn toward projects involving data analysis with Python. When I found out a fellow ham in Orlando was using his computer to stream a popular local repeater frequency over the internet I got excited because of the potential for generating data from the setup. Since this guy already has his radio connected to his PC's microphone jack, I figured I could write a Python app to check the microphone input to determine if anyone is using the frequency. By recording when people start and stop talking, I can create a log of frequency activity. Later I can write software to visualize this data. I'll talk about that in a later post. For now, here's how I used Python and a Linux box (Ubuntu, with the python-alsaaudio package installed) to generate such logs.

We can visualize this data using some more simple Python code. Long term it would be useful to visualize frequency activity similarly to how I graphed computer usage at work over the last year but for now since I don't have any large amount of data to work with. I'll just write cote to visualize a QSO (conversation) with respect to time. It should be self-explanatory. This data came from data points displayed in the video (provided at the end of this post too).

And, of course, the code I used to generate the log files (seen running in video above): Briefly, this program checks the microphone many times every second to determine if its state has changed (talking/no talking) and records this data in a text file (which it updates every 10 seconds). Matplotlib can EASILY be used to graph data from such a text file.

import alsaaudio, time, audioop, datetime
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
inp.setchannels(1)
inp.setrate(4000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1)

squelch = False
lastLog = 0
dataToLog = ""

def logIt(nowSquelch):
 global dataToLog, lastLog
 timeNow = datetime.datetime.now()
 epoch = time.mktime(timeNow.timetuple())
 if nowSquelch==True: nowSquelch=1
 else: nowSquelch=0
 logLine="%s %dn"%(timeNow, nowSquelch)
 print timeNow, nowSquelch
 dataToLog+=logLine
 if epoch-lastLog&gt;10:
 #print "LOGGING..."
 f=open('squelch.txt','a')
 f.write(dataToLog)
 f.close()
 lastLog = epoch
 dataToLog=""

while True:
 l,data = inp.read()
 if l:
 vol = audioop.max(data,2)
 #print vol #USED FOR CALIBRATION
 if vol&gt;800: nowSquelch = True
 else: nowSquelch = False
 if not nowSquelch == squelch:
 logIt(nowSquelch)
 squelch = nowSquelch
 time.sleep(.01)

To use this code make sure that you've properly calibrated it. See the "vol>800" line? That means that if the volume in the microphone is at least 800, it's counted as talking, and less than it's silence. Hopefully you can find a value that counts as silence when the squelch is active, but as talking when the squelch is broken (even if there's silence). This is probably best achieved with the radio outputting at maximum volume. You'll have to run the program live with that line un-commented to view the data values live. Find which values occur for squelch on/off, and pick your threshold accordingly.

After that you can visualize the data with the following code. Note that this is SEVERELY LIMITED and is only useful when graphing a few minutes of data. I don't have hours/days of data to work with right now, so I won't bother writing code to graph it. This code produced the graph seen earlier in this page. Make sure matplotlib is installed on your box.

import pylab

def loadData():
 #returns Xs
 import time, datetime, pylab
 f=open('good.txt')
 raw=f.readlines()
 f.close()
 onTimes=[]
 timeStart=None
 lastOn=False
 for line in raw:
 if len(line)&lt;10: continue
 line = line.strip('n').split(" ")
 t=line[0]+" "+line[1]
 t=t.split('.')
 thisDay=time.strptime(t[0], "%Y-%m-%d %H:%M:%S")
 e=time.mktime(thisDay)+float("."+t[1])
 if timeStart==None: timeStart=e
 if line[-1]==1: stat=True
 else: stat=False
 if not lastOn and line[-1]=="1":
 lastOn=e
 else:
 onTimes.append([(lastOn-timeStart)/60.0,
 (e-timeStart)/60.0])
 lastOn=False
 return onTimes

times = loadData()
pylab.figure(figsize=(8,3))
for t in times:
 pylab.fill([t[0],t[0],t[1],t[1]],[0,1,1,0],'k',lw=0,alpha=.5)
pylab.axis([None,None,-3,4])
pylab.title("A little QSO")
pylab.xlabel("Time (minutes)")
pylab.show()
Markdown source code last modified on January 18th, 2021
---
title: Python-Powered Frequency Activity Logger
date: 2009-06-12 17:42:32
---

# Python-Powered Frequency Activity Logger

__I'm often drawn toward projects involving data analysis with Python. __When I found out a fellow ham in Orlando was using his computer to stream a popular local repeater frequency over the internet I got excited because of the potential for generating data from the setup. Since this guy already has his radio connected to his PC's microphone jack, I figured I could write a Python app to check the microphone input to determine if anyone is using the frequency. By recording when people start and stop talking, I can create a log of frequency activity. Later I can write software to visualize this data. I'll talk about that in a later post. For now, here's how I used Python and a Linux box (Ubuntu, with the python-alsaaudio package installed) to generate such logs.

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

__We can visualize this data__ using some more simple Python code. Long term it would be useful to visualize frequency activity similarly to [how I graphed computer usage at work over the last year](2009-05-20-graphing-computer-usage/) but for now since I don't have any large amount of data to work with. I'll just write cote to visualize a QSO (conversation) with respect to time. It should be self-explanatory. This data came from data points displayed in the video (provided at the end of this post too).

<div class="text-center">

[![](qsographpng_thumb.jpg)](qsographpng.png)

</div>

__And, of course, the code I used to generate the log files (seen running in video above):__ Briefly, this program checks the microphone many times every second to determine if its state has changed (talking/no talking) and records this data in a text file (which it updates every 10 seconds). Matplotlib can EASILY be used to graph data from such a text file.

```python
import alsaaudio, time, audioop, datetime
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
inp.setchannels(1)
inp.setrate(4000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1)

squelch = False
lastLog = 0
dataToLog = ""

def logIt(nowSquelch):
 global dataToLog, lastLog
 timeNow = datetime.datetime.now()
 epoch = time.mktime(timeNow.timetuple())
 if nowSquelch==True: nowSquelch=1
 else: nowSquelch=0
 logLine="%s %dn"%(timeNow, nowSquelch)
 print timeNow, nowSquelch
 dataToLog+=logLine
 if epoch-lastLog&gt;10:
 #print "LOGGING..."
 f=open('squelch.txt','a')
 f.write(dataToLog)
 f.close()
 lastLog = epoch
 dataToLog=""

while True:
 l,data = inp.read()
 if l:
 vol = audioop.max(data,2)
 #print vol #USED FOR CALIBRATION
 if vol&gt;800: nowSquelch = True
 else: nowSquelch = False
 if not nowSquelch == squelch:
 logIt(nowSquelch)
 squelch = nowSquelch
 time.sleep(.01)

```

__To use this code__ make sure that you've properly calibrated it. See the "vol&gt;800" line? That means that if the volume in the microphone is at least 800, it's counted as talking, and less than it's silence. Hopefully you can find a value that counts as silence when the squelch is active, but as talking when the squelch is broken (even if there's silence). This is probably best achieved with the radio outputting at maximum volume. You'll have to run the program live with that line un-commented to view the data values live. Find which values occur for squelch on/off, and pick your threshold accordingly.

__After that you can visualize__ the data with the following code. Note that this is SEVERELY LIMITED and is only useful when graphing a few minutes of data. I don't have hours/days of data to work with right now, so I won't bother writing code to graph it. This code produced the graph seen earlier in this page. Make sure matplotlib is installed on your box.

```python
import pylab

def loadData():
 #returns Xs
 import time, datetime, pylab
 f=open('good.txt')
 raw=f.readlines()
 f.close()
 onTimes=[]
 timeStart=None
 lastOn=False
 for line in raw:
 if len(line)&lt;10: continue
 line = line.strip('n').split(" ")
 t=line[0]+" "+line[1]
 t=t.split('.')
 thisDay=time.strptime(t[0], "%Y-%m-%d %H:%M:%S")
 e=time.mktime(thisDay)+float("."+t[1])
 if timeStart==None: timeStart=e
 if line[-1]==1: stat=True
 else: stat=False
 if not lastOn and line[-1]=="1":
 lastOn=e
 else:
 onTimes.append([(lastOn-timeStart)/60.0,
 (e-timeStart)/60.0])
 lastOn=False
 return onTimes

times = loadData()
pylab.figure(figsize=(8,3))
for t in times:
 pylab.fill([t[0],t[0],t[1],t[1]],[0,1,1,0],'k',lw=0,alpha=.5)
pylab.axis([None,None,-3,4])
pylab.title("A little QSO")
pylab.xlabel("Time (minutes)")
pylab.show()
```

Prime Prototype Construction

Now that I've worked-out the software side of the microcontroller-powered prime number generator, it's time to start working on the hardware. I want to make a prototype which is far smaller and simpler than the final version but lets me practice driving lots of LEDs (30). I expect the final version to have around 80. Also, the heart of this project is an ATTiny2313 microcontroller, and for the full version I'd like to use an ATMEega8. I picked up an unfinished wooden box with a magnetic latch from Michaels. It's delicate and tends to chip when you drill it, but moving slowly I'm able to make nice evenly-spaced holes.

This is the circuit concept. The chip is an ATTiny2313, sourced with 5V, where the left pins control the columns (by providing current) and the right pins control the rows (by providing ground). The "holes" at the top of the circuit represent where I hook up my PC and external power for testing purposes.

Thoughts from Future Scott (10 years later, August, 2019)

A+ for enthusiasm and construction but your design is... just no!

Why are you using an external crystal?

The schematic for the crystal is wrong: those capacitors should be to ground not in series!

You made the circuit diagram in InkScape!

You shouldn't drive current directly out of the microcontroller pins.

The majority of the microcontroller CPU cycles will go into managing multiplexing of the display (not calculating primes).

After a little more work I have a functional device and it looks better than I expected. There are a few more features I want to add, and I want to work on the code some more, but I hope to be done tomorrow. The coolest part is that I've included an internal button which drives a pause/resume and speed-controller menu based upon the length of button presses! There's a lot of awesome stuff I want to write, but once again, I'll save it for the completed project page.

I rendered the cover sticker wrong and all the LEDs are mislabled. The first LED should be 2^0 (1), and the second should be 2^1 (2), etc. Also, 2^22 and 2^23 are mislabeled - oops! But the thing really does generate, differentiate, and display [only[ prime numbers. Once again, videos (including demonstration of the menus and the programming options) and source code will be posted soon.

Markdown source code last modified on January 18th, 2021
---
title: Prime Prototype Construction
date: 2009-06-04 12:46:18
tags: circuit, microcontroller
---

# Prime Prototype Construction

__Now that I've worked-out the software side of the microcontroller-powered prime number generator, it's time to start working on the hardware.__ I want to make a prototype which is far smaller and simpler than the final version but lets me practice driving lots of LEDs (30). I expect the final version to have around 80. Also, the heart of this project is an ATTiny2313 microcontroller, and for the full version I'd like to use an ATMEega8. I picked up an unfinished wooden box with a magnetic latch from Michaels. It's delicate and tends to chip when you drill it, but moving slowly I'm able to make nice evenly-spaced holes.

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

[![](img_2028_thumb.jpg)](img_2028.jpg)
[![](img_2041_thumb.jpg)](img_2041.jpg)
[![](img_2043_thumb.jpg)](img_2043.jpg)
[![](img_2047_thumb.jpg)](img_2047.jpg)
[![](img_2054_thumb.jpg)](img_2054.jpg)
[![](img_2056_thumb.jpg)](img_2056.jpg)
[![](img_2057_thumb.jpg)](img_2057.jpg)
[![](img_2058_thumb.jpg)](img_2058.jpg)
[![](img_2062_thumb.jpg)](img_2062.jpg)
[![](img_2025_thumb.jpg)](img_2025.jpg)

</div>

__This is the circuit concept. __The chip is an ATTiny2313, sourced with 5V, where the left pins control the columns (by providing current) and the right pins control the rows (by providing ground). The "holes" at the top of the circuit represent where I hook up my PC and external power for testing purposes.

<div class="text-center">

[![](prime-number-broken-circuit_thumb.jpg)](prime-number-broken-circuit.png)

</div>

<blockquote class="wp-block-quote"><p><strong>Thoughts from Future Scott (10 years later, August, 2019)</strong></p><p>A+ for enthusiasm and construction but your design is... just no!</p><p>Why are you using an external crystal? </p><p>The schematic for the crystal is wrong: those capacitors should be to ground not in series!</p><p>You made the circuit diagram in InkScape!</p><p>You shouldn't drive current directly out of the microcontroller pins.</p><p>The majority of the microcontroller CPU cycles will go into managing multiplexing of the display (not calculating primes).</p></blockquote>

__After a little more work I have a functional device__ and it looks better than I expected. There are a few more features I want to add, and I want to work on the code some more, but I hope to be done tomorrow. The coolest part is that I've included an internal button which drives a pause/resume and speed-controller menu based upon the length of button presses! There's a lot of awesome stuff I want to write, but once again, I'll save it for the completed project page.

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

[![](img_2066_thumb.jpg)](img_2066.jpg)
[![](img_2076_thumb.jpg)](img_2076.jpg)
[![](img_2085_thumb.jpg)](img_2085.jpg)
[![](img_2089_thumb.jpg)](img_2089.jpg)

</div>

__I rendered the cover sticker wrong and all the LEDs are mislabled.__ The first LED should be 2^0 (1), and the second should be 2^1 (2), etc. Also, 2^22 and 2^23 are mislabeled - oops! But the thing really does generate, differentiate, and display \[only\[ prime numbers. Once again, videos (including demonstration of the menus and the programming options) and source code will be posted soon.

Prime Number Generator Prototype

In my quest to build a hardware-based prime number generator I built a rapid prototype to assess how quickly primes can be found with an 8-bit microcontroller. There is a lot of room for improvement, but the code works. Instead of messing with tons of little LEDs, this design displays numbers on an LCD. Interestingly the library to run the LCD takes up about 90% of the memory of the chip leaving only a handful of bytes to write the prime calculation code in!

#define F_CPU 1E6
#include <stdlib.h>
#include <avr/io.h>
#include <math.h>
#include <util/delay.h>
#include "lcd.h"
#include "lcd.c"

const unsigned long int primeMax=pow(2,25);
unsigned long int primeLast=2;
unsigned long int primeTest=0;
unsigned int primeDivy=0;

void wait(void);
void init(void);
void updateDisplay(void);
char *toString(unsigned long int);

int main(void){
    init();
    short maybePrime;
    unsigned int i;
    for(primeTest=2;primeTest<sqrt(primeMax);primeTest++){
        maybePrime=1;
        for (i=2;i<=(sqrt(primeTest)+1);i++){
            primeDivy=i;
            updateDisplay();
            if (primeTest%primeDivy==0){maybePrime=0;break;}
        }
        if (maybePrime==1){primeLast=primeTest;updateDisplay();}
    }
    return 0;
}

void updateDisplay(void){
    lcd_gotoxy(12,0);lcd_puts(toString(primeLast));
    lcd_gotoxy(5,1);lcd_puts(toString(primeTest));
    lcd_gotoxy(16,1);lcd_puts(toString(primeDivy));
    return;
}

void init(void){
    lcd_init(LCD_DISP_ON);
    lcd_puts("PRIME IDENTIFICATIONn");
    _delay_ms(2000);
    lcd_clrscr();
    lcd_puts("LAST PRIME:n");
    lcd_puts("TRY:");
    lcd_gotoxy(14,1);lcd_puts("/");
    return;
}

char *toString(unsigned long int x){
    char s1[8];
    ltoa(x,s1,10);
    return s1;
}
Markdown source code last modified on January 18th, 2021
---
title: Prime Number Generator Prototype
date: 2009-05-30 18:22:58
tags: microcontroller, old
---

# Prime Number Generator Prototype

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

[![](img_1984_thumb.jpg)](img_1984.jpg)

</div>

__In my quest to build a hardware-based prime number generator__ I built a rapid prototype to assess how quickly primes can be found with an 8-bit microcontroller. There is a lot of room for improvement, but the code works. Instead of messing with tons of little LEDs, this design displays numbers on an LCD. Interestingly the library to run the LCD takes up about 90% of the memory of the chip leaving only a handful of bytes to write the prime calculation code in!

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

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

</div>

```c
#define F_CPU 1E6
#include <stdlib.h>
#include <avr/io.h>
#include <math.h>
#include <util/delay.h>
#include "lcd.h"
#include "lcd.c"

const unsigned long int primeMax=pow(2,25);
unsigned long int primeLast=2;
unsigned long int primeTest=0;
unsigned int primeDivy=0;

void wait(void);
void init(void);
void updateDisplay(void);
char *toString(unsigned long int);

int main(void){
    init();
    short maybePrime;
    unsigned int i;
    for(primeTest=2;primeTest<sqrt(primeMax);primeTest++){
        maybePrime=1;
        for (i=2;i<=(sqrt(primeTest)+1);i++){
            primeDivy=i;
            updateDisplay();
            if (primeTest%primeDivy==0){maybePrime=0;break;}
        }
        if (maybePrime==1){primeLast=primeTest;updateDisplay();}
    }
    return 0;
}

void updateDisplay(void){
    lcd_gotoxy(12,0);lcd_puts(toString(primeLast));
    lcd_gotoxy(5,1);lcd_puts(toString(primeTest));
    lcd_gotoxy(16,1);lcd_puts(toString(primeDivy));
    return;
}

void init(void){
    lcd_init(LCD_DISP_ON);
    lcd_puts("PRIME IDENTIFICATIONn");
    _delay_ms(2000);
    lcd_clrscr();
    lcd_puts("LAST PRIME:n");
    lcd_puts("TRY:");
    lcd_gotoxy(14,1);lcd_puts("/");
    return;
}

char *toString(unsigned long int x){
    char s1[8];
    ltoa(x,s1,10);
    return s1;
}
```

May 27th, 2009

A Prime Idea

I'm completely drained of energy. I visited my wife's family in Tennessee last week. I left Thursday and came back Tuesday (yesterday). I drove a total of 2,180 miles. The drive to Humboldt, TN (the destination) and back is only 1,658 miles. That means that I drove over 520 miles over the 3 days while at my destination. That's about 174 miles a day. At 50 MPH average speed that's about 4 hours in the car. So, 13 hour drive (each way) to get there, then 4 hours in the car every day I was there. That's a lot of car time!

While speaking with my brother-in-law (who just got a BS in computer science with a minor in mathematics) I learned that a faculty member at the university challenged him to write a computer program which could find the N'th prime number (up to 10^15) for a graduate school project. I was fascinated by the idea project and the various techniques, and workarounds related to it. After working on the theory behind the software (which I tested in Python) for a few hours, I had the idea to attempt to perform a similar task at the microcontroller level.

Here's the project I want to begin: I want to build a microcontroller-powered prime number generator which displays results in binary. The binary-encoded output is similar to the binary clocks which are nothing new. My project will calculate prime numbers up to 2^25 (33,554,432) and display the results in binary using long strips of 20 LEDs. There will be 3 rows of LEDs. The middle row (red) will simply count from 0 to 2^25. Every time it gets to a new number, the bottom row (blue) counts from 0 to the square root of the middle row. For every number on the bottom row, the remainder (modulus) of the middle/bottom is calculated. If the remainder is 0, the middle (red) number is divisible by the bottom (blue) therefore it is not prime. If the bottom number gets all the way to the square root of the middle number, the middle number is assumed to be prime and it is copied to the top row (green). The top row displays the most recent number determined to be prime.

Technical details of the project further reveal its dual simplicity/complexity nature. I'll add some buttons/switches for extra features. For example, I want to be able to start the program at a number of my choosing rather than forcing it to start at 0. Also, I want to be able to adjust the speed at which it runs (I don't want the blue row to just flicker forever). The ATTiny2313 (my microcontroller of choice because I have a few extra of them) has 18 IO pins. If I get creative with my multiplexing techniques, I can probably run 81 LEDs from 18 pins (9 rows of 9 LEDs). I've specifically chosen against charlieplexing because I will be lighting many LEDs "simultaneously" and I think the degree of flicker would be far too great to satisfy my sensitive eyes, even though I could do it all with only 10 pins.

I've decided to transistorize the entire project to provide a greater and more constant current to the LEDs. I'll use a set of 9 transistors to set the row that gets power (when the microcontroller powers the base, the row gets power) and another set of 9 transistors to set the LEDs in each row that light up (when the microcontroller powers the base, the LED gets grounded and lights up). To have consistently-bright, non-flickering LEDs which don't dim as more LEDs illuminate, I will add a resistor to every LED. Maybe I can get creative and utilize 10-pin resistor networks (one for each row) immediately after the row-selecting transistor! That will save me so much time. (I just came up with that idea - just now!) Anyway, that's my project idea.

I'd love to make this project look nice. All of my other projects were housed in junky plastic or cardboard boxes (if they were housed at all!) and this is something I want to keep. I start dental school soon, and I've love to have a fancy-looking piece of artsy/geeky/electrical memorabilia so I'll never forget who I am, my roots, and my true interests. Plus, it will give me something groovy to stare at when I come home after a long day cleaning the teeth of manikins and wondering why I went to dental school [sigh].

Update (nextday): I've been toying over some various layouts for the LEDs. I most like the rectangle and hex-rectangle configurations, and am already working on assembly of the "mini" (prototype). Here are some random images of my thinking process.

Markdown source code last modified on January 18th, 2021
---
title: A Prime Idea
date: 2009-05-27 10:28:19
tags: old, circuit
---

# A Prime Idea

__I'm completely drained of energy.__ I visited my wife's family in Tennessee last week. I left Thursday and came back Tuesday (yesterday). I drove a total of 2,180 miles. The drive to Humboldt, TN (the destination) and back is only 1,658 miles. That means that I drove over 520 miles over the 3 days _while_ at my destination. That's about 174 miles a day. At 50 MPH average speed that's about 4 hours in the car. So, 13 hour drive (each way) to get there, then 4 hours in the car every day I was there. That's a lot of car time!

__While speaking with my brother-in-law__ (who just got a BS in computer science with a minor in mathematics) I learned that a faculty member at the university challenged him to write a computer program which could find the N'th prime number (up to 10^15) for a graduate school project. I was fascinated by the idea project and the various techniques, and workarounds related to it. After working on the theory behind the software (which I tested in Python) for a few hours, I had the idea to attempt to perform a similar task at the microcontroller level.

<div class="text-center">

[![](prime_binary_thumb.jpg)](prime_binary.png)

</div>

__Here's the project I want to begin:__ I want to build a microcontroller-powered prime number generator which displays results in binary. The binary-encoded output is similar to the [binary clocks](http://www.thinkgeek.com/interests/giftsforhim/59e0/) which are nothing new. My project will calculate prime numbers up to 2^25 (33,554,432) and display the results in binary using long strips of 20 LEDs. There will be 3 rows of LEDs. The middle row (red) will simply count from 0 to 2^25. Every time it gets to a new number, the bottom row (blue) counts from 0 to the square root of the middle row. For every number on the bottom row, the remainder (modulus) of the middle/bottom is calculated. If the remainder is 0, the middle (red) number is divisible by the bottom (blue) therefore it is not prime. If the bottom number gets all the way to the square root of the middle number, the middle number is assumed to be prime and it is copied to the top row (green). The top row displays the most recent number determined to be prime.

__Technical details of the project__ further reveal its dual simplicity/complexity nature. I'll add some buttons/switches for extra features. For example, I want to be able to start the program at a number of my choosing rather than forcing it to start at 0. Also, I want to be able to adjust the speed at which it runs (I don't want the blue row to just flicker forever). The ATTiny2313 (my microcontroller of choice because I have a few extra of them) has 18 IO pins. If I get creative with my [multiplexing techniques](http://en.wikipedia.org/wiki/Multiplexed_display), I can probably run 81 LEDs from 18 pins (9 rows of 9 LEDs). I've specifically chosen against [charlieplexing](http://en.wikipedia.org/wiki/Charlieplexing) because I will be lighting many LEDs "simultaneously" and I think the degree of flicker would be far too great to satisfy my sensitive eyes, even though I could do it all with only 10 pins.

__I've decided to transistorize__ the entire project to provide a greater and more constant current to the LEDs. I'll use a set of 9 transistors to set the row that gets power (when the microcontroller powers the base, the row gets power) and another set of 9 transistors to set the LEDs in each row that light up (when the microcontroller powers the base, the LED gets grounded and lights up). To have consistently-bright, non-flickering LEDs which don't dim as more LEDs illuminate, I will add a resistor to every LED. Maybe I can get creative and utilize [10-pin resistor networks](http://www.gino-midi.nl/Electr_pagina_afbeeldingen/!SIL10_9.jpg) (one for each row) immediately after the row-selecting transistor! That will save me so much time. (I just came up with that idea - just now!) Anyway, that's my project idea.

__I'd love to make this project look nice.__ All of my other projects were housed in junky plastic or cardboard boxes (if they were housed at all!) and this is something I want to keep. I start dental school soon, and I've love to have a fancy-looking piece of artsy/geeky/electrical memorabilia so I'll never forget who I am, my roots, and my true interests. Plus, it will give me something groovy to stare at when I come home after a long day cleaning the teeth of manikins and wondering why I went to dental school \[sigh\].

__Update (nextday):__ I've been toying over some various layouts for the LEDs. I most like the rectangle and hex-rectangle configurations, and am already working on assembly of the "mini" (prototype). Here are some random images of my thinking process.

<div class="text-center">

[![](prime_layout_2_thumb.jpg)](prime_layout_2.png)
[![](g12684_thumb.jpg)](g12684.png)
[![](rect7887_thumb.jpg)](rect7887.png)

</div>
Pages