Kossel Mini Build

Originally posted on www.letsmakerobots.com

I thought I should give my Kossel a “Robot” page, since Silas asked what the Kossel was, and I told him, “A 3D Printer,” to which my precocious son replied, “No, it’s a robot.”

A lot of the information here is a copy from my build blog, but I’ve re-thought it’s presentation slightly, since there preexist two build guides for the Kossel.

  1. Blokmer’s Kossel Mini Build Guide
  2. builda3dprinter’s Kossel Build Guide

Both are put together by organizations selling Kossel kits. Blokmer’s guide is much more detailed and slow paced. Of course, I purchased my kit from builda3dprinter (here on referred to as B3DP) and tried to use their guide as much is possible, that said, the B3DP guide has a lot missing information. I wont bitch too much, since I’ve enjoyed their kit, but it does bring me to how I’ll approach the information here.

I’m going to write this guide as a supplement to existing build guides. For example, the Kossel has an auto-level probe that is somewhat problematic to assemble. Both guides did a poor job of explaining several key parts of its assembly. Therefore, I’ll focus primarily on missing information.

Purchasing the Kossel materials:

I sourced a few parts from China and purchased the major parts from www.builda3dprinter.eu.

eBay and Fasttech

3 x NEMA 17 Motors: $42.00

1 x Planetary Stepper: $60.00

12V, 30A Power Supply: $31.39

Ramps and A4988 Drivers: $31.00

Arduino Mega: $15.81

J-head MK-V, 0.4MM Nozzle, 1.75MM: $36.99

For the rest, I bought several “kits” from www.builda3dprinter.eu.

B3DP Kits

Kossel Kit (plastic parts): $55

Nuts and Bolts kit for Kossel: $30

OpenBeam Kit for Kossel: $70

Rails to Wheels conversion kit: $50

The rest: $115

Shipping: ~$50.00

Total for Essentials: $587.19

After purchasing all the essentials I bought a few things I felt would make the build neat.

Scrunchy Wire Wrap: $10.02

Little zip-ties x 100: $3.85

Big zip-ties x 50: $4.85

Colorful heat-shrink x 140: $11.78

Total for Neatness: $30.50

Total Essetials and Neatness: $617.69

Regarding www.builda3dprinter.eu

I need to say I’ve mixed feelings towards B3DP. Being a mental-health worker, when someone has mixed feelings we create a T-Chart of pros and cons. Here’s mine on B3DP kit.


  1. Shorted ~20 M3 Nuts.
  2. Six weeks for processing and delivery
  3. No clear documentation on the effector provided
  4. Missing Allen key, springs, and safety pin (for auto-probe). This is not included in their list of what’s not included.
  5. Pin connectors are cheap and not reliable
  6. Huge holes in documentation (Blokmer rocks this one).


  1. Plastic part quality is excellent.
  2. Responded to delays by giving me a free borisillicate plate.
  3. Communicate well (they responded quickly to all my questions).
  4. Their kits **do **work well together.

In fairness, I’m not done with the build, but writing this out, I’d say I would buy B3DP kits again.

The bit it’s difficult to put a price on is part precision and synergize. Since the parts are meant to work together, calibration is much simplier (still not easy). For instance, instead of having to measure out the length of rods, carriage offset, etc. B3DP provided a Marlin (firmware for delta) with these measurements already input. In sum, half of the calibration is already done by B3DP.

Purchase “Doh”s!

1. Effector mismatch:

B3DP provided me with a MK V end effector and I bought MK IV J-Head extruder that was advertised as an MK V. Point to you eBay. So far, this hasn’t caused any problems, I simply pulled the brass end off my extruder and pushed it into place. Not sure of the open area between the effector plastic and the PTFE tubing will cause me problems down the road, like filament bunching.

2. Must have a Geared Stepper motor for extruder:

I purchased my stepper motors in a lot of five. I thought, “I’ll use 3 for the X, Y, Z axes and one 1 for the extruder.” Well, this is where I should have done more research. The original design for the Kossel requires a NEMA 17 Geared Stepper Motor. So, I broke down and ordered a geared stepper-motor for the extruder. I was a little under budget and felt it was a better choice rather than struggling trying to get the current motor I had to work with what B3DP sent.

But to be clear the extruder from B3DP is built for a stepper-motor with a 8mm shaft. Actually, the parts are from the original design which called for a geared-stepper motor and a spur-gear with 22 teeth, with a 8mm diameter shaft. The “common” NEMA17 has a 5mm diameter shaft. I’ve seen a few extruder designs that use a regular stepper and a 5mm diamter spur-gear, but that is not what comes with the B3DP kit.


Like I stated, I’m no going into a lot of detail about the assembly, since there exist two guides. But I’ll include time-lapse of most of the build (what was easy to film) and notes on stuff not in the exist build-guides.

1. Jig Setup & Traxxas Ends

The Blokemer guide states I should tap and drill the Traxxas ends and the carbon rods. I bought a metric tap and die set from Harbor Freight, but when I examined the pieces I received from B3DP I noticed the headless bolts were too small to catch the inside of the carbon rods. Also, I wasn’t sure how to use my tap and die; this devolved into the realization I had the wrong thread sizes. Makes sense, I was using a US tool and parts from everywhere else but the US.

Well, I lucked out. According to the B3DP manual you don’t need to tap anything. Just screw the headless bolts into the Traxxas ends, then use slow-setting Epoxy to glue the ends into the carbon rods. Screwing the headless bolts in the Traxxas ends went great. Um, gluing was another matter.

Not much to say about setting up the jigs for the carbon rods and Traxxas ends. Just follow the instructions on pages 3-6 of the Blomker guide. I used a square and a speed-square, the square to align the rails flush, then the speed-square to align the machine screws at one end. I’ve read that the arms can deviate from the 180mm outlined by the guide, but they should all be the same length. My goal was to identify rods longer than the others and file them down a little.

Post-build note: I found to “spare” objects in my plastic parts that came from B3DP–I realized they are jig bits. Doh.

2. Gluing Traxxas Ends (and a big F’up)

I bought some cheap slow setting epoxy from Harbor Freight. I mixed it with a chop-stick (a favorite tool) and began to apply it to the Traxxas ends. Then, I f’ed up.

I dropped one of the Traxxas ends into the epoxy. I tried cleaning it in alcohol and acetone. But there was still some residue that prevented the ball-joint from moving as freely as I wanted. Sigh. I went ahead and ordered more Traxxas heads, so, if anyone needs an extra because they dropped it in epoxy, just let me know. I’ll have eleven.

One more note, be sure to wipe excess epoxy from the Traxxas end and rod joint. I was worried about an improper seal between the two and left the globulated extra. It leaked into the crevices of the 1515 Beam. Of course, I thought, “I’ll just make sure to turn the yucky part inside when I put the pieces together so it’s not noticeable.” Well, the nuts bolting it to the plastic pieces are also on the inside. In short, it caused a lot of problems. I’d wipe them off before setting them in place on the jigs if I could do it over.

3. Bottom Triforce Assembly

I didn’t like the name “Bottom Assembly” so, I renamed this step: Bottom Triforce assembly. For the most part, smooth sailing. Just make sure you barely screw the nuts on. If they are too tight you can’t get the plastic lips to close around them. Also, they have a top and bottom.

Adding the shafts to the bottom Triforce was a little tricky. First, it should be noted, there is an “up” and a “down” to the Triforce pieces:

The little circular tabs on the bottom Triforce assembly are for printing purposes and may be removed with a sharp knife and steady hand. In the absence of a steady hand, a lot of blood and an emergency-room visit will suffice.

Also, don’t screw any bolts down too tight until you press all pieces together. I had reviewed the section in the Blokmer guide, pages 28-32, but I realized the need for give from all sides was greater than expected. You’ll notice towards the end of my video I was struggling not to look like a complete idiot trying to push all the pieces together.

