Basic AVR programming with the Tiny45
June 8th, 2009Tags: attiny45, avr, microcontroller, programming, quickstart, tiny45
I’ve been doing some figuring out of different (cheaper, smaller, more customisable) platforms to work with than the arduino lately, and in the interest of staying small I’m working with the ATTiny45.
I’m programming in C, partially because of initial assembly fright and partially because of the lack of an assembly compiler for the mac. To get my toolchain up, I installed avrdude for loading hex programs onto the chip, avr-gcc for compiling the c code and avr-libc for nice includes. I actually used this crosspack which got everything running pretty much immediately.
To actually program the chip I’m using Lady Ada’s USBTinyISP programmer. It works great and is pretty inexpensive and lets you not need external power supplies for the chips. I’m actually using the ATTiny45v, which operates from 1.8-5.5v, meaning you can run it off coin cells easily.
I suppose there are people out there that know basic C, so I will just include some example code here:
#include<stdio.h> #include<avr/io.h> #include<util/delay.h> main(){ DDRB = 0b11111111; //sets all pins in port b to outputs while(1){ //ie forever _delay_ms(1000); PORTB |=(1<<PB0); //turn pb0 on _delay_ms(1000); PORTB &= ~(1<<PB0); //turn pb0 off } }
Tada, the blinking LED. Now if we want to read a digital input as well:
#include<stdio.h> #include<avr/io.h> #include<util/delay.h> main(){ DDRB = 0b11111101; //all outputs except for pb1 PORTB |=(1<<PB1); //sets the internal pullup resistor of pb1 while(1){ if (PINB & (1<<PB1)){ //if bit is set PORTB &= ~(1<<PB0); //clearbit } if (!(PINB & (1<<PB1))){ //if bit is clear PORTB |=(1<<PB0); //setbit } } }
Here we have PB1 reading any digital input it is hooked up to. If the digital input is high, it keeps PB0 off, and if it is low it turns PB1 on. More on analog sensing and output to follow.