同步Arduino和Python
我有一些Arduino代码,可以移动我想要与python脚本同步的电机,以使用串行总线控制它 这是Arduino代码:同步Arduino和Python,python,serial-port,arduino,Python,Serial Port,Arduino,我有一些Arduino代码,可以移动我想要与python脚本同步的电机,以使用串行总线控制它 这是Arduino代码: #define BUFFER_SIZE 100 #define P1_STEP_PIN 31 #define P1_DIR_PIN 33 #define P1_ENABLE_PIN 29 #define V1_STEP_PIN 25 #define V1_DIR_PIN 27 #define V
#define BUFFER_SIZE 100
#define P1_STEP_PIN 31
#define P1_DIR_PIN 33
#define P1_ENABLE_PIN 29
#define V1_STEP_PIN 25
#define V1_DIR_PIN 27
#define V1_ENABLE_PIN 23
char buffer[BUFFER_SIZE];
int pins[1][2][2] = {
{ {P1_STEP_PIN, P1_DIR_PIN}, {V1_STEP_PIN, V1_DIR_PIN} }
};
void setup()
{
Serial.begin(115200);
Serial.flush();
// pins setup
}
void loop()
{
get_command();
}
void get_command()
{
if (Serial.available() > 0) {
int index = 0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if ( numChar > ( BUFFER_SIZE - 3 ) ) { //avoid overflow
numChar = ( BUFFER_SIZE - 3 );
}
while (numChar--) {
buffer[index++] = Serial.read();
}
process_command(buffer);
}
}
void process_command(char* data)
{
char* parameter;
parameter = strtok (data, " "); // strtok splits char* in " "
while (parameter != NULL) {
long dir, pump, motor, sp, steps;
switch ( parameter[0] ) {
// moves the motor around
}
parameter = strtok(NULL, " ");
}
for ( int x=0; x < BUFFER_SIZE; x++) {
buffer[x] = '\0';
}
Serial.flush();
Serial.write("ok");
}
#定义缓冲区大小100
#定义P1_步骤_引脚31
#定义P1_方向_引脚33
#定义P1_启用_引脚29
#定义V1_步骤_针脚25
#定义V1_DIR_引脚27
#定义V1_启用_引脚23
字符缓冲区[缓冲区大小];
int引脚[1][2][2]={
{{P1_步进_针,P1_方向_针},{V1_步进_针,V1_方向_针}
};
无效设置()
{
序列号开始(115200);
Serial.flush();
//引脚设置
}
void循环()
{
get_命令();
}
void get_命令()
{
如果(Serial.available()>0){
int指数=0;
延迟(100);//让缓冲区填满
int numChar=Serial.available();
如果(numChar>(缓冲区大小-3)){//避免溢出
numChar=(缓冲区大小-3);
}
而(努姆查尔--){
缓冲区[index++]=Serial.read();
}
进程_命令(缓冲区);
}
}
无效进程_命令(字符*数据)
{
char*参数;
参数=strtok(数据,“”;//strtok在“”中拆分字符*
while(参数!=NULL){
长方向,泵,电机,sp,步骤;
开关(参数[0]){
//转动马达
}
参数=strtok(空,“”);
}
用于(int x=0;x
Python部分是我遇到问题的地方。当我从Python发送命令来移动马达时,Arduino代码工作得很好,但当我连续发送多个命令时,它会失败,因为我怀疑Python会同时发送所有内容,而不是等待Arduino完成每个操作
因此,基本上在Python中,我尝试了一些东西,主要是像ser.readline()或ser.read(2)之类的东西,并检查命令是否“ok”
奇怪的是,每个命令都应该有一个“ok”,但是没有,不是所有的命令都到达Python。我试图“冲洗”它,但它是一样的
我创建了一个线程,它不断地从串行中侦听命令,并检查命令是否“正常”,但事实并非如此。如果我发送4个命令,可能会收到2个“正常”,有时是0,有时是1。与其一次最多读取97个字节(
缓冲区大小-3
),不如尝试发送一个“命令结束”字符(或字符序列)来自Python代码
在Arduino草图中,阅读直到您收到此“命令结束”序列,然后运行该命令