Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]


int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';
              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED

Python code:

import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
  • 3
    if (dat == 1) would make more sense since you already converted the character to a corresponding digit
    – Juraj
    Commented Nov 26, 2020 at 5:56

2 Answers 2


Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like dat.write(b'1') and then receive it on the Arduino using Serial.readString(). I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)" If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.


try with Firmata, it is a protocol that establishes serial communication between the computer with Arduino. All you have to do is have the Firmata on Arduino Board, and pyFirmata plugin available to talk with Arduino from Python on your machine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.