November 29, 2009

Happy Thanksgiving

I really thought I'd do something this week, but at present. I am drinking wine with my chix0r, and playing with a robotic cockroach on the dining room table with my daughter. Screw it, it's a holiday weekend.

All I have for you this week is some information from my readings. When rummaging around at my house, I uncovered my old copy of TTL Cookbook by Don Lancaster - a classic! For fun, I looked up our 74HC164 shift register from last week. I learned that the function of this device is a lot like seating 8 people for Thanksgiving dinner, then ordering them all to attack the buffet at once :) There will be more on this when we get this in and put it to use. There wa also much other goodness I will be referring to in the future (555, 556 timers, etc). I have also been digging around in Applied Robotics by Edwin Wise. We will be making motor controllers using N-channel MOSFETs in the near future using plans from there.

OK enough for now. Time to go eat some lox, drink some wine, and count my blessings.

November 23, 2009

Shift Registers are Important

I started out this week's lap looking at my options. I had a RS232 shifter board kit. Interesting, but that's mostly a bunch of boring soldering. I just received a cool new Arduino Duemilanove! Sweeter than sweet, but I don't have the required version of AVR-GCC installed (you need 4.3.3 for the ATmega328 due to a bug in older versions - I currently run AVR-GCC version 4.3.0). Compiling software is not how I planned on spending my Saturday, so nixed. The 16x2 LCD display I bought to monkey around with sounded pretty good.  Figured it should be fun figuring out how to display something childish and dirty to the little guy!

Knowing practically nothing about the display, I started with a close examination of the hardware. Nothing dramatic, besides the display screen, the only other outstanding feature on the display was 16 solder pads on the edge. To figure out which pad was for what, I consulted the data sheet - and almost fell asleep! OK, from an EE perspective, all that stuff is interesting, but I thought this was not quite the right doc to start with. Too low, like in the freakin weeds low-level. Being the impatient pragmatist, I want to see working examples and overviews first, and then later on maybe we can put a microscope on in to scope out the bit plumbing. I found better (better, I mean because I could at least identify what was useful) info on the manufacturer's sheet. Found out I have 8 data lines, power (Vcc, Vss), some adjustment inputs, register select and read/write controls, not to mention some ambiguously labeled control input called "enable" (insert Spock sound byte: 'fascinating!'). I think I may understand what most of these might do. Now was the time to dig deeper though, since I didn't have enough to go on yet.

When ferreting out more info on the unit, I discovered that the HD44780 character display seems to be a defacto standard. This means many different manufacturers make character displays, using the same basic interface. This is a good thing. Why? Well because this means I will likely never need to read the datasheet ever again, since many engineers have already done this and documented the living dogshit out of it prior to my arrival. Have I mentioned that at this point I felt all mushy and awkward toward Peter Ouwehand for having an entire site dedicated to HD44780 character displays? I'm gonna send him a fruit bastket just for saving us from that nasty datasheet. He has examples! Examples!

I jumped quickly to a linked AVR example. For whatever reason, the first thing to leap out at me was the 10K trimmer required for the contrast adjustment. Luckily, after digging through my stuff I found that my arduino kit included a 10K trim pot. Why the 74HC164 interface IC on there didn't register in my consciousness first is an utter mystery. It did eventually though. And when I finally figured out what "serial in, parallel out shift register" means I knew my day was destined for shortness. Yep, the 74HC164 takes serial input and then outputs to a parallel device. This whole time I guess I had assumed the LCD display somehow used serial I/O. I imagine the datasheet may have had this info somewhere between all the clock timing specs and register state bitmaps, but really just seeing 8 data I/O pins should have tipped me off! Hey well I do learn eventually.

Without a shift register, I was pretty much done. Ordering one right now so we can do this up later. I spent the rest of my project time soldering up the RS232 shifter board. Looking great! Except I couldn't find my dikes to snip the legs. So tune in next week! Does Chuck find his dikes? Will he also notice that the example uses a dissimilar AT90S2313 micro? Will he reread the evil datasheet and slip into a coma? Why is there a pizza in the first picture of this blog? The suspense! Have a great week, and happy hacking everyone.

November 15, 2009

Mucking About with Code and UART I/O

While attending my daughter's dance recital Saturday, my mind stuck on the word "recital". The kids weren't reciting anything, they were dancing. Neither do kids at a piano recital actually recite anything, and so on*. "Recital" I suspect is one of those words originating out of a specific common event, which eventually broadened in definition to mean any event where a pupil demonstrates his progress and/or achievement in a very formal and public way. Once I sorted it out in my head, I realized I am performing sort of an electronics recital here, am I not? Only difference is, when I'm done I intend to launch killer flying killer robots instead of playing "Mary had a Little Lamb". Heck, I might even make flying killer robots that play "Mary had a Little Lamb"! Onward with the recital then...

