Resit Target Localisation Ciaran Kane 18689005

Dependencies:   mbed

Revision:
7:acf82069b794
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Piezo_Buzzer/piezo_bz.cpp	Thu Aug 25 13:50:39 2022 +0000
@@ -0,0 +1,122 @@
+/*
+ * Mbed library program
+ *  Control Piezo Transducer
+ *
+ * Copyright (c) 2018 Kenji Arai / JH1PJL
+ *  http://www.page.sannet.ne.jp/kenjia/index.html
+ *  http://mbed.org/users/kenjiArai/
+ *      Created:    Feburary  28th, 2018
+ *      Revised:    March      3rd, 2018
+ */
+
+#include "mbed.h"
+#include "piezo_bz.h"
+
+PIEZO_BZ::PIEZO_BZ(PinName pin, uint32_t f, uint32_t on_off_time)
+    :  _pin(pin)
+{
+    out = false;
+    _pin.write(0);
+    freq = f;
+    if (freq < 50) {
+        freq = 50;
+    } else if (freq > 10000) {
+        freq = 10000;
+    }
+    flag_run = false;
+    _t0.attach_us(callback(this, &PIEZO_BZ::create_freq_irq), 500000 / freq);
+    t_onoff  = on_off_time;
+    if (t_onoff == 0) {
+        flag_continuous = true;
+        _t1.attach_us(
+            callback(this, &PIEZO_BZ::create_onoff_irq),
+            1000000000 // 1000sec
+        );
+    } else {
+        flag_continuous = false;
+        _t1.attach_us(
+            callback(this, &PIEZO_BZ::create_onoff_irq),
+            t_onoff * 1000
+        );
+    }
+}
+
+PIEZO_BZ::~PIEZO_BZ()
+{
+    _t0.detach();
+    _t1.detach();
+}
+
+void PIEZO_BZ::start()
+{
+    flag_run = true;
+}
+
+void PIEZO_BZ::stop()
+{
+    flag_run = false;
+}
+
+void PIEZO_BZ::change_frequency(uint32_t f)
+{
+    _t0.detach();
+    freq = f;
+    if (freq < 300) {
+        freq = 300;
+    } else if (freq > 10000) {
+        freq = 10000;
+    }
+    _t0.attach_us(callback(this, &PIEZO_BZ::create_freq_irq), 500000 / freq);
+}
+
+void PIEZO_BZ::change_on_off(uint32_t on_off_time)
+{
+    _t1.detach();
+    t_onoff  = on_off_time;
+    if (t_onoff == 0) {
+        flag_continuous = true;
+        _t1.attach_us(
+            callback(this, &PIEZO_BZ::create_onoff_irq),
+            1000000000U // 1000sec
+        );
+    } else {
+        flag_continuous = false;
+        _t1.attach_us(
+            callback(this, &PIEZO_BZ::create_onoff_irq),
+            t_onoff * 1000U
+        );
+    }
+}
+
+void PIEZO_BZ::create_freq_irq(void)
+{
+    // <point A>
+    if (!flag_run) {
+        _pin.write(0);
+        return;
+    }
+    if (!flag_continuous) {
+        if (!flag_onoff) {
+            _pin.write(0);
+            return;
+        }
+    }
+    _pin.write(out);
+    out = !out;
+    // <point B>
+    // Processing time from <point A> to <point B> is 200 to 230ns
+    // measured on Nucleo-F446RE board (System clock 180MHz)
+}
+
+void PIEZO_BZ::create_onoff_irq(void)
+{
+    // <point C>
+    if (flag_continuous) {
+        flag_onoff = true;
+    } else {
+        flag_onoff = !flag_onoff;
+    }
+    // <point D>
+    // Processing time from <point C> to <point D> is 120 to 140ns
+    // measured on Nucleo-F446RE board (System clock 180MHz)
+}