#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <math.h>
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
const int sensorPin = A0; // Analog input pin for MyoWare Muscle Sensor
const int numReadings = 100; // Number of readings to take for statistics
const int screenW = 320;
const int screenH = 240;
const int margin = 10;
const int graphH = screenH - 2 * margin;
const int graphW = screenW - 2 * margin;
const int graphX = margin;
const int graphY = margin;
void setup() {
Serial.begin(9600);
tft.begin();
tft.setRotation(3);
tft.fillScreen(ILI9341_BLACK);
tft.drawRect(graphX, graphY, graphW, graphH, ILI9341_WHITE);
}
void loop() {
int readings[numReadings]; // Array to store readings
int index = 0; // Index for the current reading
int total = 0; // Total of all readings
// Read multiple values for statistics and graph
for (int i = 0; i < numReadings; i++) {
readings[i] = analogRead(sensorPin);
total += readings[i];
delay(10); // Delay between readings
}
// Calculate statistics
int min_emg = readings[0];
int max_emg = readings[0];
float sum_squared = 0.0;
for (int i = 0; i < numReadings; i++) {
if (readings[i] < min_emg) {
min_emg = readings[i];
}
if (readings[i] > max_emg) {
max_emg = readings[i];
}
sum_squared += pow(readings[i], 2);
}
float average_emg = total / numReadings;
float rms_emg = sqrt(sum_squared / numReadings);
int median_emg = readings[numReadings / 2];
float compound_fraction = (rms_emg / average_emg) * 100.0;
// Display statistics on the screen
tft.fillRect(0, 0, screenW, screenH, ILI9341_BLACK);
tft.setCursor(10, 10);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.println("EMG Statistics:");
tft.println();
tft.setTextSize(1);
tft.print("Minimum EMG: ");
tft.println(min_emg);
tft.print("Maximum EMG: ");
tft.println(max_emg);
tft.print("Average EMG: ");
tft.println(average_emg);
tft.print("RMS EMG: ");
tft.println(rms_emg);
tft.print("Median EMG: ");
tft.println(median_emg);
tft.print("Compound Fraction: ");
tft.print(compound_fraction);
tft.println("%");
// Display EMG graph
for (int i = 0; i < numReadings - 1; i++) {
int x0 = map(i, 0, numReadings - 1, graphX, graphX + graphW);
int x1 = map(i + 1, 0, numReadings - 1, graphX, graphX + graphW);
int y0 = map(readings[i], 0, 1023, graphY + graphH, graphY);
int y1 = map(readings[i + 1], 0, 1023, graphY + graphH, graphY);
tft.drawLine(x0, y0, x1, y1, ILI9341_GREEN);
}
delay(1000); // Delay before taking the next set of readings
}