I did Sparkfun's Beginning Embedded Electronics tutorial #5. It was labeled "AVR GCC Compiling", but I like my title better, since we really do just muck with some code and our serial interface some more. And that's cool with me, I have a little 16x2 serial display on the way; I need to get a handle on this stuff. I realized late last week that the subtext to last week's lab said we'd printf some foo to our monitor via a running program on the AVR, and somehow that never happened. Until now, of course.

I started by compiling and writing the "basic-out-atmega168" program to my micro. Of course I noticed right away that something wasn't quite right - The code was supposed run on the micro and output something like "Test it! x = 1Test it! x = 2Test it! x = 3Test it! x = 4Test it! x = 5" to my minicom (terminal emulator) screen. What I got was a bunch of garbled crap. Looked like the inventor of ASCII threw up in my term session. Good time to recap what we learned last week. I did a successful loopback test on the UART. Looking at the schematic for the max3232 indicated I tie RX and TX on the micro somehow to "R1OUT and T1IN".  A break in the drawing doesn't show which goes to which though. I guessed RX went to the transmit pin and TX to the receive pin. A basic crossover connection, right? Looking at the resultant garbled crap made me think about what the RS232 controller really does - it does some voltage foowankery, but basically it's a traffic cop, a pass through. That means the TX on the micro goes to T1IN and RX goes to R1OUT, and all would be fine. It was. Program now works. Just a note, Homework for this week is to see if I can manage 2 serial streams with this guy, cause I noticed a set of unused pins labeled R2xxx, T2xxx.



Can you spot my rookie screw up here? This setup can't work.

The tutorial goes over some basic methods used in C to twiddle bits, toggle GPIO pins, and set other options. After a while, it'd probably be good to spend some time rooting around header file avr/io.h to see what interesting AVR defines and directives exist. Even though the tutorial skirts around the subject, now is probably a real good time for me and anybody else who hasn't used a bitwise C operator since college to get a good refresher. They are of course used to enable things that could make life sweet, like the TX and RX pins (RXEN0 & TXEN0). More homework for lucky me. The author states that he never starts any code from scratch - he always modifies existing code. If I actually trusted other programmers, I might use this method. But since I trust neither the coders out there, nor coding contexts as germane to my efforts, I think I may spend more time getting familiar with the coding end of this whole thing. I can't recommend my way over Sparkfun Nate's, as it will be considerably more work, I imagine it just depends on whether you trust people or not. Damn, trusting people is a lot less work than my way. *sigh*


I won't discuss compiling and loading the second program, since it was uneventful, so that's it for now. Time to think about using the interface for more useful stuff. Like I said earlier, I have a 16x2 serial display en route. I'll see if I can get the micro to display to it next week.

The next 2 Sparkfun tutorials deal with soldering. I am probably going to skip these. This does not diminish the importance of good soldering technique, I am just already pretty good at this. Not sure about the CAD ones either. I have downloaded the free Eagle CAD software (good stuff! they have great Linux support!) and will use it to design my stuff, but I want to keep focusing on getting the micro to bend to my will, not peripheral stuff. So I guess that means I am pretty much done with the Basic Embedded tutorials at Sparkfun! Woooo! Be sure to check out their last one, which is basically things to do to prevent frustration and embarrassment. I should formally thank them for sharing all the learning material. I had fun and now know a little something about something.

*If one was performing an original oratory for the very first time, would that just be a "cital"? Or does one "cite" when first putting pen to paper? No, I would think it drafting or composing. And then everyone repeating it would then re-cite it? No, that would be speech, or speaking. But there is no "respeeching" or "respeaking", only recital. Strange word. Calling all linguists! Attack!

November 7, 2009

Installing and Testing a Serial Interface


As I wandered through the farmer's market in Urbana this morning, instead of thinking about tasty dishes I could cook, I was wondering if I could use the the old potato-battery trick to power a micro. So that pretty much tells you where my head is these days. According to this guy, we'd get 0.5V with 0.2mA, so that means we'd need what? A bakers dozen to safely power our ATMega168? Good to know if I ever get stranded without power in Idaho! Maybe for fun I'll do this later on.

Now, down to the business at hand: Today I hacked a serial interface onto the ATMega168, using a MAX232 IC, and tested it using Linux and minicom. I was loosely following Sparkfun's "UART and Serial Communications" tutorial, but with the normal diversions to use tools commonly used with Linux. In this case, the tutorial would have us test out the rs232 interface by firing up Hyperterminal (infernal Windows term thing). Yeah, you know me. I was all "we're totally not doing that."

