两者之间的区别读序列号()和串行读取()

2024-09-28 03:15:44 发布

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

目前我正试图通过串行端口从python向Arduino发送信息。在

我只使用一个字母Serial.read()'p'并用以下代码在我的Arduino上执行一个操作。在

Arduino代码:

#define arduinoLED 12   // Arduino LED on board

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(arduinoLED, OUTPUT);     // Configure the onboard LED for output
  digitalWrite(arduinoLED, LOW);   // default to LED off
 }

void loop() {
// put your main code here, to run repeatedly:
//delay (20000);
//char comein=Serial.read();
//Serial.println(comein);
char *arg = "hello";
if (Serial.read()== 'P'){


digitalWrite(arduinoLED, HIGH);
delay(5000);
}
else {
digitalWrite(arduinoLED, LOW);
Serial.println("Hello World");
}
}

Python代码:

^{pr2}$

这很好地工作,并且打开了我的LED,但我如何管理多个字母的命令,例如'p12018'的LED打开?在

但我真正的问题是,我试图做完全相同的事情,使用相同的Python代码,但是使用SCmd.readSerial()来读取Arduino中的信息,例如:

Arduino代码:

 #include <SerialCommand.h>

 #define arduinoLED 12   // Arduino LED on board

 SerialCommand SCmd;   // The demo SerialCommand object

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(arduinoLED, OUTPUT);     // Configure the onboard LED for output
  digitalWrite(arduinoLED, LOW);   // default to LED off


  SCmd.addCommand("P1", process_command1); // Converts two arguments to integers and echos them back
  SCmd.addCommand("P", relay1_on);       // Turns Relay1 on
  SCmd.addDefaultHandler(unrecognized);  // Handler for command that isn't matched  (says "What?")
  Serial.println("Ready");
  }

  void loop() {
  // put your main code here, to run repeatedly:

  SCmd.readSerial();     // We don't do much, just process serial commands


 }

 void relay1_on()
{
  digitalWrite(12, HIGH);
  Serial.println(3000);
  delay(3000);
  digitalWrite(12, LOW);
 }

void process_command1()
{
  int aNumber = 5;
  char *arg = "hello";

  Serial.println("We're in process_command");
  arg = SCmd.next();
  int OhmPosition = atoi(arg); //will return only numbers
  arg = SCmd.next();
  int relay = atoi(arg); //will return only numbers
  arg = SCmd.next();
  int opentime = atoi(arg); //will return only numbers

  Serial.println(OhmPosition);
  Serial.println(relay);
  Serial.println(opentime);
  }

正如你所看到的,他们的is串行命令,响应的是'p'这是同一个例子,但它不起作用,因为某些原因,不明白为什么。有什么想法吗?在

第二个串行命令是'P1',这是我想在结尾处得到的,所以我可以从Python发送类似于:

Python代码:

my_string6 = 'P1'+str(actions_time_[0][0] )+' '+str(actions_time_[0][1])+' '+str(actions_time_[0][2]))
my_string_as_bytes=str.encode(my_string6)
print(my_string_as_bytes)
ser.write(my_string_as_bytes)
output looks like this=> b'P1 150.0 5.0 2000.0 '

为了使我能够启动P1命令并发送要保存在OhmPosition中的值,中继,时间将被一个空格隔开,因为目标是引导一个小型的电气自动化。在

我将非常高兴得到您的支持,在这些夫妇之间的点相互关联。在


Tags: to代码ledonmysetupserialarg
1条回答
网友
1楼 · 发布于 2024-09-28 03:15:44

你的程序如何区分接收“P1”命令和接收“p”命令后随机“1”的区别

您的代码似乎依赖于一个不是Arduino安装的标准部分的库。您应该提供一个指向SerialCommand类的链接。在

相关问题 更多 >

    热门问题