Python Forum
Stop the serial read until video is recorded
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stop the serial read until video is recorded
#1
Hi

im new to python so of course i do understand that if this is a stupid question or at least an easy fix. my code does work as it takes a picture, records a video when reading something from the serial port. the issue i am facing is that once it read something it should take a picture and record a video, while it is doing that for some reason it still continues to read, so as soon as the picture is taken and the video is recorded for 8 seconds it just starts doing it again, taking another picture and making another video. im guessing that the code is storing the data from the serial port so as soon as it is done it does it again. so is there a way to disable the port and then re-enable it once the video is done.

below is my code
# Write your code here :-)
import cv2
import numpy as np
import tkinter as tk
from PIL import Image, ImageTk
import datetime
import os
import argparse
import serial
from picamera import PiCamera
import time

serialPort = serial.Serial(port = "/dev/ttyUSB0", baudrate=115200,
                           bytesize=8, timeout=0, stopbits=serial.STOPBITS_ONE)

output_path = "/home/pi/Pictures"

window = tk.Tk()
window.wm_title("Trusign Camera")
window.config(background="#FFFFFF")

var = tk.StringVar(window)

imageFrame = tk.Frame(window, width=1000, height=840)
imageFrame.grid(row=0, column=0, padx=0, pady=0)

lmain = tk.Label(imageFrame)
lmain.grid(row=0, column=0)
cap = cv2.VideoCapture(0)
#cap.set(3, 1000)
#cap.set(4, 840)
cap.set(3, 640)
cap.set(4, 480)

global check
check = 0

def show_frame():
    _, frame = cap.read()
    #frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    show_frame.curent_frame = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_frame)
    serial_read_data()

def serial_read_data():
    global check
    if(serialPort.in_waiting > 0 and check == 0):
        serialString = serialPort.readline()
        global serialresult
        global serialresulting
        serialresult = int(serialString.decode('Ascii'))
        serialresulting = str(serialresult )
        var.set(serialresulting + "MPH")
        serialPort.flush()
        if(serialresult > 18 and check == 0):
            check = 1
            print("Take SnapShot")
            serial_read_data.speed_result = serialresult
            take_snapshot()
        else:
            pass
    else:
        pass

def take_snapshot():
    ts = datetime.datetime.now() # grab the current timestamp
    filename = "{}.png".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))  # construct filename
    p = os.path.join(output_path, filename)  # construct output path
    speed_result_2 = serial_read_data.speed_result
    image2 = np.array(show_frame.curent_frame)
    cv2.putText(image2,"Speed :" + str(speed_result_2)+"Mph", (10,25), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
    cv2.imwrite(p,cv2.cvtColor(image2, cv2.COLOR_RGB2BGR))
    print(p)
    take_video()


def take_video():
    global check
    td = datetime.datetime.now()
    filename2 = "{}.mp4".format(td.strftime("%Y-%m-%d_%H-%M-%S"))
    n = os.path.join(output_path, filename2)
    save_name = "output.mp4"
    fps = 20
    width = 600
    height = 480
    output_size = (width, height)
    out = cv2.VideoWriter(n,cv2.VideoWriter_fourcc('M','J','P','G'), fps, output_size )
    for z in range(0,161,1):
        _, frame2 = cap.read()
        #cv2.putText(frame2,"Speed : 0Mph", (10,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        out.write(cv2.resize(frame2, output_size))
        if(z == 160):
            out.release()
            print("Save")
            check = 0
        else:
            print("")


#Slider window (slider controls stage position)
sliderFrame = tk.Frame(window, width=200, height=480)
sliderFrame.grid(row = 0, column=640, padx=0, pady=0)
sliderFrame.config(background="#FFFFFF")

l = tk.Label(sliderFrame, text="Speed")
l.config(font =("Courier", 23), background="#FFFFFF")



l2 = tk.Label(sliderFrame, textvariable = var)
l2.config(font =("Courier", 15), background="#FFFFFF")

btn = tk.Button(sliderFrame, text = "Test Shot", command=take_snapshot)

l.place(x=40, y=0)
l2.place(x=70, y=50)
btn.place(x=60, y=440)

#serial_read_data()
show_frame()
window.mainloop()
i have been stuck on it for ages and if anyone could help that would be great

Thank you
Reply
#2
you could use serialPort.close() and re-initialize as required

put your Initialization code in a separate function
you can set a serial_port_active boolean true or false here, then before using the port for data transfer test boolean, and reopen port if required.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 3,325 Aug-24-2023, 07:56 AM
Last Post: gowb0w
  Python Serial: How to read the complete line to insert to MySQL? sylar 1 787 Mar-21-2023, 10:06 PM
Last Post: deanhystad
  UART Serial Read & Write to MP3 Player Doesn't Work bill_z 15 5,647 Jul-17-2021, 04:19 PM
Last Post: bill_z
  Unable to read from serial port br0kenpixel 1 2,428 Aug-08-2020, 10:03 PM
Last Post: Larz60+
  Read Data from Serial Port PA3040 3 3,130 Feb-16-2020, 04:54 AM
Last Post: PA3040
  Read serial BR=9600 . print me 2 lines? korenron 1 2,236 Dec-31-2019, 06:39 PM
Last Post: DeaD_EyE
  Python Read/Write serial dlizimmerman 0 6,588 Jan-31-2019, 03:12 AM
Last Post: dlizimmerman
  How to extract temperature value of pixels of a thermal image recorded by IR camera hamacvan 1 14,380 Jan-13-2019, 06:06 PM
Last Post: Larz60+
  serial communication write(comand) and read(result) ricardons 1 2,877 Mar-01-2018, 04:26 PM
Last Post: mpd
  NMEA read parse and write from/to serial port ESEAMarine 1 10,532 Aug-11-2017, 12:36 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020