Of course, I didn’t realize this until I already had bolted the bottom Triforce down and started trying to shove the first shaft in place. I quickly pulled the bottom apart, flipped the odd piece I had so all my plastic pieces had the two-prong guide at the “top.”

Now, I’ve seen half-dozen different ways to press the 1515 into printed plastic. I tried my heat gun, but was really wary I’d deform a piece and I would have to wait 6 weeks to get another from B3DP. I ended up using the following tools:

To press the rods in, I started the rod into the first nut. Then, when it started to get tight, I put a little bike oil (the green bottle) around the edges, flipped over the assembly, and put it in my lap. I pressed the end of the rod I had started against the tile floor and beat on the receiving end (assembly) with a balled fist.

Well, this worked great. A little too great. The rod slipped past being flush. This is where the screwdriver and hammer came in. I simply left the assembly in my lap, but raised the rod off the floor. Then with the tip of the screwdriver against the end of the 1515 rod, I tapped against the screwdriver with the hammer. This allowed me to align the 1515 rod flush with the bottom plastic of the Triforce assembly.

4. Carriage Assembly

Carriages assembly went pretty well. I had to tap the holes for most of the bolts on the carriages, since there was printer-webs still in the holes. But after the holes were clear it was pretty straight forward. I followed the guide from B3DP.

A few notes: If you haven’t sorted your bolts, might be a good idea to do it now. If all your bolts are lumped together digital-calipers are a godsend. You just measure from directly under the head, to the end of the shaft.

There are three nuts that will need to be pressed into the plastic of the carriage assembly. I used a heat gut to soften the plastic of the intended holes, then pressed the nut slightly in place by placing the tip of a flat-head screwdriver over the nut and tapping it with a hammer. This method worked well. One exception, there are three nuts, but two of the bolts are 25mm and one is 16mm. The 16mm bolt is not long enough to catch the threads of the nut unless you tap it deep into its hole. I hope this picture makes it clear:

5. Motors and Endstops

Bottom endstops and motors went smooth.

Only bits of advice on the motors are: Make sure you tap the holes in the plastic to prevent any plastic shards from misaligning your bolt as you try to screw it into the motor hole.

Also, don’t tighten any bolts down until all your bolts are started correctly. I found they often were misthreading, which I attributed to such a harsh angle.

Oh, one more bit, purchase a long 2mm Balled Allen Key for this process. As you may notice at the beginning of my video I tried with a short, balless Allen key to no avail.

6. Carriage Arms and Effector Assembly

A couple notes,

The carriage assembly is pretty straight forward, just make sure you follow the instructions and don’t get in a hurry. But the effector I had a little difficulty putting together. Mainly, the round part of the J-head wouldn’t fit into the hole. I’ve tried to avoid using a heatgun as much as possible, but here I used it to warm the plastic enough and pressed the J-head into place.

7. Top Triforce, PSU, Ramps 1.4, and Attaching Effector

Here I become a little peeved at B3DP. First, there are three parts they do not include in “The Rest” kit, but also don’t mention in the “What’s not included” section. They are the spring, safety pin, and Allen-key for the auto-level.

The auto-level bit is a little tricky to put together. You will need to source three parts: The safety pin, Allen-key, and springs. I ordered an Allen-key off eBay. The safety pin I “borrowed” from my wife’s things. And the springs I pulled from some old pins. After much fiddling I was able to piece something together.

Now, I need to state, in my original blog I was a little unfair to B3DP. I bitched about them sending a button-switch for the auto-probe. The problem was they provided a button switch instead of an button and arm switch.

Arm and Button

Button Switch

This should not have bothered me too much, since the three end-stops worked. But when it came to the auto-level, the Allen-key crook was supposed to catch the metal arm of the above shown switches, guiding it down to the button. Well, I found when the Allen-key came to sit on the button, instead of pressing it down it would slide either to the left or right. And it didn’t seem to matter how much tweaking I did, I couldn’t get it to sit right. In the end, I bought the “appropriate” switch at Radio Shack for $3.

Here is what my auto-level looked like after tweaking. When I tested it unmounted it worked.

But, when I mounted the auto-probe and started using it, I found the arm would catch underneath the safety-pin bolt. Hmm.

Therefore, I feel I owe B3DP half an apology.

I ended up using the switch I was sent, effectively, and I apologize for bitching about the wrong switch. But, to get the switch I was sent to work properly, I had to layer heatshrink, over, and over. This builds the arm up to the point it can’t help but catch the button. And the heatshrink has some natural resistance to it. This necessary modification probably needs to make it into the B3DP guide.

Regarding the power-supply.

I tried buying a cheap computer-power cord from eBay. But after I sliced the end off and found less copper than in telephone wire. I sacrificed one of my old computer power cords. The powercord wasn’t as long as I’d like, but it had enough copper to pull the possible 30A the PSU could source.

To wire the PSU,

  • Green <—> Ground
  • White <—> N(eutral)
  • Black <—> L(ive)

Also, if you are using that fasttech.com PSU, I noticed it came to me with the 240v as default. If you’re in the states make sure you flip the switch on the side.

After wiring my PSU to the Ramps I turned it on and looked for blue-smoke. Nothing. Waahoo!

But I had another problem. The Mega underneath wasn’t getting power. Well, I scratched my head for a bit and then actually read the Ramps manual. Apparently the diode that had been taped to the underbelly of my Ramps is what enabled it to be powered from a 12V PSU. I soldered it in place.

After soldering the diode everything appeared to be working. I continued to wire everything else up like proper.

12V to Arduino Mega Diode placement

Here, I switched gears and put the top Triforce together.

One note I’ll make. Again, the top Triforce has a “bottom” and a “top.” It has to do with the tensioner bolt, it must angle from the top-outside to the bottom-inside. Like this,

After, I got a hankering to actually put the top on and the belts in place. It took a little courage, since B3DP sent my timing belts in one role. I had to make cuts and was worried they had given me just enough belt and if I made a cut that was a little off would have to wait on another belt. But it was in vain, I had enough.

To cut the belts I just strung them up as shown and left about four rubber-teeth past the end of the linker groove. The little extra room can be adjusted when the top Triforce is put on. There are three tension bolts for this purpose.

This is what the belt should look like in place, except the should go below the carriage or it will knock into the end-stops before carriage.

(Sidenote, from here on I’m using a lot of pictures, since the Kossel is a little difficult to video given its physical size)

I then tightened the top Triforce and quickly hooked up the Ramps. I uploaded the Marlin firmware and was able to get the motors to respond to one direction. The problem came when I tried to hook the cooling fan to the Ramps. Two of the three FETs were putting out 0Vs. Waaa-waaah.

Apparently, the power control FETs on the Ramps were bad?

I found out later (Brassfly and Bdk6 actually figured it out) that it was not bad FETs. It was a trace-short somewhere on the first 12V power rail. Oh well. I ordered another Ramps board for $14 and took a break from the build for 18 days while it found its way to me.

8. It’s Alive!

The evening I received the new Ramps board I wired everything up. Sure enough, I powered the thing on and all the blue-fairies stayined in their Silicon homes. I then ran the Blink sketch to check the power FETs on pins 8, 9, 10. They all powered on like expected, spitting out 12Vs.

Next, I uploaded Blokmer’s Marlin sketch. Big mistake.

Blokmer and B3DP both provide a Marlin sketch with “typical” measurements already plugged into the Configuration.cpp. I didn’t know this. I had essentially put diesel into a gasoline engine.

  1. Blokmer’s Marlin Firmware Specific to Blokmer’s Kossel, Pronterface, and Slicer (.zip; for Windows)
  2. B3DP’s Setup Page. It links to Marlin Firmware specific to B3DP Kossel, Pronterface, and KISSlice.

