-
Notifications
You must be signed in to change notification settings - Fork 1
/
M5-Signal-Multimeter.ino
350 lines (301 loc) · 10.3 KB
/
M5-Signal-Multimeter.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/* 4/3/2018 FFT
4/9/2018 Oscillo
4/9/2018 Hz
4/11/2018 no more core 1, moved oscillo, fft to the main loop, back to drawline
4/12/2018 moved everything in the main loop
4/15/2018 split draw and capture, added semaphores (doesn't work)
4/19/2018 back to main loop, split FFT() and drawFFT(), increased sampling to 20kHz for sound,
4/2/2018 waterfall, sprite, using TFT_eSPI, no more m5 but... capture is anemic.... why??
5/1/2018 capture and FFT are performed on core 0 and draw on core 1... and it works!! added auto trigger
*/
// TODO: fix the weird retults, FFT access wrong?
// TODO: fix the oscillo draw which is a bit on the sloooooooowwwwwwwww siiiiiiiiide
#include <dummy.h>
//#include <M5Stack.h>
#include <arduinoFFT.h>
arduinoFFT FFT = arduinoFFT();
#include <TFT_eSPI.h>
TFT_eSPI tft = TFT_eSPI();
TFT_eSprite spectrum = TFT_eSprite(&tft); // Sprite object spectrograph
TFT_eSprite waterfall = TFT_eSprite(&tft); // Sprite object waterfall
TFT_eSprite oscillo = TFT_eSprite(&tft); // Sprite object waterfall
const unsigned int GRAPHWIDTH = 256;
const unsigned int SPECTRUMHEIGHT = 40;
const unsigned int WATERFALLHEIGHT = 100;
const unsigned int OSCILLOHEIGHT = 80;
/////////////////////////////////////////////////////////////////////////
const unsigned int SAMPLES = 512; // Must be a power of 2;
const unsigned long SAMPLING_FREQUENCY = 10000UL; // Hz, must be 40000 or less due to ADC conversion time. Determines maximum frequency that can be analysed by the FFT Fmax=sampleF/2.
const unsigned int SIGNAL_AMPLITUDE = 200; // Depending on your audio source level, you may need to increase this value;
unsigned int sampling_period_ms = 0;
unsigned long long microseconds = 0;
//byte peak[8] = { 0 };
double vSample[SAMPLES] = { 0 };
double buffer[SAMPLES] = { 0 };
double oldOscilloBuffer[SAMPLES] = { 0 };
double vOldSample[SAMPLES] = { 0 };
unsigned long long newTime = 0, oldTime = 0;
/////////////////////////////////////////////////////////////////////////
const unsigned int OSCILLO_Y = 160;
float OSCILLO_YSCALE = 0.015f;
float FFTDisplayScale = 0;
String majorPeakFrequency = "";
String THD = "";
unsigned long majorPeakTime = 0;
String oldFFTDisplayScale = "";
bool getHeatMapColor(float value, uint8_t *red, uint8_t *green, uint8_t *blue)
{
const int NUM_COLORS = 3;
static float color[NUM_COLORS][3] = { { 50,0,100 },{ 255,0,0 } ,{ 255,255,0 } };
int idx1; // |-- Our desired color will be between these two indexes in "color".
int idx2; // |
float fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is.
if (value <= 0) { idx1 = idx2 = 0; } // accounts for an input <=0
else if (value >= 1) { idx1 = idx2 = NUM_COLORS - 1; } // accounts for an input >=0
else
{
value = value * (NUM_COLORS - 1); // Will multiply value by 3.
idx1 = floor(value); // Our desired color will be after this index.
idx2 = idx1 + 1; // ... and before this index (inclusive).
fractBetween = value - float(idx1); // Distance between the two indexes (0-1).
}
*red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0];
*green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1];
*blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2];
}
#include <driver/adc.h>
void Capture()
{
//capturee
for (int i = 0; i < SAMPLES; i++)
{
newTime = micros() - oldTime;
oldTime = newTime;
vSample[i] = analogRead(35); // A conversion takes about 1uS on an ESP32
//vSample[i] = adc1_get_raw(ADC1_CHANNEL_7);
vTaskDelay(sampling_period_ms / portTICK_PERIOD_MS);
}
}
double FFTreal[SAMPLES] = { 0 };
double FFTimaginary[SAMPLES] = { 0 };
double FFTmagnitude[SAMPLES] = { 0 };
void ComputeFFT()
{
//copy to fft buffer
for (int i = 0; i < SAMPLES; i++)
{
FFTreal[i] = vSample[i];
FFTimaginary[i] = 0;
}
//FFT
FFT.Windowing(FFTreal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(FFTreal, FFTimaginary, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(FFTreal, FFTimaginary, SAMPLES);
//copy to draw buffer
for (int i = 0; i < SAMPLES; i++)
{
FFTmagnitude[i] = FFTreal[i];
}
}
void DrawOscillo()
{
//copy ADC samples to buffer
for (int i = 0; i < SAMPLES; i++)
buffer[i] = vSample[i];
// auto trigger
// find middle value
double min=1000, max=-1000, middle=0;
for (int i = 0; i < SAMPLES; i++)
{
if (buffer[i] > max)
max = buffer[i];
if (buffer[i] < min)
min = buffer[i];
}
middle = (min + max) / 2;
// find trigger index
int triggerIndex = 0;
for (int i = 0; i < min(GRAPHWIDTH, SAMPLES); i++)
{
if ((buffer[i - 1]<buffer[i] && buffer[i] > middle))// || (buffer[i - 1] > buffer[i] && buffer[i] < middle))
triggerIndex = i;
}
oscillo.fillSprite(TFT_BLACK);
for (int i = triggerIndex; i < min(GRAPHWIDTH+triggerIndex,SAMPLES); i++)
{
oscillo.drawLine(i - 1- triggerIndex, buffer[i - 1] * OSCILLO_YSCALE, i- triggerIndex, buffer[i] * OSCILLO_YSCALE, TFT_RED);
}
oscillo.pushSprite(0,OSCILLO_Y);
//copy to back buffer (for deleting the curve, not needed when using sprite as frame buffer)
for (int i = 0; i < SAMPLES; i++)
oldOscilloBuffer[i] = buffer[i];
}
double FFTDisplayBuffer[SAMPLES] = { 0 };
void DrawFFT()
{
// copy to display buffer
//copy to fft magnitude
for (int i = 0; i < SAMPLES; i++)
{
FFTDisplayBuffer[i] = FFTmagnitude[i];
}
//display spectral bands
spectrum.fillSprite(TFT_BLACK);
for (int i = 2; i < min(SAMPLES>>1 , GRAPHWIDTH) ; i=i+1)
{
int amplitude = (int)FFTDisplayBuffer[i] * FFTDisplayScale / SIGNAL_AMPLITUDE;
amplitude = min(amplitude, SPECTRUMHEIGHT);
uint8_t r, g, b;
getHeatMapColor((float)amplitude / (float)SPECTRUMHEIGHT, &r, &g, &b);
uint16_t color = tft.color565(r, g, b);
spectrum.drawFastVLine(i, SPECTRUMHEIGHT - amplitude, amplitude, color);
waterfall.drawPixel(i, 0, color);
}
spectrum.pushSprite(0, 0);
waterfall.pushSprite(0, SPECTRUMHEIGHT);
waterfall.scroll(0, 1);
//calculate peak and THD
if (millis() > majorPeakTime)
{
majorPeakTime = millis() + 500;
majorPeakFrequency = String(FFT.MajorPeak(FFTDisplayBuffer, SAMPLES, SAMPLING_FREQUENCY), 1);
//THD
double totalTHD = 0;
double maxPowerForTHD = 0;
for (int i = 2; i < SAMPLES / 2; i++)
{
totalTHD += sq(FFTreal[i]);
if (FFTreal[i] > maxPowerForTHD)
maxPowerForTHD = FFTDisplayBuffer[i];
}
totalTHD -= sq(maxPowerForTHD);
totalTHD = sqrt(totalTHD) / maxPowerForTHD;
totalTHD *= 100;
THD = String(totalTHD, 0);
TextBox(String(majorPeakFrequency + " Hz"), GRAPHWIDTH, 10);
TextBox("THD " + THD + " %", GRAPHWIDTH, 40);
}
}
TFT_eSprite img = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
void TextBox(const String& txt, int x, int y)
{
// Size of sprite
#define IWIDTH 60
#define IHEIGHT 16
// Create a 8 bit sprite 80 pixels wide, 35 high (2800 bytes of RAM needed)
img.setColorDepth(8);
img.createSprite(IWIDTH, IHEIGHT);
// Fill it with black (this will be the transparent colour this time)
img.fillSprite(TFT_BLACK);
// Draw a background for the numbers
img.fillRoundRect(0, 0, IWIDTH, IHEIGHT-1, 6, TFT_DARKGREY);
//img.drawRoundRect(0, 0, IWIDTH, IHEIGHT-1, 6, TFT_WHITE);
// Set the font parameters
img.setTextSize(1); // Font size scaling is x1
img.setTextColor(TFT_WHITE); // White text, no background colour
// Set text coordinate datum to middle right
img.setTextDatum(MR_DATUM);
// Draw the number to 3 decimal places at 70,20 in font 4
img.drawString(txt, IWIDTH,8, 1);
// Push sprite to TFT screen CGRAM at coordinate x,y (top left corner)
// All black pixels will not be drawn hence will show as "transparent"
img.pushSprite(x, y, TFT_BLACK);
// Delete sprite to free up the RAM
img.deleteSprite();
}
//*********************************** sin and square out
void Sinusoide_Task(void *parameter)
{
for (;;)
{
for (int i = 0; i < 360; i++)
{
dacWrite(26, (120 + (sin((i * 3.14) / 180) * (120 - (i / 100)))));
}
}
vTaskDelete(NULL);
}
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255)
{
uint32_t duty = (8191 / valueMax) * min(value, valueMax);
ledcWrite(channel, duty);
}
// Make a PWM generator task on core 0 Signal generator pin 2
void LedC_Task(void *parameter)
{
int phase = 128;
int phaseStep = 5;
ledcSetup(0, 600, 13);
ledcAttachPin(2, 0);
for (;;)
{
ledcAnalogWrite(0, phase);
vTaskDelay(20 / portTICK_PERIOD_MS);
}
vTaskDelete(NULL);
}
//**************************************** compute tasks
void taskCaptureAndFFT(void *pvParameters)
{
for (;;)
{
//uint32_t dt = millis();
Capture();
ComputeFFT();
//TextBox(String(millis() - dt) + " ms", GRAPHWIDTH, 70);
}
}
void TaskDraw(void *pvParameters)
{
for (;;)
{
DrawFFT();
DrawOscillo();
}
}
void TaskDebug(void *pvParameters)
{
for (;;)
{
Serial.println(esp_get_minimum_free_heap_size());
delay(5000);
}
}
void setup()
{
tft.init();
tft.fillScreen(TFT_BLACK);
tft.setRotation(1);
// Create a sprite for the graphs
spectrum.setColorDepth(16);
spectrum.createSprite(GRAPHWIDTH, SPECTRUMHEIGHT);
waterfall.setColorDepth(16);
waterfall.createSprite(GRAPHWIDTH, WATERFALLHEIGHT);
oscillo.setColorDepth(16);
oscillo.createSprite(GRAPHWIDTH, OSCILLOHEIGHT);
Serial.begin(115200);
//speaker shhhhh
dacWrite(25, 0);
//adc1_config_width(ADC_WIDTH_BIT_12); //Range 0-1023
//adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_2_5); //ADC_ATTEN_DB_11 = 0-3,6V
analogReadResolution(12); // Default of 12 is not very linear. Recommended to use 10 or 11 depending on needed resolution.
analogSetAttenuation(ADC_0db); // Default is 11db which is very noisy. Recommended to use 2.5 or 6.
sampling_period_ms = round(1000 * (1.0 / SAMPLING_FREQUENCY));
FFTDisplayScale = 0.3;
//launch tasks parameters: (task function, name, stack size (W), task parameters, priority, task handle, core#)
xTaskCreatePinnedToCore(taskCaptureAndFFT, "AD sampling", 8192, NULL, 1, NULL, 0);
//xTaskCreatePinnedToCore(TaskDraw, "draw", 8192, NULL, 2, NULL, 0);
//xTaskCreatePinnedToCore(TaskDebug, "debug", 8192, NULL, 2, NULL, 0);
//xTaskCreatePinnedToCore(Sinusoide_Task, "sin output on 26", 8192, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(LedC_Task, "square wave on 26", 8192, NULL, 2, NULL, 0);
}
long int oldMillis = 0;
void loop()
{
uint32_t dt = millis();
//Capture(); //10ms
//ComputeFFT(); //14ms @ 512, 3ms @ 128
DrawOscillo(); // 14ms
DrawFFT(); //28ms
TextBox(String(millis() - dt) + " ms", GRAPHWIDTH, 200);
}