当前位置: 移动技术网 > IT编程>脚本编程>Python > PC-Arduino Serial communication using python

PC-Arduino Serial communication using python

2020年07月29日  | 移动技术网IT编程  | 我要评论

PC-Arduino Serial communication

介绍

记录最简单的用python和Arduino实现异步通信的方法, 通过使用python serial 模块让Arduino 的build-in LED实现开关

PC: python serial 程序

import serial
import serial.tools.list_ports, warnings

#port detection - start
ports = [
    p.device
    for p in serial.tools.list_ports.comports()
    # if 'USB' in p.description
]

print (ports)

if len(ports) > 1:
    warnings.warn('Connected ...')

ser = serial.Serial(ports[0],9600) # to connect the first ports

while 1:
    val = input("Enter 0 or 1 to control the LED:")
    ser.write(val.encode())

Arduino代码

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); // set the baud rate of 9600 bps
  Serial.println("Ready"); // print "Ready" once
  pinMode (13, OUTPUT); // configure the on-board LED as output
}

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

  if (Serial.available())// if the receiver is full
  {
    switch (Serial.read())
    {
      case '0': digitalWrite(13, LOW);
                break;
      case '1': digitalWrite(13, HIGH);
                break;
      default:  break;
    }
    delay(1); // delay for 0.1 second for each loop
  }
}

本文地址:https://blog.csdn.net/Chen1189/article/details/107634722

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网