首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Arduino系列尺寸

Arduino系列尺寸
EN

Stack Overflow用户
提问于 2014-10-23 10:02:06
回答 1查看 140关注 0票数 0

我正试图通过带有python的usb电缆向arduino发送消息。

代码语言:javascript
复制
#!python3

import serial
import time
import api
import sys

api = api.API()

arduino = serial.Serial('COM3', 115200, timeout=.1)
time.sleep(2)

while api['IsOnTrack'] == True:
        if api['Gear'] == 3:
            arduino.write('pinout 13')
            print "Sending pinon 13"
            msg = arduino.read(arduino.inWaiting())
            print ("Message from arduino: ")
            print (msg)
            time.sleep(2)

Arduino:

代码语言:javascript
复制
// Serial test script

int setPoint = 55;
String command;

void setup()
{

  Serial.begin(115200);  // initialize serial communications at 9600 bps
  pinMode(13,OUTPUT);
}

void loop()
{
  while(!Serial.available()) {
  }
   // serial read section
  while (Serial.available())
  {
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer


  if(c == '\n')
  {
    parseCommand(command);
    command = "";
  }
  else
  {
    command += c;          //makes the string command
  } 
    }
  }
  if (command.length() >0)
  {
    Serial.print("Arduino received: ");  
    Serial.println(command); //see what was received
      }
}
void parseCommand(String com)
{
  String part1;
  String part2;

  part1 = com.substring(0, com.indexOf(" "));
  part2 = com.substring(com.indexOf(" ") +1);

  if(part1.equalsIgnoreCase("pinon"))
  {
    int pin = part2.toInt();

    digitalWrite(pin, HIGH);
  }
  else if(part1.equalsIgnoreCase("pinoff"))
  {
    int pin = part2.toInt();

    digitalWrite(pin, LOW);
  }
  else
  {
    Serial.println("Wrong Command");
  }
}

Python如下所示:http://i.imgur.com/IhtuKod.jpg

例如,我可以让arduino读一次消息并清除序列吗?或者你能发现我犯的一个明显的错误吗?

而只使用Arduino IDE串行监视器。当我写"pinon 13“时,led会亮起来,这在使用python时不起作用。或者当我从串行监视器发送"pinout 13“消息时,它会告诉我这是一个”错误的命令“,在使用python时也不会发生这种情况。

你们知道我该如何让蟒蛇只发一次信息而不是连络吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-23 10:21:09

在Python代码中,您必须在命令之后编写/发送一个\n,以便Arduino识别。

serial.write('pinon 13\n');应该可以工作;但是请注意,\n可能在不同的系统上产生不同的结果(例如。因此,您可能希望在Arduino和PC上显式使用相同的ASCII代码。

在Python中,这应该是chr(10),在Arduino上,如果需要,可以使用if(c == 10)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26525693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档