Here's where I started: I have a max232 IC which is my serial interface. I really don't have to know much about it, other than the fact that it converts +/-12V signals to usable 0-5V signals for our micro and other UART magic (the charge pump link in the tutorial is pretty interesting though). I noticed again no mention of static guarding IC's; Am I just too anal about this? I still don't have a grounding strap for my wrist, but I grounded myself to the leg of the table before I carefully bent the pins and installed it on my breadboard.

It was nice to know about the decoupling caps - I suppose I should plan on keeping a bucket of 22 and 10 uF ceramics around. I noticed also we weren't using electrolytics anymore for decoupling. We used them for the 5V power supply, but not for the oscillator nor for this max232. Can anyone tell me when one is preferable over the other? The datasheets of course specify ceramics, and that's fine. I was just wondering.

When installing the caps, one thing jumped out at me. Caps decoupled pins 1&3, 2&6, 4&5. Pins 7&8 are unused. Sound familiar? It did to me. That is the wiring order for a CAT5 UTP crossover cable! And it made sense: Back in the day, the first ethernet cards I remember had serial-looking interfaces on the back and often required tranceivers to accept CAT5 with an RJ45 end. I should've made the connection back then, but probably had my mind on other crap! Just an interesting note.

I put a loop on the TX and RX pins of the IC, so whatever input I give it will be puked right back out. In this state, we are able test the proper functioning if the max232 by hooking up a terminal emulator or heck, even a real vt100 terminal if we want!.

The tutorial tells us to use Windows' Hyperterminal, or maybe TeraTerm. Nonsense I say! Linux! I used minicom. Minicom on my Linux laptop had no pre-set config, and defaulted to some bad defaults which I needed to change.

Welcome to minicom 2.3

OPTIONS: I18n 
Compiled on Oct 24 2008, 06:37:44.
Port /dev/tty8

              Press CTRL-A Z for help on special keys

You'll notice it defaults to tty8. We need to change that and switch the port speed to 9600bps. The quickest way to do this is to hit "ctrl-A O" once minicom starts.

+-----[configuration]------+
| Filenames and paths      |
| File transfer protocols  |
| Serial port setup        |
| Modem and dialing        |
| Screen and keyboard      |
| Save setup as dfl        |
| Save setup as..          |
| Exit                     |
+--------------------------+

I selected "Serial port setup" and made the following changes:

+-----------------------------------------------------------------------+
| A -    Serial Device      : /dev/ttyS0                                |
| B - Lockfile Location     : /var/lock                                 |
| C -   Callin Program      :                                           |
| D -  Callout Program      :                                           |
| E -    Bps/Par/Bits       : 9600 8N1                                  |
| F - Hardware Flow Control : Yes                                       |
| G - Software Flow Control : No                                        |
|                                                                       |
|    Change which setting?                                              |
+-----------------------------------------------------------------------+

I ran into problems here. It's worth noting that I spent a while troubleshooting a seemingly non-working serial connection. I would type and type; nothing ever got puked back to the console. I noticed that the wires running to the DB9 interface were a little too loose for my comfort, so I got out the soldering iron and a new slice of bread and fixed that mess. Still no worky. After beating my head on it for a while I figured out that somehow changing minicom on the fly does not always work. When I saved the settings to a minicom config file and restarted, all of the sudden the thing worked fine. Yesssssss! I took the loopback plug out and connected the RX and TX pins if the max232 to the RX and TX pins of the ATMega. Now we're ready for some cool I/O fun!

So next time I will be doing the AVR-GCC lab. Not sure if it will be me just going off on my own, but in any event I will be using my new serial interface to debug stuff, which is cool! Later for now, all - I'm gonna go look at cool 19x2 serial displays and russet potatoes!

November 1, 2009

Tick, Tock, Rockin the Clock with Crystal Oscillators

Yesterday I dove into Sparkfun's 3rd tutorial in the Beginning Embedded Electronics series, "What is an Oscillator?" I learned about using the AVR internal oscillator, ceramic resonators, and crystals as a clock source for my projects. Of course all did not go smoothly, which was fortunate (!) since the bumps highlighted some important things.


I started by reading a good article on clocksources on AVR Freaks. Knowing all the different sources and properties is cool, but I really didn't get a good feel for proper applications. I mean, I know the tolerances on ceramic resonators and the internal AVR osclllator aren't tight enough for your highly synchronized stuff like serial or network communication, but they are good for something, right? Besides blinking an LED, what is some other uses for ceramics and/or the internal? I'll try and look into this some more - If you have some experience with this, let me know in the comments.

