Pyserial正在从arduin获取不一致的数据

2024-09-26 17:59:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个由arduino读取的传感器代码,然后将该数据发送到python,以便打印并保存以供将来分析。问题是当我看到arduino的串行监视器时,它是一个一致的数字流。这就是我想要的,但是当它到达python时,偶尔会导致这个数字乘以100。这种情况大约每4行数据就发生一次。我很难根据我编写的代码和用作指导的代码来找出为什么会发生这种情况。你知道吗

阿尔杜伊诺

#include <HX711_ADC.h>
#include "CytronMotorDriver.h"


// Configure the motor driver.
CytronMD motor(PWM_DIR, 3, 2);  // PWM = Pin 3, DIR = Pin 2.

int up = HIGH;
int down = LOW;
int dstate = up;
float interval = 12000;
float pretime= 0;
float curtime = 0; 


// LOAD CELL
//HX711 constructor (dout pin, sck pin)
HX711_ADC LoadCell(11, 12);
float force;  
float calforce;
float newtons;


// The setup routine runs once when you press reset.
void setup() {
 Serial.begin(9600);
 LoadCell.begin();
 LoadCell.start(2000); // tare preciscion can be improved by adding a few seconds of stabilising time
 LoadCell.setCalFactor(100); // user set calibration factor (float)
}

// The loop routine runs over and over again forever.
void loop() {

  LoadCell.update();
  force = LoadCell.getData();
  force = (force/285); // Force in (N) // 285 is conversion factor
  calforce = (-1.0389*force)+0.0181, // This is in lbs
  newtons = 4.45*calforce;



  //receive from serial terminal for tare
  if (Serial.available() > 0) {
  char inByte = Serial.read();
  if (inByte == 't') LoadCell.tareNoDelay();
  }

unsigned long curtime = millis();

  if (dstate == up && (curtime - pretime >= interval)) {
    motor.setSpeed(255);  // Run forward at full speed.
    pretime = curtime; 
    dstate = down;


  }

  if (dstate == down && (curtime - pretime >= interval)) {
    motor.setSpeed(-255);  // Run backward at full speed.
    pretime = curtime;
    dstate = up;

  }


  Serial.println(newtons);
}

Arduino输出 0.08 0.08 0.08 0.08 0.08 0.08 0.08 0.08 0.08 0.08 0.08 0.08英寸

Python

import serial
import csv
import time
from time import localtime, strftime
#import numpy as np
import warnings
import serial.tools.list_ports


__author__ = 'Matt Munn'
arduino_ports = [
    p.device
    for p in serial.tools.list_ports.comports()
    if 'Arduino' in p.description
]
if not arduino_ports:
    raise IOError("No Arduino found - is it plugged in? If so, restart computer.")
if len(arduino_ports) > 1:
    warnings.warn('Multiple Arduinos found - using the first')

Arduino = serial.Serial(arduino_ports[0],9600)

Arduino.flush()
Arduino.reset_input_buffer()

start_time=time.time()

Force = []

outputFileName = "Cycle_Pull_Test_#.csv"
outputFileName = outputFileName.replace("#", strftime("%Y-%m-%d_%H %M %S", localtime()))

with open(outputFileName, 'w',newline='') as outfile:

    outfileWrite = csv.writer(outfile)

    while True:
        while (Arduino.inWaiting()==0):
            pass
        try:
            data = Arduino.readline()
            dataarray = data.decode().rstrip().split(',')
            Arduino.reset_input_buffer()
            Force = round(float(dataarray[0]),3)
            print (Force)
        except (KeyboardInterrupt, SystemExit,IndexError,ValueError):
            pass

        outfileWrite.writerow([Force,"N"])

Python输出 0.08 8 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08 0.08 8 0.08 8 0.08 8 0.08 8 0.08 8 0.08英寸

这只是我的代码的一部分,我打算根据传感器读数来控制一个线性执行器,但是如果我不能得到一致的数据流,那么我就不能继续这个项目。 谢谢您!你知道吗


Tags: inimportiftimeserialportsfloatarduino

热门问题