3
votes

I try to send an integer from python script to arduino, analize it on board and send an integer to python script. I can reciev data from arduino, but I can't send data to arduino because it reboots. Also, it works with Arduino IDE

The idea is that i send through python magicnumber = 387, than arduno compare it with its owm MN = 387 and than send MN to python, but also, when i start sending data from python it rebooting and nothing work. if it can be please answer mostly with code, 'cause i'm not very goodin English. Thanks

int magicNumber;//глобальные переменные
bool connection = false;
void setup()
{
    pinMode(infoLed, OUTPUT);
    Serial.begin(baudrate);
    while (!Serial) {
        fastBlink();
    }
    slowBlink();

    EEPROM.get(magicNumberAddr, magicNumber);
    normalBlink();
    waitForMN();
}

void loop()
{
    if (!connection) {
        waitForMN();
    }

    slowBlink();

}

void waitForMN() {//двустороннее квинтирование
    String data = "";
    byte sizeofbuf = 0;
    while (Serial.available() <= 0) {
        fastBlink();
    }
    while (!connection) {
        if (Serial.available()) {
            sizeofbuf += 1;
            char s = Serial.read();
            data = String(data + s);
            Serial.println(data.toInt());

            if (sizeofbuf == 3) {
                if (data.toInt() == magicNumber) {
                    Serial.println(magicNumber);
                    char k = Serial.read();
                    connection = true;
                    break;
                } else {
                    Serial.read();
                    waitForMN();
                }
            }
        }
    }
}

python:

import serial
import time
ser = serial.Serial("/dev/ttyUSB1",9600,timeout=10)

ser.flush()
ser.write(str("387").encode())
time.sleep(1)
ser.write(str("387").encode())

print(ser.readline())
1
Possible duplicate of Disable DTR in pyserial from codeobchardon

1 Answers

0
votes

It's actually hard to answer your question because you posted an incomplete code and also I have no any info about whatever you are getting an error from python script.

Arduino reboots after opening a serial port and it's a bootloader standard behavior. You can read more about it on the arduino web page. But actually that means, that your sketch will start to work after about ~3 seconds after connecting to serial port. Just put time.sleep(3) in your python code right after the serial connection initialization and your script must work as intended.

P.S. Consider using Serial.parseInt() instead of that bulky construction in waitForMN() function of Arduino sketch.