Of course, I pulled a lot of my hair out using Blokmer’s firmware with a B3DP build. In the end, I downloaded B3DP’s Marlin and Blokmer’s zip file. That is, I used the appropriate Marlin with Pronterface and Slicer.

Before I move on though, I’d like to go over wiring.

Here is the B3DP wiring chart:

Of course, my stepper-motors had different color wires, but I guessed and got it right. Really, I figure they would either move up or down, then I could switch them if needed. A word of caution, make sure you wire each stepper to its corresponding end-stop. If not, when you home the end-stops for the first time one or two of the motors will stop, but the other two or one will continue because their end stop hasn’t been triggered, resulting in your belt(s) coming loose. E.g., motor X will hit end-stop Z, but not turn off because the X end-stop hasn’t been switched. And the X end-stop wont switch off because motor Z has stopped because its end-stop has be triggered.

Clear as mud? Just make sure each end-stop is wired to the appropriate motor.

Regarding the thermistor, it is non-polarized. Just plug it in.

Ok. I’m going to consider the “Mechanical” section of this build complete. Now, I’ll begin working on the hard stuff: Calibration.

Metallurgy 101 - AVR UART

This is a continuation of my Robot Metallurgy 101 – AVR Lesson Journal

I started looking through Newbie Hack’s tutorials on AVR trying to work up the energy to tackle First LCD Program. Many don’t know this, but I despise workings with LCDs. I think it is two parts, one, I live in a world with high-resolution screens embedded in everything from coffee-machines to toilets. Trying to settle with an old school LCD doesn’t cut it for me. Furthermore, wiring a non-serial interface LCD is a ever loving pain.

But looking at the rest of the Newbie Hack tutorials I knew I would need some way to display information from the ATtiny1634. I thought about it and compromised: I’d focus on UART next. That way I could display information on my desktop screen.

I began reading about UART on AVR; here are some of the good ones I found,

  1. Newbie Hack’s One Way Communication
  2. Newbie Hack’s Two way Communication
  3. maxEmbedded’s USART

After reading the articles I opened up the ATtiny1634 datasheet and decided I would start by trying to output “ALABTU” to a serial-port into Real Term.

It took me maybe an hour or two to get something working; here is what I learned along the way.

1. AVR UART is Easy.

The following code sets the baud rate on the ATtiny 1634 using the UBBR chart from the datasheet, then, transmits the letter “A.”

UART Code v01

// UART Example on the ATtiny1634 using UART0.
// C. Thomas Brittain
// letsmakerobots.com

#define F_CPU 8000000    // AVR clock frequency in Hz, used by util/delay.h
#include <avr/io.h>
#include <util/delay.h>
// define some macros
#define UBBR 51 // 9600, .02%

