pythonarduino

Arduino serial port communication with Python


I use an Arduino UNO r3 via USB port attached to a PC running WIN 10 and Python. The Arduino converts the status of an attached analog switch (status open or closed) to binary code to the Python script. Everything works fine, however after some time (hours or even days) the python script gets no data anymore from the Arduino. The Arduino sketch looks like this:

#include <avr/wdt.h>  // Include watchdog library

#define ButtonPIN 8
#define LED 13

bool oldState;

void setup() {
 Serial.begin(115200);
 pinMode(ButtonPIN, INPUT_PULLUP);
 pinMode(LED, OUTPUT);
 bool state = digitalRead(ButtonPIN);
 sendMessage(state);
 oldState = state;
 Serial.println("Setup complete");
 delay(1000);  // Ensure setup message is sent before entering the loop
 wdt_enable(WDTO_8S);  // Enable watchdog timer with an 8-second timeout
}

void loop() {
wdt_reset();  // Reset the watchdog timer

bool state = digitalRead(ButtonPIN);
 if (oldState != state) {
  digitalWrite(LED, state);
  sendMessage(state);
  delay(500);  // Debounce delay
  oldState = state;
 }
}

void sendMessage(bool state) {
 Serial.write(0x01);
 Serial.write(0x29);
 Serial.write(state ? 0x01 : 0x00);
 Serial.write(0xEE);
 Serial.write('\n');
}

How can i debug this? In the serial monitor of the Arduino IDE things are looking correct, just in python the switch stops working at some point. I already checked hardware connections, OS sleep modus, bios setting for USB ports, etc. I can also trigger the failure by toggling the hardware switch many, many times realy fast. The adurino seems to stop all communication. If i press the hardware reset button on he board all is back to normal.


Solution

  • No, the second one became male functioning as well with your code suggestion, but i was able to save it. The real problem was noise from the switch which i filtered with two 100mF conducters between pin 8 and GND and GND and VCC. By simulating the switch with a script you will create no noise. But noise can result in corrupted code like in my case.