פיתוח מערכות תקשורות : דוגמא PYTHON to esp32 udp 2
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 |
#include <WiFi.h> #include <WiFiUdp.h> const char* ssid = "56654v"; const char* password = "m6545"; const unsigned int localPort = 6020; // Local port to listen on WiFiUDP udp; const int speakerPin = 25; // Digital pin connected to the speaker void setup() { Serial.begin(115200); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Start UDP udp.begin(localPort); // Initialize speaker pin pinMode(speakerPin, OUTPUT); } void loop() { // Receive voice data over UDP and play it through the speaker receiveAndPlayVoiceData(); } void receiveAndPlayVoiceData() { uint8_t voiceData[256]; // Check if there's data available to read int packetSize = udp.parsePacket(); if (packetSize) { // Read voice data from UDP packet udp.read(voiceData, packetSize); // Play voice data through the speaker for (int i = 0; i < packetSize; i++) { dacWrite(speakerPin, voiceData[i]); // Write voice data to DAC pin } } } |
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 |
import socket import wave # Define the delay in microseconds (e.g., 1000 microseconds = 1 millisecond) microseconds_delay = 0.00001 # Replace with your desired delay in microseconds # Convert microseconds to seconds (1 second = 1,000,000 microseconds) seconds_delay = microseconds_delay / 1_000_000 # Server IP address and port server_ip = "10.0.0.22" # Replace with the target IP address server_port = 6020 # Replace with the target UDP port # Create a UDP socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Specify the path to your WAV file wav_file_path = 'D:/projetcs8/Small-talk/sound/1c.wav' # Chunk size for sending data over UDP chunk_size = 256 print("send...") # Define a function to send WAV file chunks over UDP def send_wav_chunks(wav_path): try: # Open the WAV file with wave.open(wav_path, 'rb') as wav_file: # Get the audio parameters params = wav_file.getparams() # Read audio data audio_data = wav_file.readframes(params.nframes) # Send the audio data over UDP in chunks for i in range(0, len(audio_data), chunk_size): chunk = audio_data[i:i+chunk_size] client_socket.sendto(chunk, (server_ip, server_port)) # Introduce delay for cox1 in range(199999): c=cox1 #print(f"Sent {len(chunk)} bytes") except Exception as e: print(f"An error occurred: {str(e)}") # Call the function to send WAV file chunks over UDP send_wav_chunks(wav_file_path) # Close the UDP socket client_socket.close() print("end ") |