AVR calculator example program

From RoboWiki
Revision as of 19:47, 1 December 2006 by Palo (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This program retrieves (waits for) two numbers from the terminal connected to UART1, and sends back the result. It uses the uart1SendByte() and uart1GetByte() functions from uart2.c that is part of AVRlib. It works with Cerebot and BlueSmirf modules, see Cerebot & LEGO Mindstorms.

The whole project can be downloaded here: avr_calc.zip.

A follow-up version that is utilizing getchar implementation with line editor from stdiodemo WinAVR example program has more convenient input editing (BACKSPACE, DEL, and some more features work). This new version is available here: avr_calc_ed.zip.

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

// this is included from AVRlib (we need to link with uart2.c and buffer.c)
#include <uart2.h>

static int uart1_putchar(char c, FILE *stream);
static int uart1_getchar(FILE *stream);
static FILE uart_stdinout = FDEV_SETUP_STREAM(uart1_putchar, uart1_getchar, _FDEV_SETUP_RW);

//outputs one character to UART1
static int uart1_putchar(char c, FILE *stream)
{
  //we live in Windows world now 
  if (c == '\n') uart1_putchar('\r', stream);
  uart1SendByte(c);
  return 0;
}

//retrieves one character (or -1) from UART1
static int uart1_getchar(FILE *stream)
{
  char c;
  while ((c = uart1GetByte()) == (char)-1);
  uart1SendByte(c);
  return c;
}

//this function sleeps s seconds (if F_CPU is set to frequency of processor)
void sleep(uint8_t s)
{
  uint8_t i;
  while (s--) for (i = 0; i < 100; i++) _delay_ms(10);
} 

int main(void)
{
  int a, b, c;
  char ch;
 
  //set port E as output so that we can operate with LEDs
  DDRE = 0xFF;  
  
  //first LED shows that program runs
  PORTE = PINE | 16;
  
  //initialize UART1 as 2400/odd parity (that's how our BlueSmirf is configured)
  uart1Init();
  uartSetBaudRate(1, 2400);
  UCSR1C |= 48; 

  //setup character output function for stdout
  stdout = stdin = &uart_stdinout;  

  //while ((ch = fgetc(stdin)) != (char)-1) putc(ch, stdout);
  
  //wait 3 sec before printing
  sleep(3);
  
  //send string to UART1
  printf("AVR calculator.\r\n");
  printf("a=");
  scanf("%d", &a);
  printf("\r\nb=");
  scanf("%d", &b);
  c=a+b;
  printf("\r\na+b=%d (0x%x)\r\n", c, c);
    
  //turn off first LED to show that program terminates
  PORTE = PINE & ~16;
  
  return 0;
}