Как заставить Python отправлять целое число в Arduino, чтобы оно заменяло переменную - PullRequest
0 голосов
/ 22 марта 2019

Я пытаюсь управлять подключением двигателя к моему arduino с помощью python.Я пытаюсь передать силу, с которой я хочу, чтобы мотор переключал направление.Сила исходит от чтения тензодатчика.Так что, если, скажем, пользователь говорит 50 ньютонов, я хочу, чтобы направление вращения двигателя изменилось на 50 ньютонов.Я также хочу отправить его, сколько раз я хочу, чтобы он изменил направление.Поэтому я отправляю arduino 2 различных целых числа, чтобы расшифровать его.Прямо сейчас он не обновляет порог силы, когда я прошу Python сделать это.

Я пробовал подход, заставляющий python указывать arduino переключаться каждый раз, когда вводится значение силы, однако это вызывает входящую силузначения из arduino в python, чтобы все запуталось, где будет отображаться фактическая сила в течение нескольких итераций, а затем будет отображаться какое-то случайное число.Это не хорошо, когда кто-то должен анализировать эти данные.

Arduino

#include <HX711_ADC.h> // HX711 Library
#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;
int python_direction = 0;
float interval = 12000;
float pretime= 0;
float curtime = 0;
float maxForce = 5;
float cycles = 5;
float force;  
float calforce;
float newtons;
int incoming[1];
HX711_ADC LoadCell(11, 12);



void setup() {
  Serial.begin(19200);
  LoadCell.begin();
  LoadCell.start(2000); // tare preciscion can be improved by adding a few seconds of stabilising time
  LoadCell.setCalFactor(100.0); // user set calibration factor (float)
}

void loop() {

  if (Serial.available()>0){

    for (int i = 0; i < 2; i++){
      incoming[i] = Serial.read();
      float(maxForce) = incoming[0];
      float(cycles) = incoming[1];
      delay(1000);}
  }

  LoadCell.update();
  forceRead();
  motorControl(); 
  Serial.print(newtons);
  Serial.print(',');
  Serial.println(maxForce);
}


void forceRead(){

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

  //receive from serial terminal for tare

  if (Serial.available() > 0) {
  char inByte = Serial.read();
  if (inByte == 't') LoadCell.tareNoDelay();
  }
}
void motorControl(){

  if (newtons > maxForce){
  motor.setSpeed(255);  // Run backward at full speed.

  }
  if (newtons < maxForce){
    motor.setSpeed(-255);

  }

  }

Python

import serial
import csv
import struct
import time
from time import localtime, strftime
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],19200,timeout=1)
time.sleep(3)

Force_Input = input("What is the force you want to test with in Newtons?")
Cycles = input("How many cycles would you like to run?")
Material = input("What kind of material is to be tested?")
print("The test will be conducted with", Force_Input, " Newtons of force and for a total of" , Cycles, " cycles.", " on", Material)
print ("REMOVE HANDS AND OTHER OBJECTS AWAY FROM AREA OF OPERATION.")
print("Testing will begin.")
numPoints = 10
ForceList = [0]*numPoints
AvgForce = 0

arduinoInput = Arduino.write(struct.pack('>BB', int(Force_Input),int(Cycles)))
time.sleep(5)
print("Arduino has received your input")


start_time = time.time()
#This creates the unique file for saving test result data.
outputFileName =  "  Cycle_Pull_Test_#.csv"
outputFileName = outputFileName.replace("#", strftime("%Y-%m-%d_%H %M %S", localtime()))



with open(outputFileName, 'w',newline='') as outfile:
    HeaderNames = ['Material','Newtons','Time']
    outfileWrite = csv.DictWriter(outfile, fieldnames = HeaderNames)
    outfileWrite.writeheader() 
#This takes the data from the arduino and interprits it.
    while True:

        while (Arduino.inWaiting()==0):
            pass
        try:
            data = Arduino.readline()
            dataarray = data.decode().rstrip().split(',')
            for i in range(0,numPoints):
                Force = abs(round(float(dataarray[0]),3))
                maxForce =abs(round(float(dataarray[1]),3))
                ForceList[i] = Force
                AvgForce = round((sum(ForceList)/numPoints),3)
                elapsed_time = round(time.time()-start_time,3)
                print (AvgForce,maxForce, elapsed_time)
        except (KeyboardInterrupt, SystemExit,IndexError,ValueError):
            pass
#This writes the data from the loadcell to a csv file for future use.
        outfileWrite.writerow({'Material' : Material, 'Newtons' : AvgForce, 'Time' :elapsed_time })


Я надеюсь получить это, чтобы получить пользователявведите и используйте его для переключения направления между.

...