Subversion Repositories HomeAutomation

Rev

Rev 239 | Blame | Last modification | View Log | SVN | RSS feed

  1.  
  2. #ifndef _delay_h_
  3. #define _delay_h_
  4.  
  5. #include <inttypes.h>
  6. #include <avr/io.h>
  7.  
  8. /* For compatibility with bios. If standalone app comment these two lines */
  9. #include <bios.h>
  10. #define F_OSC F_CPU
  11.  
  12. /* delay function for microsec
  13.    4 cpu cycles per loop + 1 cycles(?) overhead
  14.    when a constant is passed. */
  15. static inline void delayloop16(uint16_t count)
  16. {
  17.     asm volatile (  "cp  %A0,__zero_reg__ \n\t"  \
  18.                      "cpc %B0,__zero_reg__ \n\t"  \
  19.                      "breq L_Exit_%=       \n\t"  \
  20.                      "L_LOOP_%=:           \n\t"  \
  21.                      "sbiw %0,1            \n\t"  \
  22.                      "brne L_LOOP_%=       \n\t"  \
  23.                      "L_Exit_%=:           \n\t"  \
  24.                      : "=w" (count)
  25.                      : "0"  (count)
  26.                    );                            
  27. }
  28. // delayloop16(x) eats 4 cycles per x
  29. #define DELAY_US_CONV(us) ((uint16_t)(((((us)*1000L)/(1000000000/F_OSC))-1)/4))
  30. #define delay_us(us)      delayloop16(DELAY_US_CONV(us))
  31.  
  32. /* delay function for millisec
  33.   (6 cycles per x + 20(?) overhead) */
  34. void delayloop32( uint32_t l); // not inline
  35. #define DELAY_MS_CONV(ms) ( (uint32_t) (ms*(F_OSC/6000L)) )
  36. #define delay_ms(ms)  delayloop32(DELAY_MS_CONV(ms))
  37.  
  38. /* mth 9/04:
  39.    Remark uSeconds:
  40.    Main Oscillator Clock given by F_OSC (makefile) in Hz
  41.    one CPU-Cycle takes 1/F_OSC seconds => 1000000/F_OSC uSeconds
  42.    so: 1 uSecond takes F_OSC/1000000 CPU-Cyles. The following code
  43.    is inspired by the avr-libc delay_loop2 function.
  44.    This it not "that precise" since it takes at least 4 cycles
  45.    but should be o.k. with any parameter (even 0).
  46.    Call function with delayloop(DELAYUS(dt [in uSeconds])).
  47. */
  48.  
  49. #endif
  50.