且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过串行端口将数据从python发送到Arduino

更新时间:2023-11-09 13:58:16

要从 Windows 机器与Arduino板通信,您必须安装 PySerial .请参阅此处的在计算机上安装PySerial的说明: PySerial网站

To communicate with the Arduino board from a Windows machine, you have to install PySerial. See the instructions here for installing PySerial on your machine: PySerial website

并且,请确保已为您的板安装了正确的串行驱动程序.这应该与您的电路板软件一起安装.但是,如果您需要手动进行操作,以下两个链接可能会有所帮助,Sparkfun驱动程序说明Arduino驱动程序说明

And, make sure that you have installed the correct serial driver for your board. This should be installed with your board software. But, in case you need to do it manually, here are two links that may be helpful, Sparkfun driver instructions and Arduino driver instructions

然后,确保使用正确的com端口.运行arduino IDE,将程序上载到arduino,然后在工具"菜单下(在IDE中),设置com端口并运行串行监视器.然后,在串行监视器中输入"s",并确认您看到灯亮,灯灭的消息.

Then, make sure that you are using the correct com port. Run your arduino IDE, upload your program to the arduino, and then under the Tool menu (in the IDE), set the com port and run the serial monitor. Then, in the serial monitor, enter an 's' and verify that you see the light on, light off messages.

这是您的arduino和python代码,被剥去最少的指令集来演示您的示例,以及一条println()语句(在arduino代码中)以十六进制形式回显接收到的字符.该调试语句将帮助您在开发代码时整理换行等.

Here are your arduino and python codes, stripped to the minimum set of instructions to demonstrate your example, plus a println() statement (in the arduino code) to echo the received characters in hex. That debugging statement will help you sort out line feeds and so forth as you develop your code.

更改继电器的插针号和端口的设备名称后,此处列出的代码可在我的主板和Linux机器上使用.将close()注释掉只是为了向您展示它在没有该行的情况下可以工作.

The codes as listed here, work on my board and Linux machine after changing the pin number for the relay, and the device name for the port. The close() is commented-out only to show you that it works without that line.

在arduino上:

#include <stdlib.h>

char serial;
#define RELAY1  7                       
void setup()
{    
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);       
}

void loop()
{
  if(Serial.available() > 0)
  {
      serial = Serial.read();
      Serial.println( serial, HEX);
      if (serial=='s')
      {
        digitalWrite(RELAY1,0);           
        Serial.println("Light ON");
        delay(2000);                                      
        digitalWrite(RELAY1,1);          
        Serial.println("Light OFF");
        delay(2000);
      }
   } 
}

python代码:

import time
import serial

def foo():
    print("sent")
    ardu= serial.Serial('/dev/ttyACM0',9600, timeout=.1)
    time.sleep(1)
    ardu.write('s'.encode())
    time.sleep(1)
    #ardu.close()


foo()