A technical blog about programming and technology.

Saturday, April 14, 2007

Programming the Atmel16

So like I said I got my hands wet programming an LCD. The initial code written by the computer engineers to display the characters to the screen was something like:

  UDR = 0xFE; //tell the port we want to send
UDR = 0x01; // clear the LCD
UDR = 'L';
delay_ms(120);
UDR = 'u';
delay_ms(120);
.... etc
This code hurt me, so I was determined to improve it :P. First of all notice the magic numbers 0xFE and 0x01, the comments do help us understand what they mean but they are not very clear. Better to do this :
 #define CLEAR(port) { port = 0xFE; port = 0x01; }
#define SETPOS(port, pos) { port = 0xFE; port = 0x80; port = pos }
...
typedef unsigned char byte;

void print_to_lcd(char* buffer) {
.... check the string size and for NULL
CLEAR(UDR); //clear LCD
SETPOS(UDR, 0) // start at first position of LCD
byte* p = (byte*)buffer; //the serial port wants bytes
while(*p) {
UDR = *p++;
delay_ms(120);
}
}
This was only the beginning improvement. Everyday programming paradigm, write a function for something we want to reuse throughout the program. Now they could just call print_to_lcd("Lunar Raiders") and we get the same effect as before with less code. But I had a funny feeling inside that I was reinventing the wheel, which is not always a bad thing, but I did a little research. They are C functions like printf, fopen ..etc that print characters or bytes to the stdout. Since the hardware has no notion of a console, maybe there was a way to redirect the stdout to mean the UDR(uart port) on the board. After a little research this is what I found:
init() {
... initialize board
// associate uart output function with stdio 
fdevopen(uart_putchar, NULL,0);
}
int uart_putchar(char c) { 
if (c == '\n')
uart_putchar('\r');
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}

Knowing what to search for is sometimes harder that knowing what to do. After finding this code I could use printf("%s %d", "this is cool" ,4 + 5); and like normal and it would print to the LCD.


 


del.icio.us tags: , , ,

2 comments:

Ronald R said...

you eh shame to put this rubbish up? leeme post some STAMP code..lol

David Fowler said...

lemme show you engineers how its done. lol