Advertisement
LeonardoLW

Blink AVR delay Arduino UNO

Sep 18th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #define CPU_CLK_HZ 16000000
  2. #define LOOPS_PER_MS (((CPU_CLK_HZ/1000)-(1+1+2+2))/(2+2)) // accounting for the overhead of 6 (1+1+2+2) cycles per ms and the 4 (2+2) cycles per inner loop iteration
  3.  
  4. static inline void ms_spin(unsigned short ms) {
  5.     if (ms) {
  6.         unsigned short dummy;
  7.         __asm__ __volatile__ (
  8.             "ms_spin_outer_loop_%=:                \n"
  9.  
  10.             "    ldi %A[loopcnt], lo8(%[loops])    \n"
  11.             "    ldi %B[loopcnt], hi8(%[loops])    \n"
  12.  
  13.             "ms_spin_inner_loop_%=:                \n"
  14.  
  15.             "    sbiw %A[loopcnt], 1               \n"
  16.             "    brne ms_spin_inner_loop_%=        \n"
  17.  
  18.             "    sbiw %A[ms], 1                    \n"
  19.             "    brne ms_spin_outer_loop_%=        \n"
  20.  
  21.             :  [ms] "+w" (ms),
  22.                [loopcnt] "=&w" (dummy)
  23.             :  [loops] "i" (LOOPS_PER_MS)
  24.             :  // none.
  25.         );
  26.     }
  27. }
  28.  
  29. // the setup function runs once when you press reset or power the board
  30. void setup() {
  31.   // initialize digital pin LED_BUILTIN as an output.
  32.   pinMode(LED_BUILTIN, OUTPUT);
  33. }
  34.  
  35. // the loop function runs over and over again forever
  36. void loop() {
  37.   digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  38.   ms_spin(500); //delay(1000);                       // wait for a second
  39.   digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  40.   ms_spin(500); //delay(1000);                       // wait for a second
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement