0

Estoy generando datos aleatorios en un Arduino que permanece conectado a mi ordenador y me gustaría transferir estos datos a una base de datos local en mi ordenador o a un puerto.

He intentado adaptar el código de este post pero que utilisa el port /dev/ttyACM0 y cuando utiliso el script obtengo:

serial.serialutil.SerialException: could not open port '/dev/ttyACM0':
FileNotFoundError(2, 'The system cannot find the path specified.', None, 3)

Cambio por el com que utilisa el Arduino pero me crea problemas:

Arduino: 1.8.19 (Windows 10), Board: "Arduino Uno"

Sketch uses 4494 bytes (13%) of program storage space. Maximum is 32256 bytes.

Global variables use 230 bytes (11%) of dynamic memory, leaving 1818 bytes for local variables. Maximum is 2048 bytes.

Error opening serial port 'COM7'. (Port busy)

Error opening serial port 'COM7'. (Port busy)



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Basta de bla, bla, bla. Aqui es los mios codigos.

Lado Arduino, qu utilisa Port COM 7, para generar datos:

void setup() {
  Serial.begin(115200);
  randomSeed(analogRead(0));
}


void loop() {
  SendSensorData();
}


//function to send sensor data 
void SendSensorData() {
  String sensorData1,sensorData2,sensorData3, postData;
  sensorData1=random(25, 200);
  sensorData2=random(25, 200);
  sensorData3=random(25, 200);

  //Post Data
  postData = "sensor1=" +  sensorData1 + "&sensor2=" + sensorData2+ "&sensor3=" + sensorData3;
  Serial.println(postData);
  
  delay(1000);  
}

Y, Lado PC main.py, para recibir los datos del Arduino:

import serial
import time

startMarker = '<'
endMarker = '>'
dataStarted = False
dataBuf = ""
messageComplete = False


# ========================
# ========================
# the functions

def setupSerial(baudRate, serialPortName):
    global serialPort

    serialPort = serial.Serial(port=serialPortName, baudrate=baudRate, timeout=0, rtscts=True)

    print("Serial port " + serialPortName + " opened  Baudrate " + str(baudRate))

    waitForArduino()


# ========================

def sendToArduino(stringToSend):
    # this adds the start- and end-markers before sending
    global startMarker, endMarker, serialPort

    stringWithMarkers = (startMarker)
    stringWithMarkers += stringToSend
    stringWithMarkers += (endMarker)

    serialPort.write(stringWithMarkers.encode('utf-8'))  # encode needed for Python3


# ==================

def recvLikeArduino():
    global startMarker, endMarker, serialPort, dataStarted, dataBuf, messageComplete

    if serialPort.inWaiting() > 0 and messageComplete == False:
        x = serialPort.read().decode("utf-8")  # decode needed for Python3

        if dataStarted == True:
            if x != endMarker:
                dataBuf = dataBuf + x
            else:
                dataStarted = False
                messageComplete = True
        elif x == startMarker:
            dataBuf = ''
            dataStarted = True

    if (messageComplete == True):
        messageComplete = False
        return dataBuf
    else:
        return "XXX"

    # ==================


def waitForArduino():
    # wait until the Arduino sends 'Arduino is ready' - allows time for Arduino reset
    # it also ensures that any bytes left over from a previous message are discarded

    print("Waiting for Arduino to reset")

    msg = ""
    while msg.find("Arduino is ready") == -1:
        msg = recvLikeArduino()
        if not (msg == 'XXX'):
            print(msg)


# ====================
# ====================
# the program


if __name__ == "__main__":
    setupSerial(115200, "/dev/ttyACM0")
    count = 0
    prevTime = time.time()
    while True:
        # check for a reply
        arduinoReply = recvLikeArduino()
        if not (arduinoReply == 'XXX'):
            print("Time %s  Reply %s" % (time.time(), arduinoReply))

            # send a message at intervals
        if time.time() - prevTime > 1.0:
            sendToArduino("this is a test " + str(count))
            prevTime = time.time()
            count += 1
2
  • Sólo una aplicación puede tener el control del puerto serial en el PC. Parece que tienes abierto el Arduino IDE y la app Python al mismo tiempo. Prueba la app sin el IDE abierto.
    – Candid Moe
    Commented el 13 may. 2022 a las 11:34
  • El protocolo del lado Arduino es incompatible con el protocolo del lado Python. ¿Alguna razón?
    – Candid Moe
    Commented el 13 may. 2022 a las 11:48

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.