This commit is contained in:
Guillaume BONABAU 2025-04-24 08:17:53 +02:00
parent 8849345bc3
commit d7089dff95
5 changed files with 20 additions and 257 deletions

View File

@ -9,29 +9,33 @@ import serial.tools.list_ports
NOTES_PATH = "Player\\notes\\mp3-master\\"
#Long notes
#NOTES_PATH = r"C:\Users\Balthazar\Shared\ECAM\Advance Robotique\Project\Player\notes\high-quality-master\renamed\\"
SERIAL_PORT = "COM5"
SERIAL_PORT = "COM5" #"COM3"
BAUD_RATE = 115200
# New Features
wait_note_finish = False
keyboard_input = False
check_com3 = True
wait_note_finish = False # Set to False to play without waiting for the note to finish
keyboard_input = False # Set to False to disable keyboard note input
check_com3 = True # Set to False to skip COM3 check
pygame.mixer.init()
octave = 4
notes = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"]
def play_note_with_pygame(note):
try:
pygame_sound = pygame.mixer.Sound(f"{NOTES_PATH}{note}.mp3")
pygame_sound.play()
if wait_note_finish:
while pygame.mixer.get_busy():
while pygame.mixer.get_busy(): # Wait until sound is finished
pygame.time.Clock().tick(10)
except Exception as e:
print(f"Error playing {note}: {e}")
# Check if COM port is connected
# Check if COM3 is connected
if check_com3:
ports = list(serial.tools.list_ports.comports())
com3_found = any(port.device == SERIAL_PORT for port in ports)
@ -50,36 +54,26 @@ print("Listening for Arduino input...")
while True:
try:
# Keyboard input fallback
# Keyboard input for playing notes
if keyboard_input:
user_input = input("Enter octave; note (e.g., 4; C) or 'q' to quit: ")
user_input = input("Enter note (C, Db, D, ... B) or 'q' to quit: ")
if user_input == 'q':
break
try:
octave_str, note_part = user_input.split(";")
octave = int(octave_str.strip())
note = note_part.strip().split()[0] # Get only the first note
if note in notes:
play_note_with_pygame(f"{note}{octave}")
except:
print("Invalid input format.")
if user_input in notes:
play_note_with_pygame(f"{user_input}{octave}")
# Arduino input
# Arduino input for playing notes
data = ser.readline().decode('utf-8', errors='ignore').strip()
if data:
print("data: " + data)
try:
octave_str, note_part = data.split(";")
octave = int(octave_str.strip())
note = note_part.strip().split()[0] # Only one note expected
if note in notes:
play_note_with_pygame(f"{note}{octave}")
except Exception as e:
print(f"Invalid format or error parsing data: {e}")
print("data : " + data)
note = data
if note in notes:
play_note_with_pygame(f"{note}{octave}")
except KeyboardInterrupt:
print("Exiting...")
break
except Exception as e:
print(f"Error: {e}")

View File

@ -1,80 +0,0 @@
import serial
import time
import pygame
from pydub import AudioSegment
import serial.tools.list_ports
# Define the paths
#Short notes
NOTES_PATH = "Player\\notes\\mp3-master\\"
#Long notes
#NOTES_PATH = r"C:\Users\Balthazar\Shared\ECAM\Advance Robotique\Project\Player\notes\high-quality-master\renamed\\"
SERIAL_PORT = "COM5" #"COM3"
BAUD_RATE = 115200
# New Features
wait_note_finish = False # Set to False to play without waiting for the note to finish
keyboard_input = False # Set to False to disable keyboard note input
check_com3 = True # Set to False to skip COM3 check
pygame.mixer.init()
octave = 4
notes = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"]
def play_note_with_pygame(note):
try:
pygame_sound = pygame.mixer.Sound(f"{NOTES_PATH}{note}.mp3")
pygame_sound.play()
if wait_note_finish:
while pygame.mixer.get_busy(): # Wait until sound is finished
pygame.time.Clock().tick(10)
except Exception as e:
print(f"Error playing {note}: {e}")
# Check if COM3 is connected
if check_com3:
ports = list(serial.tools.list_ports.comports())
com3_found = any(port.device == SERIAL_PORT for port in ports)
if not com3_found:
print(f"{SERIAL_PORT} not found. Switching to keyboard input mode.")
keyboard_input = True
try:
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
time.sleep(2)
except Exception as e:
print(f"Error opening {SERIAL_PORT}: {e}")
keyboard_input = True
print("Listening for Arduino input...")
while True:
try:
# Keyboard input for playing notes
if keyboard_input:
user_input = input("Enter note (C, Db, D, ... B) or 'q' to quit: ")
if user_input == 'q':
break
if user_input in notes:
play_note_with_pygame(f"{user_input}{octave}")
# Arduino input for playing notes
data = ser.readline().decode('utf-8', errors='ignore').strip()
if data:
print("data : " + data)
note = data
if note in notes:
play_note_with_pygame(f"{note}{octave}")
except KeyboardInterrupt:
print("Exiting...")
break
except Exception as e:
print(f"Error: {e}")
ser.close()

