Проблема с захватом данных из последовательного через ноутбук Jupyter - PullRequest
1 голос
/ 27 февраля 2020

Это мой код arduino

Я закрыл свой arduino ide во время выполнения кода python, узнал из прошлых ошибок, что доступ к com-порту может получить только одно приложение за один раз

int analogPin = A0;
int ledPin = 13;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  int ledPin = 13;  
}

void loop() {
  // put your main code here, to run repeatedly:
  if( millis() % 20 != 0 )       // so a reading is taken every 2 milliseconds
       return;
  // turn the ledPin on
  digitalWrite(ledPin, HIGH);
  val = analogRead(analogPin);  // read the input pin
  Serial.println(val);          // debug value
  // turn the ledPin off:
  digitalWrite(ledPin, LOW);
}

он работает правильно и дает мне показания каждый фиксированный интервал и может быть захвачен или просмотрен в интегрированном последовательном мониторе arduino ide

Это мой python код

import time
import logging
import threading
import numpy as np
import cv2
import serial

# configure serial for reading from arduino
# set baudrate and port name accordingly
COM = 'COM6'
baudRate = 9600
sensorDataFileName = r"C:\Users\cy316\Documents\FYP\SensorData.txt"
videoCaptureName = "CameraCapture.mp4"
captureTime = 10
fourcc = cv2.VideoWriter_fourcc(*'MP4V')

ser = serial.Serial(COM, baudRate)
cap = cv2.VideoCapture(0) # 0 for video camera
time.sleep(10) #allow time for arduino to reset
# function for writing the arduino readings into a file
def sensorreading(ser, stoptime):
    sensordatafile = open(sensorDataFileName,"w+") 
    starttime = time.time()
    data = []

    while ((starttime-time.time())%0.02 == 0): # run every 20ms, better than delay which might or might not be on time
        b = ser.readline()
        string_n = b.decode()
        string = string_n.rstrip()
        flt = float(string)
        print(flt)
        data.append(flt)           # add to the end of data list
        time.sleep(0.02)           # wait for arduino to take new reading

        if (starttime-time.time()>stoptime): # if i reach stoptime, return
            sensordatafile.close()
            return
# function for video capture
def videocapture(cap, stoptime):
    starttime = time.time()
    # check if camera is available
    if (cap.isOpened() == False):
        print("Unable to read camera feed")
        return
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    out = cv2.VideoWriter(videoCaptureName,fourcc, 30, (frame_height,frame_width))
    cv2.imshow('Frame',frame)
    while(starttime-time.time()<stoptime):
        ret, frame = cap.read()
        out.write(frame)
    out.release()
    return
# testcell
sensorreading(ser,captureTime)

возвратил только одно значение, один раз, и не мой указанный тайминг также не смог записать его в текстовый файл

# The cell i want to run for simultaneous sensor and camera values
SensorThread = threading.Thread(target=sensorreading(ser,captureTime), args=(1,))
VideoThread = threading.Thread(videocapture(cap,captureTime), args=(1,))

SensorThread.start()
VideoThread.start()

это потому, что я запускаю эту записную книжку Jupyter, а не что-то вроде pycharm?

или это связано с серийным кодом, которого мне не хватает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...