I monkeyed around with the AVR internal clock by downloading the ATMega168 datasheet from the Atmel site, finding and toggling the CKDIV8 bit. As was expected; unprogramming this bit took our AVR clock output from 1MHz to 8MHz. With the "blink" code from last week still loaded, the LED on the output line started to blink faster. One confusing
thing I noted right here: the bit order listed in a fuse byte is read from bit7 to bit0, not the other way around. Seems backward, but I'll just have to remember this (it will of course, if I know myself, bite me in the ass in the future, stay tuned, heh)

I am still using avrdude on Ubuntu Linux (Intrepid) and a ponyser serial programmer. I practiced dumping the fuse bits set by executing the following on the CLI:
$ sudo avrdude -p m168 -P /dev/ttyS0 -c ponyser -U lfuse:r:-:h -U hfuse:r:-:h 
  avrdude: AVR device initialized and ready to accept instructions
    Reading | ################################################## | 100% 0.00s
    avrdude: Device signature = 0x1e9406
    avrdude: reading lfuse memory:
    Reading | ################################################## | 100% 0.00s
    avrdude: writing output file ""
    0x62
    avrdude: reading hfuse memory:
    Reading | ################################################## | 100% 0.00s
    avrdude: writing output file ""
    0xdf
    avrdude: safemode: Fuses OK
    avrdude done.  Thank you.
(I love how Avrdude thanks me. "No, thank YOU!") Setting the fuse bits is just a matter of figuring which bits you want to program, then using similar syntax to write them back out to the micro. When setting the CKDIV8 bit, I looked at the starting config of the low fuse byte (0x62) and figured out the new value when unprogramming (setting to "1") bit7. The value ends up being 0xe2. Using a calculator that does hex to binary conversions is very helpful. [NOTE: the fuse calculator in the tutorial is also tres useful: http://palmavr.sourceforge.net/cgi-bin/fc.cgi]
Next, I installed the 16MHz crystal on my breadboard, following the schematic in the tutorial. Note that at this point I feel very smug and proper, having installed caps properly, unlike the "bad engineer! bad!" image in the tutorial. This will be important later, trust me.
OK, having set up the hardware, I dug back into the ATMega168 datasheet in search of programming notes regarding selecting the external clock source which I just connected to pins 9 & 10 (PB6 & PB7). Section 1.1.3 of the Pin Descriptions section gave a nice description of the function and linked out directly to what I needed: section 8, System Clock & Clock Options. So I struggled a bit here to understand the different devices you could program up with the 4 CKSEL bits. For a minute there, I was pretty sure I had an "external clock" (0000), but after reading further, and double checking with the tutorial, I found the correct setting was "full swing XTAL oscillator" (0110). NOTE: My homework this week is to find out what qualifies as an "external clock". So, to set my 16MHz external xtal and caps setup as the oscillator, I set the low fuse bit to 11100110 (0xe6)! AND...and? Oh crap. Nothing. Nothing? As soon as I set the fuse bits on the micro, the output LED just quit. I immediatedly attempted to program the fuse low bits back to use internal RC and was met with the following bad news:
$ sudo avrdude -p m168 -P /dev/ttyS0 -c ponyser -U lfuse:w:0xE2:m

    avrdude: AVR device not responding
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.
This time the "thank you" kinda stung. Not responding, thanks? Did I brick my micro with a bad config? After staring for a while, I decided to dig a little. Checked my 5V rail: all good. Checked programmer connections: all ok. Checked fuse low bit config sent (0xe6): confirmed good config. Checked crystal connection: ok. That left the caps - I rolled my eyes and went through the motions of checking the caps, then noticed something odd - "104" marked on the sides. 104? As in, 10uF. Huh, these things were supposed to be 22uF! Pulled the 2nd one, it was also the wrong value. But whatever, right? I mean the demo photo on the tutorial showed no caps at all! However, the subtext was correct. Running with no caps or out-of-spec caps is a crap shoot. The datasheet section 8.4 listed acceptable values for caps C1 and C2 at 12-22uF. I pulled the incorrect caps, installed some 22uF ceramics, and woohoo! Wicked fast blinkage on the output LED. A couple test reads/writes on the micro verified I hadn't damaged anything. Sweet!

So, reading the datasheet and double checking your work are as important as always. Got it.I thinks my flickering LED would look good in a jack-o-lantern! Maybe by next year, I can get something in for Sparkfun's Hack-o-Lantern contest!

 Next week I will be using my cool xtal clock to power some comms! Doing the "UART and Serial Communication" Lab