From 909e98b1afa02380c11195c49db83351a9069dd5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= <jbrazio@gmail.com>
Date: Fri, 29 Jul 2016 00:03:25 +0100
Subject: [PATCH] A little cleanup at speaker.h

---
 Marlin/buzzer.h  |  1 -
 Marlin/speaker.h | 28 +++++++++++++---------------
 2 files changed, 13 insertions(+), 16 deletions(-)

diff --git a/Marlin/buzzer.h b/Marlin/buzzer.h
index e967284eaa..766b7aa7cf 100644
--- a/Marlin/buzzer.h
+++ b/Marlin/buzzer.h
@@ -104,7 +104,6 @@ class Buzzer {
      */
     void tone(uint16_t const &duration, uint16_t const &frequency = 0) {
       while (buffer.isFull()) {
-        delay(5);
         this->tick();
         thermalManager.manage_heater();
       }
diff --git a/Marlin/speaker.h b/Marlin/speaker.h
index 93aa6f7361..0bc2a9a9f6 100644
--- a/Marlin/speaker.h
+++ b/Marlin/speaker.h
@@ -32,7 +32,7 @@ class Speaker: public Buzzer {
     struct state_t {
       tone_t   tone;
       uint16_t period;
-      uint16_t cycles;
+      uint16_t counter;
     } state;
 
   protected:
@@ -43,7 +43,7 @@ class Speaker: public Buzzer {
     void reset() {
       super::reset();
       this->state.period = 0;
-      this->state.cycles = 0;
+      this->state.counter = 0;
     }
 
   public:
@@ -60,7 +60,7 @@ class Speaker: public Buzzer {
      * playing the tones in the queue.
      */
     virtual void tick() {
-      if (!this->state.cycles) {
+      if (!this->state.counter) {
         if (this->buffer.isEmpty()) return;
 
         this->reset();
@@ -69,20 +69,18 @@ class Speaker: public Buzzer {
         // Period is uint16, min frequency will be ~16Hz
         this->state.period = 1000000UL / this->state.tone.frequency;
 
-        this->state.cycles =
-          (this->state.tone.duration * 1000L) / this->state.period;
+        this->state.counter =
+          (this->state.tone.counter * 1000L) / this->state.period;
 
-        this->state.period >>= 1;
-        this->state.cycles <<= 1;
+        this->state.period   >>= 1;
+        this->state.counter <<= 1;
+      } else {
+        const  uint32_t  now = micros();
+        static uint32_t next = now + this->state.period;
 
-      }
-      else {
-        uint32_t const us = micros();
-        static uint32_t next = us + this->state.period;
-
-        if (us >= next) {
-          --this->state.cycles;
-          next = us + this->state.period;
+        if (now >= next) {
+          --this->state.counter;
+          next = now + this->state.period;
           if (this->state.tone.frequency > 0) this->invert();
         }
       }