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.]
Arduino:
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() {
Serial.begin(9600);
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: ");
Serial.print(cnt);
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
print('Hello')
dat.write(1)
print('Works')
if (dat == 1)
would make more sense since you already converted the character to a corresponding digit – Juraj Nov 26 '20 at 5:56