|
| 1 | +/******************************************************************************* |
| 2 | + Dennis van Gils |
| 3 | + 22-08-2018 |
| 4 | + ******************************************************************************/ |
| 5 | + |
| 6 | +#include <Arduino.h> |
| 7 | +#include <math.h> |
| 8 | +#include "DvG_SerialCommand.h" |
| 9 | + |
| 10 | +// Serial : Programming USB port |
| 11 | +// SerialUSB: Native USB port. Baudrate setting gets ignored and is always as |
| 12 | +// fast as possible. |
| 13 | +#define Ser Serial |
| 14 | + |
| 15 | +// Initiate serial command listener |
| 16 | +DvG_SerialCommand sc(Ser); |
| 17 | + |
| 18 | +/*------------------------------------------------------------------------------ |
| 19 | + Setup |
| 20 | +------------------------------------------------------------------------------*/ |
| 21 | + |
| 22 | +void setup() { |
| 23 | + Ser.begin(115200); |
| 24 | +} |
| 25 | + |
| 26 | +/*------------------------------------------------------------------------------ |
| 27 | + Loop |
| 28 | +------------------------------------------------------------------------------*/ |
| 29 | + |
| 30 | +#define WAVE_SINE 1 |
| 31 | +#define WAVE_SQUARE 2 |
| 32 | +#define WAVE_SAWTOOTH 3 |
| 33 | + |
| 34 | +uint8_t wave_type = WAVE_SINE; |
| 35 | +double wave_freq = 0.3; // [Hz] |
| 36 | +double wave = 0.0; |
| 37 | + |
| 38 | +uint32_t curMillis = millis(); |
| 39 | +uint32_t prevMillis = 0; |
| 40 | + |
| 41 | +void loop() { |
| 42 | + char* strCmd; // Incoming serial command string |
| 43 | + |
| 44 | + // Generate wave sample every millisecond |
| 45 | + curMillis = millis(); |
| 46 | + if (curMillis - prevMillis >= 1) { |
| 47 | + |
| 48 | + if (wave_type == WAVE_SINE) { |
| 49 | + wave = sin(2*PI*wave_freq*curMillis/1e3); |
| 50 | + } else if (wave_type == WAVE_SQUARE) { |
| 51 | + wave = (fmod(wave_freq*curMillis/1e3, (double)(1.0)) > 0.5) ? 1 : -1; |
| 52 | + } else if (wave_type == WAVE_SAWTOOTH) { |
| 53 | + wave = 2*fmod(wave_freq*curMillis/1e3, (double)(1.0)) - 1; |
| 54 | + } |
| 55 | + |
| 56 | + prevMillis = curMillis; |
| 57 | + } |
| 58 | + |
| 59 | + // Process serial commands |
| 60 | + if (sc.available()) { |
| 61 | + strCmd = sc.getCmd(); |
| 62 | + |
| 63 | + if (strcmp(strCmd, "id?") == 0) { |
| 64 | + Ser.println("Wave generator"); |
| 65 | + |
| 66 | + } else if(strcmp(strCmd, "sine") == 0) { |
| 67 | + wave_type = WAVE_SINE; |
| 68 | + } else if(strcmp(strCmd, "square") == 0) { |
| 69 | + wave_type = WAVE_SQUARE; |
| 70 | + } else if(strcmp(strCmd, "sawtooth") == 0) { |
| 71 | + wave_type = WAVE_SAWTOOTH; |
| 72 | + |
| 73 | + } else if(strcmp(strCmd, "?") == 0) { |
| 74 | + Ser.print(curMillis); |
| 75 | + Ser.print('\t'); |
| 76 | + Ser.println(wave, 4); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments