[Python] Python cannot send text to arduino

Discussão em 'Python' iniciado por Stack, Junho 29, 2025.

  1. Stack

    Stack Membro Participativo

    Im trying to send the string variable from python onto arduino and print it on an lcd but it doesnt print on the lcd

    Arduino Code to get the text from python and print it on an lcd

    `Sometimes i get a "Çalışmanız programın 5798 bayt (17 %) saklama alanını kullandı. Maksimum 32256 bayt. Global değişkenler belleğin 413 byte kadarını (20%) kullanıyor. Yerel değişkenler için 1635 byte yer kalıyor. En fazla 2048 byte kullanılabilir. avrdude: ser_open(): can't open device "\.\COM3": Eri�im engellendi.

    Problem uploading to board. See https://support.arduino.cc/hc/en-us/sections/360003198300 for suggestions. " error message`

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x20, 16, 2);
    String buffer = "";

    void setup() {
    Serial.begin(9600);
    lcd.begin(16, 2);
    lcd.backlight(); // Turn on LCD backlight
    }

    void loop() {
    while (Serial.available()) {
    char c = Serial.read();
    if (c == '\n') {
    lcd.clear();
    lcd.setCursor(0, 0);

    // If text is longer than 16 characters, split across lines
    lcd.print(buffer.substring(0, 16));
    if (buffer.length() > 16) {
    lcd.setCursor(0, 1);
    lcd.print(buffer.substring(16, 32));
    }

    buffer = ""; // Reset buffer after displaying
    } else {
    buffer += c;
    }
    }
    }


    Python Code to record audio and send it to assemblyai, get it as text, print it and send it to the arduino

    import pyaudio
    import wave
    import requests
    import json
    import time
    import uuid # For generating unique filenames
    import os
    import serial

    ser = serial.Serial('COM3', 9600, timeout=1) # Adjust COM port as needed

    # AssemblyAI API config
    ASSEMBLYAI_API_KEY = 'f23aea7876d845bba0c9a3f282e8dfef' # <-- Put your AssemblyAI API key here
    UPLOAD_ENDPOINT = 'https://api.assemblyai.com/v2/upload'
    TRANSCRIPT_ENDPOINT = 'https://api.assemblyai.com/v2/transcript'

    headers_auth = {
    'authorization': ASSEMBLYAI_API_KEY,
    'content-type': 'application/json'
    }

    # Function to generate a random filename
    def generate_random_filename(extension="wav"):
    random_name = str(uuid.uuid4()) # Use UUID for uniqueness
    global nameoffile
    nameoffile = f"{random_name}.{extension}"
    return nameoffile

    # Function to record audio from the microphone
    def record_audio(filename, duration=5):
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    CHUNK = 1024
    RECORD_SECONDS = duration
    WAVE_OUTPUT_FILENAME = filename

    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

    print("Recording...")
    frames = []

    for _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

    print("Recording finished.")
    stream.stop_stream()
    stream.close()
    p.terminate()

    with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))

    # Function to upload audio file to AssemblyAI
    def upload_audio(filename):
    with open(filename, 'rb') as f:
    print("Uploading audio...")
    response = requests.post(UPLOAD_ENDPOINT, headers={'authorization': ASSEMBLYAI_API_KEY}, data=f)
    if response.status_code == 200:
    upload_url = response.json()['upload_url']
    print("Upload successful.")
    return upload_url
    else:
    print(f"Upload failed: {response.status_code} {response.text}")
    return None

    # Function to request transcription from AssemblyAI
    def request_transcription(upload_url):
    json_data = {
    'audio_url': upload_url
    }
    response = requests.post(TRANSCRIPT_ENDPOINT, json=json_data, headers=headers_auth)
    if response.status_code == 200:
    transcript_id = response.json()['id']
    print(f"Transcription requested. ID: {transcript_id}")
    return transcript_id
    else:
    print(f"Transcription request failed: {response.status_code} {response.text}")
    return None

    # Function to poll transcription result
    def poll_transcription(transcript_id, timeout=60, poll_interval=3):
    polling_endpoint = f"{TRANSCRIPT_ENDPOINT}/{transcript_id}"
    print("Polling for transcription result...")
    start_time = time.time()
    while True:
    response = requests.get(polling_endpoint, headers=headers_auth)
    if response.status_code != 200:
    print(f"Polling error: {response.status_code} {response.text}")
    return None

    result = response.json()
    status = result['status']
    if status == 'completed':
    print("Transcription completed.")
    return result.get('text', '')
    elif status == 'error':
    print(f"Transcription error: {result.get('error', 'Unknown error')}")
    return None
    else:
    # still processing
    if time.time() - start_time > timeout:
    print("Transcription polling timed out.")
    return None
    time.sleep(poll_interval)

    # Function to print the transcript
    def print_transcript(transcript):
    if transcript:
    print(transcript)
    else:
    print("No transcription available.")
    os.remove(nameoffile) # Clean up the audio file after transcription

    def main():
    audio_filename = generate_random_filename("wav")
    record_audio(audio_filename, duration=5)

    upload_url = upload_audio(audio_filename)
    if not upload_url:
    return

    transcript_id = request_transcription(upload_url)
    if not transcript_id:
    return

    transcript = poll_transcription(transcript_id)
    print_transcript(transcript)
    ser.write((transcript + '\n').encode('utf-8'))
    ser.flush()
    time.sleep(1) # Give some time for the Arduino to process the data

    if __name__ == "__main__":
    while True:
    main()


    it is not sending it at all it is not about the lcd because i tried Serial.println instead of lcd.print and it still didnt work

    Im using windows and ive checked the com3 to be true and i never get an error message from python it just doesnt send the string

    Continue reading...

Compartilhe esta Página