python - 通过 jupyter notebook 从串行捕获数据的问题
问题描述
这是我的arduino代码
我在运行 python 代码时关闭了我的 arduino ide,从过去的错误中了解到,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)
只返回了一个值,一次,不是我指定的时间也没有写入txt文件
# 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 notebook 上运行这个,而不是像 pycharm 这样的东西吗?
还是与我缺少的序列号有关
解决方案
推荐阅读
- c# - 如何在 Visual Studio 中以特定方向加载图像?
- python - 使用触摸事件获取小部件中图像的像素坐标
- javascript - 为什么这个反向堆栈函数返回未定义而不是预期的输出?
- reactjs - 为什么 React-Table 列数组对象既有 camelCasing 又有 PascalCasing
- android - 如何为流星科尔多瓦应用程序建立深层链接?
- kdb - 有没有办法将stdout作为q中的字符串重定向到变量,或者以其他方式对变量进行字符串化?
- vba - DoCmd.OpenForm 编译错误,“预期:=”
- mongodb - Spring mongo agregation 返回空列表
- javascript - 当用户将输入发送到表单时显示文本
- html - 绝对定位的行比容器宽