// function to initialize UART
void uart_init (void)
	/* Set baud rate */
	UBRR0H = (unsigned char)(UBBR>>8);
	UBRR0L = (unsigned char)UBBR;
	/* Enable receiver and transmitter */
	UCSR0B = (1<<RXEN0)|(1<<TXEN0);
	/* Set frame format: 8data, 1stop bit */
	UCSR0C = (1<<USBS0)|(1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format

void USART_Transmit( unsigned char data )
	/* Wait for empty transmit buffer */
	while ( !( UCSR0A & (1<<UDRE0)) );

	/* Put data into buffer, sends the data */
	UDR0 = data;

int main()


  • Line 10: This creates a macro for the UART Baud Rate Register (UBBR). This number can be calculated using the formula on page 148 of the datasheet. It should be: UBBR = ((CPU_SPEED)/16DESIRED_BAUD)-1. For me, I wanted to set my rate to 9600, therefore: UBBR = (8,000,000/169600)-1; Or: UBBR = (8,000,000/153,600)-1 = **51.083. **It can have a slight margin of error, and since we can’t use a float, I rounded to 51.

  • We then setup of function to initialize the UART connection. Lines 16-17 load our calculated baud rate into a register that will actually set the speed we decided upon. This is done by using four bits from the UBBR0L and UBBR0H registers. If the » is unfamiliar to you, it is the right-shift operator and works much like the left-shift, but yanno, in the other direction.

  • Still in initialization, line 19 enables both the RX0 and the TX0 pins (PA7 and PB0 respectively). I’m not using the TX0 pin yet, but I figured I might as well enable it since I’ll use it later.

  • Line 21 sets the bits to tell the Tiny1634 what sort of communication we want. We want 8 bit, non-parity, 1 stop bit. Enabling USBS0, UCSZ00 and UCSZ01 give us these values..

  • Line 24 is the beginning of the function that’ll transmit our data. Line 27 checks to see if the ATtiny1634 is finished transmitting before giving it more to transmit. The UDRE0 is a bit on the UCSR0A register that is only clear when the transmit buffer is clear. So, the while ( !(UCSR0A & (1«UDRE0)); checks the bit, if it is not clear, it checks it again, and again, until it is. This is a fancy pause, which is dependent on the transmit buffer being clear. Line 30 is where the magic happens. The UDR0 is the transmit register, whatever is placed in the register gets shot out the TX line. Here, we are passing the data that was given to the USART_Transmit function when it is called.

  • Line 39 is passing the hex value for the character “A” to the transmit function.

This was a bit easier than expected.

Here was the output from Code v01.

After a little more tweaking and watching Newbie Hack’s video on sending strings to an LCD, I adapted NH’s code to be used by my UART_Transmit() function I ended with a full string of “ALABTU!” on the serial monitor.

I did this by creating a function called Serial_Print, which is passed a character array (string). StringOfCharacters is a pointer and will be passing each character to the UART transmission. Pointers are simply variables that point to the contents of other variables. They are highly useful when you are looking at the information contained in a variable rather than changing variables’ data. Newbie Hack did an excellent job explaining pointers.

Now, whenever the Serial_Print function is called it starts the loop contained. The loop (line 60, code v02) continues to point out each value contained in the string until it comes across a “0” at which point it exits the loop, and subsequently, the function call.

UART Code v02

The above code provided the following output in the serial monitor. (ALABTU!)

At this point my simple mind was quite pleased with its trite accomplishments and I saw building a library out of my code being pretty easy. But a few problems I had to solve first:

A. Dynamic baud rate initialization.

In Arduino C Serial.begin(9600) initializes the serial connection and sets the baud rate. This is dynamic regardless of running an Arduino Uno at 1mhz or Arduino Mega at 16mhz. I wanted the same functionality; being able to set the baud rate by passing it to the intialization function, uart_init().

I solved this by adding the formula in the uart_init() function (see lines 21 and 38 of code v03). In short, the F_CPU macro contains whatever speed the microcontroller is set, in my case 8mhz, and the user knows what baud rate he wants the code set, so I had all the pieces for to solve the UBBR equation. I made F_CPU part of the calculation and allowed the uart_init() to pass the desired baud rate to the formula. This allowed me to set the baud rate simply by passing the uart_init() function whatever baud rate I wanted. e.g., uart_init(9600);

B. Carriage-return and line-feed at end-of-transmission (EOT).

In Arduino C every time you send serial data, Serial.print(“What’s up mother blinkers!?”), there are two characters added. If you are as new to the world of microcontrollers as me, you may have had headaches finding where these extra characters came from whenever you printed something serially. Arduino C’s Serial.Print() function automatically adds the carriage-return and line-feed characters. In ASCII that’s, “13” and “10” and in hex, “0x0A” and “0x0D” respectively. Arduino C does this, I believe, as a protocol flagging the end of a transmission. This is helpful for the serial receiver to parse the data.

To solve this I simply created two functions CR() and LF() that would transmit the hex code for the line-feed character and the carriage-return. I went this route because not every serial devices excepts them, for instance, the HM-10 that I’m in a love-hate with excepts no characters following the AT commands you send it. I wanted an easy way to send these characters, but not so embedded I had to pull my hair out trying not to send them.

The following code is what I ended with,

UART Code v03

The above code provided the following output. Notice my serial monitor automatically recognized the CR and LF character, which is why “ALABTU!” is one per line, and always left-justified. Booyah!

Ok. I’m not done yet, here is what I’ll be working on in the evening over the next few days,

Receiving data is a little more complex…a little.

2. RX is less easy

I started by reviewing Newbie Hack’s code One Way Communication from Chip-to-Chip, more specifically, his code about the receiving chip. I skipped the part about intilization, since I’d already done that and went straight to his receiving code,

include <avr/io.h>
int main(void)
	DDRB |= (1 << PINB0);

	//Communication UART specifications (Parity, stop bits, data bit length)
	int UBRR_Value = 25; //This is for 2400 baud
	UBRR0H = (unsigned char) (UBRR_Value >> 8);
	UBRR0L = (unsigned char) UBRR_Value;
	UCSR0B = (1 << RXEN0) | (1 << TXEN0);
	UCSR0C = (1 << USBS0) | (3 << UCSZ00);

	unsigned char receiveData;
	while (1)
		while (! (UCSR0A & (1 << RXC0)) );

		receiveData = UDR0;

		if (receiveData == 0b11110000) PORTB ^= (1 << PINB0);

This code receives data and turns on/off a LED if anything was received. It doesn’t concern itself with the values received, just whether something was received.

I was able to replicate this code and get the LED to switch states, but I quickly noticed a problem. The While loop on line 16 is stuck in checking to see if anything has been received, continuously. The problem is apparent; this freezes the microcontroller from doing anything else. Damnit.

Alright, need a different solution; sadly, the solution was something I’d been avoiding for a year, the use of interrupts.

I’m not the sharpest when it comes to electronics, before July 2012 all I’d ever done with electronics was turned’em on and checked Facebook. (By the way, up yours Facebook.) Since my hardware education began I’ve avoided learning about interrupts because they’ve intimidated me.

I won’t go into interrupts here, since I’m just learning about them. But I’ll mention there are two types, internal and external.

Internal interrupts are generated by the internal hardware of a microcontroller and are called software interrupts, because they are genereated by the CPU as a result of how it is coded. External interrupts are voltages delivered to a pin on the microcontroller. Also, interrupts essentially cause the CPU to put a bookmark in the code it was reading, run over and take care of whatever, then when finished, come back to the bookmarked code and continues reading.

That stated, I’d refer you to Newbie Hack’s tutorials on AVR interrupts. It’s excellent. Also, Abcminiuser over at AVR Freaks provided an excellent tutorial on AVR interrupts.

Ok. Back to my problem.

So, I dug in the ATtiny1634 datasheet (pg 168) and found the ATtiny1634 has an interrupt that will fire whenever the RX data buffer is full. To activate this interrupt we have to do two things, enable global interrupts and set the RXCIE0 bit on the UCSR0B register. This seemed pretty straight forward, but I found a AVR Freaks tutorial that helped explain it anyway.

Caveat, I’m learning to re-read which register a bit is found. Occasionally, I’m finding myself frustrated a piece of code is not working, only to realize I’m initializing a bit on an incorrect port. For example, UCSR0D |= (1<<RXCIE0) will compile fine, but it would actually be enabling the bit RXSEI, which is the bit you set to enable an interrupt at the start of a serial data receive. This happens because the names of registers and bits are part of the AVR Core library, but they are simply macros for numbers. In the case of RXCIE0, it actually represents 7, so coding UCSR0D |= (1<<RXCIE0) is simply setting the 7th bit on the wrong register. Not that I did that or something.

Alright, I now have the interrupt setup for when the ATtiny1634 is done receiving a byte.

UART Code v04

Of course, I didn’t add a character to character array conversion, yet. I’m not sure if I want to add this to current function. I personally would rather handle my received characters on a project specific basis. But it should really be as simple as adding character array, then a function to add each character received to the array until it is full. Then, decide what to do when the character array is full.

But Code v04 gave me the following output:

Each time the letter “A” is sent from the serial terminal a RX interrupt event occurs. The interrupt transfers the byte to a variable that is then sent right back out by the Serial_Print() function. Thus, echoing the data you send it.

3. Fully Interrupted

Ok, so, interrupts are a little tricky. Well, one trick. When you are using an interrupt that modifies a variable anywhere else your main that modifies the same variable, you’ll need to disable the interrupt before the modification. It prevents corrupt or incomplete data.

Also, I am using a poor man’s buffer. It’s a simple buffer that overwrites itself and requires an end-of-transmission character, in my case, a “.” from the transmitter to know where to cap the buffer. Still, I believe this will work for a lot of what I’d like to use it.

I do foresee a problem when I enable the second UART on the Tiny1634, since really, only one RX interrupt can run the show. We’ll see. I’m a little tired to detail things here, but here is the code I ended with and I tried to comment the hell out of it.

UART Code v05

One of the other things I did was enable the sleep mode on the Tiny1634. It is setup on line 39 and part of the main loop. It wakes on receiving serial data. I’ve not tested the power consumption, but this is supposed to make the chip drop down to ~5uA.

Nifty right? :)

Ok, code for the second UART.

UART Code v06

I was surprised. The interrupts didn’t seem to trip each other up. Of course, I only did a simple test of sending data from one terminal into the ATtiny1634 and having it come out on the other terminal. This would be: Data–>RX0—>TX1 and Data–>RX1–>TX0

So, there really shouldn’t be any reason the code would trip out, since the RX0 and RX1 interrupts aren’t firing at the same time. I’ll create a library from this code, and as I start using the library in applications I’ll do more debugging and improvement. Also, if anyone is bored and wants to critique the code, I’ve got my big boy pants on, I’d appreciate the criticism.

4. All Together!

It only took me 30 minutes or so to convert the UART code to a library. Here it is, a UART library consisting of 12 functions.

  1. USART_init0()
  2. USART_init1()
  3. USART_Transmit0()
  4. USART_Transmit1()
  5. Serial_Print0()
  6. Serial_Print1()
  7. ClearBuffer0();
  8. ClearBuffer1();
  9. LF0()
  10. LF1()
  11. CR0()
  12. CR1()

Functions numbered 0 relate to serial lines 0, which are pins PA7 (Rx0) and PB0 (Tx0). The functions numbered 1 are serial lines 1, which are pins PB1 (Rx1) and PB2 (Tx1).


  • Initializes a serial lines. Enables TX and RX pins, assigns the baud rate, and enables RX interrupt on receive. It also sets the communication as 8 bit, 1 stop-bit, and non-parity.


  • Will transmit a single character.


  • Prints a string.


  • Empties the receiving buffer.

LF and CR

  • Transmit a line-feed or carriage-return character.

This is the library code: 1634_UART.h

#ifndef	UART_1634
#define UART_1634

#include <avr/interrupt.h>  //Add the interrupt library; int. used for RX.

//Buffers for UART0 and UART1
char ReceivedData0[32];	//Character array for Rx data.
int ReceivedDataIndex0;	//Character array index.
int rxFlag0;			//Boolean flag to show character has be retrieved from RX.

char ReceivedData1[32];	//Character array for Rx data.
int ReceivedDataIndex1;	//Character array index.
int rxFlag1;			//Boolean flag to show character has be retrieved from RX.

//Preprocessing of functions.  This allows us to initialize functions
//without having to put them before the main.
void USART_init0(int BUADRATE);
void USART_Transmit0( unsigned char data);
void Serial_Print0(char *StringOfCharacters);
void clearBuffer0();

void USART_init1(int BUADRATE);
void USART_Transmit1( unsigned char data);
void Serial_Print1(char *StringOfCharacters);
void clearBuffer1();

//EOT characters.
void LF0();
void CR0();

//EOT characters.
void LF1();
void CR1();

// function to initialize UART0
void USART_init0(int Desired_Baudrate)
	//Only set baud rate once.  If baud is changed serial data is corrupted.
	#ifndef UBBR
	//Set the baud rate dynamically, based on current microcontroller
	//speed and the desired baud rate given by the user.
	#define UBBR ((F_CPU)/(Desired_Baudrate*16UL)-1)

	//Set baud rate.
	UBRR1H = (unsigned char)(UBBR>>8);
	UBRR1L = (unsigned char)UBBR;

	//Enables the RX interrupt.
	//NOTE: The RX data buffer must be clear or this will continue
	//to generate interrupts. Pg 157.
	UCSR1B |= (1<<RXCIE1);

	//Enable receiver and transmitter
	UCSR1B |= (1<<RXEN1)|(1<<TXEN1);

	//Set frame format: 8data, 1 stop bit
	UCSR1C |= (1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format

	//Enables global interrupts.

// Function to initialize UART1
void USART_init1(int Desired_Baudrate)
	//Only set baud rate once.  If baud is changed serial data is corrupted.
	#ifndef UBBR
		//Set the baud rate dynamically, based on current microcontroller
		//speed and the desired baud rate given by the user.
		#define UBBR ((F_CPU)/(Desired_Baudrate*16UL)-1)

	//Set baud rate.
	UBRR0H = (unsigned char)(UBBR>>8);
	UBRR0L = (unsigned char)UBBR;

	//Enables the RX interrupt.
	//NOTE: The RX data buffer must be clear or this will continue
	//to generate interrupts. Pg 157.
	UCSR0B |= (1<<RXCIE0);

	//Enable receiver and transmitter
	UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

	//Set frame format: 8data, 1 stop bit
	UCSR0C |= (1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format

	//Enables global interrupts.

void USART_Transmit0( unsigned char data )
	//We have to disable RX interrupts.  If we have
	//an interrupt firing at the same time we are
	//trying to transmit we'll lose some data.
	UCSR0B ^= ((1<<RXEN0)|(1<<RXCIE0));

	//Wait for empty transmit buffer
	while ( !( UCSR0A & (1<<UDRE0)) );

	//Put data into buffer, sends the data
	UDR0 = data;

	//Re-enable RX interrupts.
	UCSR0B ^= ((1<<RXEN0)|(1<<RXCIE0));


void USART_Transmit1( unsigned char data )

	//We have to disable RX interrupts.  If we have
	//an interrupt firing at the same time we are
	//trying to transmit we'll lose some data.
	UCSR1B ^= ((1<<RXEN1)|(1<<RXCIE1));

	//Wait for empty transmit buffer
	while ( !( UCSR1A & (1<<UDRE1)) );

	//Put data into buffer, sends the data
	UDR1 = data;

	//Re-enable RX interrupts.
	UCSR1B ^= ((1<<RXEN1)|(1<<RXCIE1));


//This functions uses a character pointer (the "*" before the StringOfCharacters
//makes this a pointer) to retrieve a letter from a temporary character array (string)
//we made by passing the function "ALABTU!"

void Serial_Print0(char *StringOfCharacters){
	UCSR0B ^= ((1<<RXEN0)|(1<<RXCIE0));

	//Let's do this until we see a zero instead of a letter.
	while(*StringOfCharacters > 0){

		//This function actually sends each character, one by one.
		//After a character is sent, we increment the pointer (++).
	//Re-enable RX interrupts.
	UCSR0B ^= ((1<<RXEN0)|(1<<RXCIE0));

void Serial_Print1(char *StringOfCharacters){
	UCSR1B ^= ((1<<RXEN1)|(1<<RXCIE1));

	//Let's do this until we see a zero instead of a letter.
	while(*StringOfCharacters > 0){

		//This function actually sends each character, one by one.
		//After a character is sent, we increment the pointer (++).
	//Re-enable RX interrupts.
	UCSR1B ^= ((1<<RXEN1)|(1<<RXCIE1));

void clearBuffer0(){
	//Ugh.  A very inefficient way to clear the buffer. :P
	for (unsigned int i = 0; i < 64;)
		//We set the buffer to NULL, not 0.
		ReceivedData0[i] = 0x00;

void clearBuffer1(){
	//Ugh.  A very inefficient way to clear the buffer. :P
	for (unsigned int i = 0; i < 64;)
		//We set the buffer to NULL, not 0.
		ReceivedData1[i] = 0x00;

void LF0(){USART_Transmit0(0x0A);}  //Function for sending line-feed character.
void CR0(){USART_Transmit0(0x0D);}  //Function for sending carriage-return character.

void LF1(){USART_Transmit1(0x0A);}  //Function for sending line-feed character.
void CR1(){USART_Transmit1(0x0D);}  //Function for sending carriage-return character.

	//RX0 interrupt

	//Show we have received a character.
	rxFlag0 = 1;

	//Load the character into the poor man's buffer.
	//The buffer works based on a end-of-transmission character (EOTC)
	//sent a the end of a string.  The buffer stops at 63 instead of 64
	//to always give room for this EOTC.  In our case, "."
	if (ReceivedDataIndex0 < 63){
		//Actually pull the character from the RX register.
		ReceivedData0[ReceivedDataIndex0] = UDR0;
		//Increment RX buffer index.
	else {
		//If the buffer is greater than 63, reset the buffer.

	//RX1 interrupt
	PORTA ^= (1 << PINA6);
	//Show we have received a character.
	rxFlag1 = 1;

	if (ReceivedDataIndex1 < 63){
		//Actually pull the character from the RX register.
		ReceivedData1[ReceivedDataIndex1] = UDR1;
		//Increment RX buffer index.
	else {
		//If the buffer is greater than 63, reset the buffer.


Really, it is all the functions moved over to a header file (.h). One thing I’ll point out, the #ifndef makes sure the header file is not included twice, but I was getting an error with it for awhile, come to find out, you cannot start #define name for #ifndef with a number, e.g.,

  1. #ifndef 1634_UART – This will not work.
  2. #ifndef UART_1634 – Works great!

Eh. Devil’s in the details.

Ok, here is a program that utilizes the library.

Code v07

// UART Example on the ATtiny1634 using UART0.
// C. Thomas Brittain
// letsmakerobots.com
#define F_CPU 8000000UL		//AVR clock frequency in Hz, used by util/delay.h
#include <avr/io.h>			//Holds Pin and Port defines.
#include <util/delay.h>		//Needed for delay.
#include <avr/sleep.h>		//Needed for sleep mode.
#include "1634_UART.h"

// Main
int main()
	//Setup received data LED.
	DDRA |= (1 << PINA6);

	//Light LED on PA6 to show the chip has reboot.
	PORTA ^= (1 << PINA6);
	PORTA ^= (1 << PINA6);

	//Initialize the serial connection and pass it a desired baud rate.

	//Set Sleep

	//Forever loop.
		//ReceivedData = "ASDASDAS";

		if (ReceivedData0[(ReceivedDataIndex0)-1]==0x2E){
			//Function to print the RX buffer
			//Let's signal the end of a string.
			LF1();CR1(); //Ending characters.
			//After we used the data from buffer, clear it.
			//Reset the RX flag.
			rxFlag0 = 0;

		if (ReceivedData1[(ReceivedDataIndex1)-1]==0x2E){
			//Function to print the RX buffer
			//Let's signal the end of a string.
			LF0();CR0(); //Ending characters.
			//After we used the data from buffer, clear it.
			//Reset the RX flag.
			rxFlag1 = 0;


This program is the same as above, but using the library. It simply takes data receiving from one UART and send its out the other.

Alright, that’s enough UART for awhile. I might update this when I run into bugs, which I will, I am a hack. So, use this code at your own risk of frustration.

Stuff I’d no energy to finish.

  1. Implement a circular-buffer (if I get smart enough to do it, that is).
  2. At least making the buffer size user definable. :)

Originally posted on www.letsmakerobots.com

UPDATE: August 10th, 2014

I printed a body and added BLE. I’ll explain tomorrow after I get some rest, but the BLE was to allow me to test directed locomotion. I’ve also done some feature testing (load-sharing, charging circuit, “hunger” ADC), the board is actually a good design. Works well.

The BLE is the HM-11, itty-bitty BLE.

My goal is to test the physical and feature designs with the ATtiny84, and when Mr. Bdk6 releases his toolchain for the LPC1114, switch it as the controlling chip.

This is my version of Yahmez’ Baby Bot, the ATtiny84 Y-Baby (YB84). There are few differences from Yahmez’ version.

  1. This version uses an ATtiny84.
  2. It uses a LIR2032.
  3. It has a charge circuit built in, using the MCP73831. This circuit has load-sharing capability so the baby can “feed” without sleeping.
  4. The YB84 has two LED indicators.
  5. One pin on the YB84 monitors the battery voltage, so it can tell how “hungry” it is.

This version came about because Yahmez’ Baby Bots were so damn cool I had to copy them. Here’s the node where I asked permission and added design notes. Also, I’ve wanted to make a small, cheap, small robot to couple with my Overlord projects in hope to develop an electronic lab-rat.

Here is the BOM:

  1. 1 x LIR2032 – $.44
  2. 1 x 1uF 0402 – $.08
  3. 1 x 4.7uF 0805 – $.10
  4. 1 x B130LAW – $.41
  5. 1 x DMP1045U – $..51
  6. 2 x 3mm IR LED – ?
  7. 1 x IR RX
  8. 3 x colorful LED 0603 – $.33
  9. 2 x MBT2222A (SOT-23) – $.24
  10. 1 x 60k Resistor 0402 – $.10
  11. 1 x 100k Resistor 0402 – $.10
  12. 5 x 330 Resistor 0402 $.50
  13. 1 x MCP73831 – $.61
  14. 1 x ATtiny84 – $.1.30
  15. 1 x YB84 PCB – $1.76
  16. 2 x virbation motor – $1.95

Note, I’ve not included the IR receiver or IR transmitters in the BOM. I’ve not tested the circuit yet, or sourced cheap parts. But I’m shooting to keep them under $10.

YB84 BOM Total: $7.70

YB84 v_05

Really, there wasn’t much to developing this little guy, Yahmez had done all the work. I simply selected an Atmel uC that I felt was cheap enough and provided enough pins to accomplish what I wanted to do with the little guy. The one problem I had was with the load-sharing circuit I tried to copy from Zak Kemble.

When I went to layout the load-circuit my mind got locked on the old thought, “MOSFET diodes go against the current.” This caused me to lay the DMP1045U down backwards, which essentially shorts the battery.

This took me a bit to figure out. I apparently wasn’t the only one that made the mistake, as a comment on Zak’s blog had a fellow asking my questions for me. In the end, I got the circuit sorted out and now the little guy works as intended.

That’s about it for now. I still have lots of testing to do on the little guy.

  1. Motor placement for correct movements.
  2. Leg angling for correct gait.
  3. IR-RX circuit.
  4. IR-TX circuit.

Currently, I have a pogo-pin programming header. But it is imperative to accomplish my goals for this little guy to make him programmable via IR. This should allow me to program a swarm of these little guys without manual interaction. I know the Kilotbot projects modified the Arduino code to do this very thing. My ideal setup is to add a mobile hanging over a swarm of these guys. On this mobile would be: IR-TX, IR-RX, and a camera. The camera would be using Overlord to track these guys and the IR to communicate with them in mass.

As always, thoughts, opinions, and critiques I welcome :)

Metallurgy 101 - AVR PWM

Originally posted on www.letsmakerobots.com

This is a continuation of my Robot Metallurgy 101 Lesson Journal.

After I was able to get my motors moving using the SN754410 I became a little obessessed with understanding AVR PWM architecture. There are several tutorials that helped me a lot:

  1. Newbie Hack’s “Intro to PWM.”
  2. Newbie Hack’s “Control a Servo with PWM.”
  3. humanHardDrive’s “PWM
  4. maxEmbedded’s “AVR Timers – PWM MODE

In the end, I ripped maxEmbedded code and got my PB3 LED working in about 10 minutes. Then, I spent the next three evenings reading trying to figure out what maxEmbedded’s code was doing.

Really, it was the register and bit names that were tripping me up. Each had names like, “TCCROA1” and “OCR0A”, and so forth. Each is an initialism. This was a problem for me, I was soon lost in a jungle of intialisms, which represented abstract concepts, such as other intialisms. I felt as if I were bumbling through a George MacDonald dissertation on an orc language:

NOTE: Dear reader, I apologize if that video confused you more. Again, this is a journal so to help me remember what I learn. And I find adding a story to ridicules abstractions is necessary for me.

Alright, now that I had a little story in my head to handle the intialisms learning PWM on the AVR flowed a little easier.

Here is my reference list:

1. TCCR = Timer/Counter Control Register.

On the ATtiny1634 there are 4 control registers. One is 8-bit and the other is 16-bit. Though, this journal will stick with the Arduino standard, meaning, I’ll use my 16-bit as an 8-bit. Here are the four Timer/Counter Control Register names:

  1. TCCROA (8-bit)
  2. TCCROB (8-bit)
  3. TCCR1A (16-bit)
  4. TCCR1B (16-bit)

TCCROA (8-bit timer) and TCCROB (16-bit timer) control the PWM functions of pins.

  • TCCROA/B control pins PA5 and PA6.
  • TCCR1A/B control pins PC0 and PB3.

2. COM = Compare Output Mode

There are four bits per TCCR register that control the compare output of each pin. This is where the magic happens. If a pin is setup in compare output mode, it will only go high when the counter is equal to or higher than a number you provide. For instance,

  • Is timer greater than 100? Then go high.

This is the essence of PWM. You provide a number, in our case a number between 0-255 since it is an 8-bit counter, and if the timer is equal to or greater than your number, the pin will be HIGH. Then, the timer will continue to count up and will reset to 0 after 255 is reached. Mind you, the comparison is made every tick of the counter, so when it resets to 0 the comparison will be made and the pin will go LOW ago. Voila!

There are four COM bits in each TCCR register, two control the output of one pin.

Found in TCCR0A:

  1. COM0A0 and COM0A0 control pin PC0.
  2. COM0B0 and COM0B0 control pin PA5.

Found in TCCR1A:

  1. COM1A0 and COM1A1 control pin PB3.
  2. COM1B0 and COM1B1 control pin PA6.

Now, switching these bits can create many different types of output. But I stuck with Arduino standard.

3. WGM = Wave Form Generation (for 8-bit)

There are 3 bits that control the type of PWM we end up with. There are all sorts of wave-forms, but the main three are:

  1. Phase Correct
  2. CTC
  3. Fast PWM

(Here is an Arduino article that explains them a bit.)

The one I’ll invoke is Fast PWM,

We select this by setting WGM00 and WGM01 bits.

4. How to set the TCCR registers.

So, setting things up, the code will look something like this,

// Demonstration of PWM on an ATtiny1634.
// C. Thomas Brittain

#define F_CPU 8000000    // AVR clock frequency in Hz, used by util/delay.h
#include <avr/io.h>
#include <util/delay.h>

//Initialize PWM
void pwm_init()
	//This is the first PWM register, TCNT0.  It is 8 bit.  Both PIN PA5 and PA6 are set to clear on compare,
	//then set at bottom; this makes them non-inverting.  The WGM bits are set to for "Fast PWM MODE"
	//and this clears at the top, "0x00FF."
	TCCR0A = 0b10100011; // WORKS FOR OC0A, OC0B
	TCCR0B = 0b00000001; // WORKS FOR OC0A, OC0B

	//This is the second PWM register;TCNT1.  It is 8 bit.  Both PIN PB3 and PC0 are set to clear on compare,
	//then set at bottom; this makes them non-inverting.  The WGM bits are set to for "Fast PWM MODE"
	//and this clears at the top, "0x00FF."
	TCCR1A = 0b10100001;  //WORKS FOR OC1A, OC1B
	TCCR1B = 0b00001001;  //WORKS FOR OC1A, OC1B

	//This sets the PWM pins as outputs.
	DDRB |= (1<<PINB3);
	DDRA |= (1<<PINA5);
	DDRA |= (1<<PINA6);
	DDRC |= (1<<PINC0);


I left the assignment of the TCCR registers in a binary format. This was just easier for me, but you could as easily use bitwise operations, e.g.,

TCCR1A |= (1<<COM1A1)|(1<<WGM01)

You notice we set the COM0A1 or COM1A1 bits, but later I’ll change this so they are not set at initialization. I found if you connect the pins to the timers at the beginning, then they’ll constantly have a nominal voltage on them. This is made clearer if you have an LED on the pin. Therefore, unless you set the COM0A1 and COM1A1 bits low then the LED will never fully turn off.

Also, we have to set the data direction registers for the PWM pins to outputs.

Now, that the initialization is done, let’s look at the code I used to demonstrate PWM on the ATtiny1634.

int main()
	uint8_t brightness;

	// initialize timer0 in PWM mode

	//Setup several duty-cycle counters to show differential PWM channels.
	uint8_t brightness2 = 0;
	uint8_t brightness3 = 0;
	uint8_t brightness4 = 0;

	//Let's only do this 3 times before turning PWM off.
	for (int counterB = 0; counterB < 2; ++counterB){

		//The main duty PWM cycle counter will also be our loop counter. (0-255)
		for (brightness = 255; brightness > 0; --brightness)
				// set the brightness as duty cycle
				brightness2 = brightness2 + 1;
				brightness3 = brightness3 + 2;
				brightness4 = brightness4 + 10;

				OCR0A = brightness;   // PCO0
				OCR0B = brightness2;  // PA5
				OCR1A = brightness3;  // PB3
				OCR1B = brightness4;  // PA6

				//Delay to make changes visible.

			//After 3 loops clear the PWM channels by setting COM0A1 and COM0B1 bits low.
			//If this is not done then there will be a nominal voltage on these pins due to
			//the internal pull-ups setting them as outputs.
			TCCR0A = 0b00000011; // WORKS FOR OC0A, OC0B
			TCCR1A = 0b00000011; // WORKS FOR OC0A, OC0B

You’ll notice this is a modified “Fade” sketch from the Arduino world.

The above code provided this output,

How the magic happens in AVR is around the output comparison registers,

  1. OCR0A – controls PC0
  2. OCR0B – controls PA5
  3. OCR1A – controls PB3
  4. OCR1B – controls PA6

Basically, the OCR registers flip the pin HIGH or LOW (as setup by the TCCR) based upon the number you assign to it. If you assign OCR0A a value you of 144, it’ll be LOW (0v) for 144 clock cycles (TCNT) and HIGH (5v) for 111 clock cycles. This gives us our PWM. Booyah!

  • OCROA = 127;

This sets PC0 to approximately 2.5v. (127/255bit * 5v = ~2.5v)

  • OCR1A = 255;

This sets PB3 to 5v. (255/255bit * 5v = 5v)

Ok, here’s the tricky one,

  • OCR0A = 0;

This should set PC0 to 0v, but that’s not the case. When we set the COM registers (COM0A1, etc.) there are internal pull-up resistors connected to the corsponding pin. This results in a constant nominal voltage unless the COM register is set low again.

This can be done using the XOR operator on the TCCR register,

  • TCCRO ^= (1«COM0A0)

This should set the PC0 pin to 0v.

It’s really that simple…well, unless you want to mess with the type of PWM you are creating. Ugh.

5. ATtiny1634 analogWrite.h

After I figured out how to use PWM on the ATtiny1634, I started thinking how nice it would be to re-create the Arduino library for it.

Being able to write,

  • analogWrite(pin, strength)

had a lot of appeal to me.

I played with it a bit and ended up with the following,

#ifndef analogWrite1634
#define analogWrite1634

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

void analogWrite(int PWM_PinSelect, int duty);

// initialize PWM
void pwm_init()
	//Define PWM pins.
	#define PWM_PC0 1
	#define PWM_PA5 2
	#define PWM_PA6 3
	#define PWM_PB3 4

	//This is the first PWM register, TCNT0.  It is 8 bit.  Both PIN PA5 and PA6 are set to clear on compare,
	//then set at bottom; this makes them non-inverting.  The WGM bits are set to for "Fast PWM MODE"
	//and this clears at the top, "0x00FF."
	TCCR0A = 0b00000011; // WORKS FOR OC0A, OC0B
	TCCR0B = 0b00000001; // WORKS FOR OC0A, OC0B

	//This is the second PWM register;TCNT1.  It is 8 bit.  Both PIN PB3 and PC0 are set to clear on compare,
	//then set at bottom; this makes them non-inverting.  The WGM bits are set to for "Fast PWM MODE"
	//and this clears at the top, "0x00FF."
	TCCR1A = 0b00000001;  //WORKS FOR OC1A, OC1B
	TCCR1B = 0b00001001;  //WORKS FOR OC1A, OC1B

	//This sets the PWM pins as outputs.
	DDRB |= (1<<PINB3);
	DDRA |= (1<<PINA5);
	DDRA |= (1<<PINA6);
	DDRC |= (1<<PINC0);


void analogWrite(int PWM_PinSelect, int duty){

	//Make sure we were passed a number in-range.
	if (duty > 255) duty = 255;
	if (duty < 1) duty = 0;

	//Sets PWM for PC0
	if (PWM_PinSelect == 1){
		if (duty > 0){
			TCCR0A |= (1<<COM0A1);
			OCR0A = duty;
		else {
			TCCR0A ^= (1<<COM0A1);

	//Sets PWM for PA5
	if (PWM_PinSelect == 2){
		if (duty > 0){
			TCCR0A |= (1<<COM0B1);
			OCR0B = duty;
		else {
			TCCR0A ^= (1<<COM0B1);

	//Sets PWM for PA6
	if (PWM_PinSelect == 3){
		if (duty > 0){
			TCCR1A |= (1<<COM1B1);
			OCR1B = duty;
		else {
			TCCR1A ^= (1<<COM1B1);

	//Sets PWM for PB3
	if (PWM_PinSelect == 4){
		if (duty > 0){
			TCCR1A |= (1<<COM1A1);
			OCR1A = duty;
		else {
			TCCR1A	 ^= (1<<COM1A1);



A synopsis of the library,

  • Lines 1-2 and 90 make sure the library is only included once.
  • Lines 13-16 define the ATtiny1634 pins.
  • 18-28 setup the TCCR registers (notice, the pins start out off to prevent nominal voltage).
  • 41-42 makes sure our PWM value is in range.
  • 46-85 control the PWM on each pin, with an else statement to gives us a true zero voltage in the case a PWM value of 0 is passed to the function.

I saved this as 1634analogWrite.h and then wrote a sketch to use

// program to change brightness of an LED
// demonstration of PWM
//void Tiny1634_PWM(int PWM_PinSelect, int duty);

#define F_CPU 8000000    // AVR clock frequency in Hz, used by util/delay.h
#include <avr/io.h>
#include <util/delay.h>
#include "1634analogWrite.h"

int main()
	uint8_t brightness;

	// initialize timer0 in PWM mode
	int brightness2 = 255;
	int brightness3 = 255;
	int brightness4 = 255;
	// run forever
		for (brightness = 255; brightness > -1; --brightness)
			analogWrite(PWM_PC0, brightness);
			analogWrite(PWM_PB3, brightness2);
			analogWrite(PWM_PA5, brightness3);
			analogWrite(PWM_PA6, brightness4);

			brightness2 = brightness2 - 5;
			brightness3 = brightness3 - 10;
			brightness4 = brightness4 - 15;

			if (brightness == 0)
			if(brightness2 < 0) brightness2 =255;
			if(brightness3 < 0) brightness3 =255;
			if(brightness4 < 0) brightness4 =255;


Ok. I’ll revisit this probably with a complete H-Bridge control library.

As always, please feel free to correct my f’ups. :)

Advanced(ish) HM-10

Originally posted on www.letsmakerobots.com

Here are some random notes on working with the HM-10.

  1. Working RX/TX LEDs
  2. How upgrade the HM-10
  3. Pseudo Star-Networking HM-10s

Working RX/TX LEDs

I spent some time trying to find a way to create RX/TX traffic LEDs for the HM-10 breakout. This might be easy for some, but it was a real thinker for me. The HM-10 is TTL, which as it was explained me, means that the line is high while idling and low to represent data. The problem here is the typical LED setup doesn’t work. Sadly, this is the setup I used in two of my fabricated boards.

Well, this stupid mistake has been staring me in the face. Especially since a few guys ordered my board and mentioned politely, “It only flashes when large amounts of data go through.”

After asking around I was told the best way to approach this problem was to use a PNP transistor. The guys at LMR pretty much gave me the solution here. The people here are brilliant. (Please don’t tell them I’m not, I want to hang with the cool-kids for a bit before they find out my mom still dresses me.)

But while LMR was helping me I found Sparkfun’s solution to the problem on one of their Xbee Explorer boards. In essence, the LEDs are wired from in between 3.3v and the TX/RX lines, this allows them to act as sinks whenever the data is coming through. As long as the LED is a green, blue or other with a 3.1v drop, then the voltage being sunk doesn’t interfere with the data.

Of course, this is risky. The CC2540 is a nifty chip, but it isn’t meant to be a high-current uC. I dug through the datasheet to see what the current sink rating of the RX/TX pins (2 & 3) were. Well…it’s not in the datasheet! But then I came across this post.

So, I checked chapter 7.3 of the CC2540 User Guide.

Well, there we go. So, I breadboarded a circuit and found it worked. But I was only brave enough to use a 1k resistor.

Eventually Brassfly helped me work through the math,

“Given that the voltage drop across the forward biased junction of a red LED is about 2 Vdc (we will call that Vf) the total current through the LED/Resistor is equal to Vsupply-Vf/R, or in this case 3.3V-2V/1000=.0013A=1.3mA….If they are bright enough then don’t worry about it. If not, you might then consider using a 470 ohm resistor (2.7mA) or even 330 ohm resistor (3.9mA).”

So, I made up a fresh version of the HM-10 breakout board (v.9.9) with this LED setup. I wired it up. And, it seems to be working.

Again, can’t use yellow or red LEDs on the RX/TX lines, since they do not create a high-enough voltage drop to signal the CC2540 low).

How upgrade the HM-10

(NOTE: You can only upgrade versions 507 or later, according to Jnhuamoa)

1. Visit the HM-10 website and learn all about the HM-10 upgrade process.

2. Download the lastest firmware version file. (Make sure your HM-10 is a CC2540, if it’s CC2541 use that file).

3. Before we proceed, here’s my bitchy disclaimer. Re-read the instructions and b_eware all ye who try to upload firmware and don’t blame me for problems, like the death of your HM-10 :P_

4. Open Realterm (or your preferred serial terminal).

5. Wire your HM-10’s serial connection as described in my earlier post.

6. You are about to cross the point of no return. Open a serial connection to the HM-10 and if you are prepared for the worst, type: “AT+SBLUP” and the module should reply, “SBLUP+OK.” Congratulations, you’ve bricked your HM-10–well, at least until the upgrade process is complete.

7. Now, CLOSE YOUR SERIAL CONNECTION in Realterm. Yes, I forgot to close the connection myself and was pissed because I thought I had bricked my HM-10 when I tried the next step. I’m a hack, hacking with a hacksaw.

8. Unzip the “HMSoft-10-2540-V522.zip” (or the latest version, respectively) into a folder. There should be several files in the folder, open HMSoft.exe

9. Now, click on the ellipsis and select “HMSoft.bin” file. Then, type the number of your com port. You don’t need to include anything but the number (e.g., COM34 becomes 34).

10. Pray (for the HM-10 this works best if to Nyarlathotep).

11. Click “Load Image.” The upload process should start pretty quick and should take approximately a minute and a half to complete. Do not remove power or screw with the wiring until you see the following:

12. Click “Ok” and open Realterm. Bring up a serial connection and type: “AT+VERS?” It should respond, “HMSoft v521.” That’s not a typo, even though we uploaded the V522 version it responds saying it is V521? You got me. But it works ok :)

Pseudo Star-Networking HM-10s

Setup up at least three units.

Unit #1 (“Master”)

  1. AT+ROLE2
  2. AT+IMME1
  3. AT+CONxxxSLAVE#1xxxx

Unit #2 (Slave #A)

  1. AT+ADDR? Write the address down. Mine replied, “OK+ADDR:883314DD8015”
  2. AT+MODE1

Unit #3 (Slave #B)

  1. AT+ADDR? Write the address down.Mine replied, “OK+ADDR:883314DD8016”

  2. AT+MODE1

Oh, one more bit. You need to wire pin 4 on the Arduino to the HM-10 Master’s reset line. Since there really isn’t anyway to reset the slave and the master at the same time. This gets us around the timeout for both, slave and master.

  • RESET<—-1k Resistor—–>D4 on Arduino

Then use the following code, changing your addresses respectively.

// Crap code for HM-10 pseudo-Networking
// By the crappy code Thomas Brittain, aka, Ladvien.

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is completeString inputString = "";         // a string to hold incoming data

float time;
float oldTime;

void setup() {
// initialize serial:
pinMode(4, OUTPUT);
digitalWrite(4, LOW);

void HM10Reset(){
  digitalWrite(4, HIGH);
  digitalWrite(4, LOW);

void loop() {
  // print the string when a newline arrives:
  Serial.print("From first node!  Seconds ago last here: ");
  time = millis();
  oldTime = millis();
  Serial.println("From second node!");

void serialEvent() {
  while (Serial.available()) {
  // get the new byte:
  char inChar = (char)Serial.read();
  // add it to the inputString:
  inputString += inChar;
  stringComplete = true;


Not going to lie. I’m pretty dissapointed with how complicated the firmware makes it to switch between nodes. Although, I’ve only begun to play with firmware versions greater than V303.

I couldn’t do much better than about 2.84 seconds switching between nodes. This simply wont do for me. And, of course, this rate goes up with more nodes. So, a swarm of little robots controlled this way would be unmanagable.

I tried tweaking the timing of everything in the code. The HM-10 wasn’t having it. If I lowered the delay following an AT command it, the command wouldn’t take. This would often cause the nodes to become stuck (waiting for timeout, still connected, etc.) Also, the hardware reset on the HM-10 is said to be 100ms, but I’m finding it unhappy with much less than 250ms.

Anyway, if anyone else wants to carry the banner my suggestion is uping the buad rate and sticking with hardware resets, like in my ATtiny Bitsy Spider board.