//------------------------------------------------------------------
// qfix.h
// 
// This file contains general includes and definitions for the
// family of qfix boards.
//
// Copyright 2004-2006 by KTB mechatronics GmbH
// Author: Stefan Enderle
//------------------------------------------------------------------

#ifndef qfix_h
#define qfix_h


#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>


/* defines for compatibility */
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
#ifndef BV
#define BV _BV
#endif

   

/** Returns the absolute value of a
*/
inline
int abs(int a) 
{
  if (a>=0) return a;
  else return -a;
}



/** Sleeps for sec seconds. (Note: this is tuned for
*   an Atmel ATmega32 running with 8 MHz.)
*/
inline
void sleep(int sec)
{
  for (int s=0; s<sec; s++) {
    for (long int i=0; i<702839; i++) {
      asm volatile("nop"); 
    }
  }
}


/** Sleeps for msec milliseconds. (Note: this is tuned for
*   an Atmel ATmega32 running with 8 MHz.)
*/
inline
void msleep(int msec)
{
  for (int s=0; s<msec; s++) {
    for (long int i=0; i<703; i++) {
      asm volatile("nop"); 
    }
  }
}




/** Translates the given number into a string which ends
*   with 0.
*/
inline
void num2str(int num, char* str)
{
  bool showZero = false;
  int i=0;
  int n=abs(num);

  if (num<0) str[i++]='-'; 
 
  if (n>=10000 || showZero) { str[i++]=(n/10000)+'0';  n=n % 10000; showZero=true; }
  if (n>=1000  || showZero) { str[i++]=(n/1000) +'0';  n=n % 1000;  showZero=true; }
  if (n>=100   || showZero) { str[i++]=(n/100)  +'0';  n=n % 100;   showZero=true; }
  if (n>=10    || showZero) { str[i++]=(n/10)   +'0';  n=n % 10;    showZero=true; }
  str[i++]=n +'0';     // last digit
  str[i++]=0;          // ending 0
}


#endif