View File

@ -1,62 +0,0 @@
/**
* This file is used for debugging the analog values of the pins on the ESP32.
* It reads the analog values from the specified pins and prints them to the Serial Monitor.
* The values are color-coded based on a defined threshold.
* Values below the threshold are printed in green, while values above the threshold are printed in red.
*/
#include <Arduino.h>
#define THRESHOLD 3000 // Define the threshold value for analog readings
#define COLOR_RED "\033[31m" // ANSI escape code for red color
#define COLOR_GREEN "\033[32m" // ANSI escape code for green color
#define COLOR_RST "\033[0m" // ANSI escape code to reset color
//const int pinList[] = {34, 35, 32, 33, 25, 26, 27, 14, 15, 2, 0, 4}; // Array of the pins you want to use
const int pinList[] = {4, 0, 2, 15, 14, 27, 26, 25, 33, 32, 35, 34}; // Array of the pins you want to use
const int numPins = sizeof(pinList) / sizeof(pinList[0]); // Number of pins in the array
int ArrayStates[numPins]; // Array to store previous states of pins
float ArrayValues[numPins]; // Array to store analog values of pins
template <typename T>
void printArray(T array[], int size);
void setup() {
Serial.begin(115200);
// Initialize each pin in the pinList as an input
for (int i = 0; i < numPins; i++) {
pinMode(pinList[i], INPUT); // Set pins as input
ArrayStates[i] = 0; // Set initial state to 0
}
}
void loop() {
for (int i = 0; i < numPins; i++) {
int analogValue = analogRead(pinList[i]); // Read the analog value of the pin
ArrayStates[i] = (analogValue < THRESHOLD) ? 1 : 0; // Compare with threshold
ArrayValues[i] = analogValue; // Store the analog value
}
printArray(ArrayValues, numPins);
//Serial.print(">States: ");
//printArray(ArrayStates, numPins);
//delay(0); // Add a small delay to avoid flooding the output
}
template <typename T>
void printArray(T array[], int size) {
Serial.print("["); // Start of the message
for (int i = 0; i < size; i++) {
if (array[i] < THRESHOLD) {
Serial.print(COLOR_GREEN); // Change color to red if below threshold
} else {
Serial.print(COLOR_RED); // Change color to green if above threshold
}
Serial.print(array[i]); // Print the value
Serial.print(COLOR_RST); // Reset color to default
if (i < size - 1) {
Serial.print(", "); // Add a comma and space if it's not the last element
}
}
Serial.println("]"); // End of the message
}

View File

