如何使用pyserial向Arduino提供字符串输入?

2024-10-04 03:18:36 发布

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

尝试使用pyserial的字符串输入并将其转换为整数,然后根据该输入运行步进电机,但如果输入来自串行监视器,则我的代码会运行,如果输入来自pyserial,则不会运行

Arduino代码如下:

#include <Stepper.h>

const int stepsPerRevolution = 200; 
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0; 

const byte numChars = 40;
char receivedChars[numChars]; // an array to store the received data
char messageFromPC[40] = {0};
int integerFromPC = 0;
int integerFromPC_2 = 0;
float floatFromPC = 0.0;
boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
    myStepper.setSpeed(200);
    if (Serial.available() > 0) {
        recvWithEndMarker();
        showNewData();
        parseData();
        showParsedData();
        moveStepperMotor();
    }
}

void loop() {

}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        } else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
    }
}


void parseData() {
    if (newData == true) {
        char * strtokIndx; 
        strtokIndx = strtok(receivedChars,",");      // get the first part - the string
        strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

        strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
        integerFromPC = atoi(strtokIndx);     // convert this part to an integer

        strtokIndx = strtok(NULL, ",");
        integerFromPC_2 = atoi(strtokIndx);
    }
}

void showParsedData() {
    if (newData == true) {
        Serial.print("Message ");
        Serial.println(messageFromPC);
        Serial.print("Integer ");
        Serial.println(integerFromPC);
        Serial.print("Float ");
        Serial.println(floatFromPC);
    }
}

void moveStepperMotor(){
    if (newData == true) {

        Serial.println("starting");
        myStepper.step(integerFromPC);
        Serial.println("finished");

        Serial.println("starting");
        myStepper.step(-integerFromPC_2);
        Serial.println("finished");

        newData = false;
    }
}

python代码是:

import serial
import struct
import time

ser = serial.Serial('/dev/cu.usbmodem14101', 9600,writeTimeout=3)

# let it initialize
time.sleep(2)
str = 'This is a test, 800, 800'
ser.write(b'This is a test, 800, 800')

如何通过从python获取字符串输入来运行Arduino代码


Tags: the代码trueifserialintprintlnchar