Search code examples
pythonarduinopyserial

pySerial sending data from Python to arduino


I have a question about sending data using the pySerial Python library.

I'm new to this library and sorry about my bad english.

How can i send the data from python to Arduino continuously? For example, i want to send a string that contain 1 digit (0 or 1), can i put it in while loop in python?

For example:

import serial
import time
import cv2
import mediapipe as mp
from cvzone.HandTrackingModule import HandDetector
ser = serial.Serial('COM5', 9600)

#initiate webcam
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

x3 = 0
y3 = 0
xgrab = 0
ygrab = 0
grab = 0 
# hand detector
detector = HandDetector(detectionCon=0.8, maxHands=1)

while True:
  success, image = cap.read()
  hands = detector.findHands(image, draw=False)
  if hands:
    lmList = hands[0]['lmList']
    xgrab, ygrab = lmList[4][:2]
    x3, y3 = lmList[3][:2]
    if xgrab < x3:
        grab = 1
    else:
        grab = 0
  else:
      grab = 0
  grab = str(grab)
  ser.write(grab.encode())
  cv2.imshow('Control window', cv2.flip(image,1))
  if cv2.waitKey(5) & 0xFF == 27:
      break
cap.release()
        

This code will detect your hand gesture and send 1 or 0 to Arduino. Since i put the ser.write command in while loop to send it continuously, but somehow it doesn't work as i expected. My arduino doesn't turn on/off the LED though.

Here is my Arduino code:

String Recstring;
void setup() {

Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
if (Serial.available()){
  Recstring = Serial.readStringUntil('\n');
  if (Recstring == "1"){
    digitalWrite(LED_BUILTIN, HIGH);
  }
  else{
    digitalWrite(LED_BUILTIN, LOW);
  }
  }
}

I don't know if Arduino doesn't read the data fast enough to turn on/off LED. I've tried put some time.sleep to delay the data but it still like that.


Solution

  • So i need to add \n to grab = str(grab) + '\n' in my python code and it will work.

    Thanks to Mark Setchell.