@ -1,59 +0,0 @@
/**
* This file is used for debugging the analog values of the pins on the ESP32.
* It reads the analog values from the specified pins and prints them to the Serial Monitor.
* The values are color-coded based on a defined threshold.
* Values below the threshold are printed in green, while values above the threshold are printed in red.
*/
#include <Arduino.h>
#define THRESHOLD 3000 // Define the threshold value for analog readings
//const int pinList[] = {34, 35, 32, 33, 25, 26, 27, 14, 15, 2, 0, 4}; // Array of the pins you want to use
const int pinList[] = {4, 0, 2, 15, 14, 27, 26, 25, 33, 32, 35, 34}; // Array of the pins you want to use
const int numPins = sizeof(pinList) / sizeof(pinList[0]); // Number of pins in the array
const char* noteList[] = {"C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"}; // Array of note names
int ArrayStates[numPins]; // Array to store previous states of pins
int LastSentStates[numPins]; // Array to store last sent states of pins
float ArrayValues[numPins]; // Array to store analog values of pins
bool isArrayEmpty(int array[], int size) {
for (int i = 0; i < size; i++) {
if (array[i] != 0) { // Check if any element is not zero
return false; // Array is not empty
}
}
return true; // Array is empty
}
void setup() {
Serial.begin(115200);
// Initialize each pin in the pinList as an input
for (int i = 0; i < numPins; i++) {
pinMode(pinList[i], INPUT); // Set pins as input
ArrayStates[i] = 0; // Set initial state to 0
}
Serial.println("Starting up..."); // Print a message indicating startup
}
void loop() {
for (int i = 0; i < numPins; i++) {
int analogValue = analogRead(pinList[i]); // Read the analog value of the pin
ArrayStates[i] = (analogValue < THRESHOLD) ? 1 : 0; // Compare with threshold
ArrayValues[i] = analogValue; // Store the analog value
}
if (memcmp(ArrayStates, LastSentStates, sizeof(ArrayStates)) != 0) {
memcpy(LastSentStates, ArrayStates, sizeof(ArrayStates)); // Update last sent states
if (isArrayEmpty(ArrayStates, numPins) == false) {
for (int i = 0; i < numPins; i++) {
if (ArrayStates[i] == 1) {
Serial.print(noteList[i]); // Print the note name if the state is 1
Serial.print(" "); // Add a space between note names
}
}
Serial.println(); // Print a new line after printing all note names
delay(250); //avoid flickering in the sensing
}
}
}

View File

@ -5,19 +5,9 @@
* Values below the threshold are printed in green, while values above the threshold are printed in red.
*/
#include <Arduino.h>
#include <RotaryEncoder.h>
#define THRESHOLD 3000 // Define the threshold value for analog readings
// Pin definitions for the rotary encoder
#define ENCODER_PIN_A 23
#define ENCODER_PIN_B 22
#define ENCODER_BUTTON_PIN 21
// Rotary encoder setup
RotaryEncoder encoder(ENCODER_PIN_A, ENCODER_PIN_B);
//const int pinList[] = {34, 35, 32, 33, 25, 26, 27, 14, 15, 2, 0, 4}; // Array of the pins you want to use
const int pinList[] = {4, 0, 2, 15, 14, 27, 26, 25, 33, 32, 35, 34}; // Array of the pins you want to use
const int numPins = sizeof(pinList) / sizeof(pinList[0]); // Number of pins in the array
@ -27,8 +17,6 @@ int ArrayStates[numPins]; // Array to store previous states of pins
int LastSentStates[numPins]; // Array to store last sent states of pins
float ArrayValues[numPins]; // Array to store analog values of pins
int octave = 4; // Default octave
bool isArrayEmpty(int array[], int size) {
for (int i = 0; i < size; i++) {
if (array[i] != 0) { // Check if any element is not zero
@ -46,26 +34,10 @@ void setup() {
pinMode(pinList[i], INPUT); // Set pins as input
ArrayStates[i] = 0; // Set initial state to 0
}
// Initialize the encoder button pin as input with pull-up resistor
pinMode(ENCODER_BUTTON_PIN, INPUT_PULLUP); // Set encoder button pin as input with pull-up resistor
encoder.setPosition(octave); // Set initial encoder position (scaled for sensitivity)
Serial.println("Starting up..."); // Print a message indicating startup
}
void loop() {
// Update the encoder position
encoder.tick();
// Read the encoder to adjust the octave
int newPosition = encoder.getPosition(); // Divide by 2 to reduce sensitivity
if (newPosition != octave) {
octave = constrain(newPosition, 1, 7); // Limit octave between 1 and 7
encoder.setPosition(octave); // Set the new position of the encoder
//Serial.print("Octave set to: ");
//Serial.println(octave);
}
for (int i = 0; i < numPins; i++) {
int analogValue = analogRead(pinList[i]); // Read the analog value of the pin
ArrayStates[i] = (analogValue < THRESHOLD) ? 1 : 0; // Compare with threshold
@ -74,8 +46,6 @@ void loop() {
if (memcmp(ArrayStates, LastSentStates, sizeof(ArrayStates)) != 0) {
memcpy(LastSentStates, ArrayStates, sizeof(ArrayStates)); // Update last sent states
if (isArrayEmpty(ArrayStates, numPins) == false) {
Serial.print(octave);
Serial.print(";");
for (int i = 0; i < numPins; i++) {
if (ArrayStates[i] == 1) {
Serial.print(noteList[i]); // Print the note name if the state is 1