簡體   English   中英

pySerial和Arduino通訊

[英]pySerial and Arduino communication

到目前為止,我正在使用pySerial和Arduino探索Python。 我做了一些項目,其中pySerial從串行端口讀取某些內容。

import serial 

arduinoSerialData = serial.Serial('com11',9600) #Create Serial port object called arduinoSerialData


while (1==1):
    if (arduinoSerialData.inWaiting()>0):
        myData = arduinoSerialData.readline()
        print (myData)
int trigPin=13; //Sensor Trig pin connected to Arduino pin 13
int echoPin=11;  //Sensor Echo pin connected to Arduino pin 11
float pingTime;  //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

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

  digitalWrite(trigPin, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state

  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)

  Serial.println(targetDistance);

  delay(100); //delay tenth of a  second to slow things down a little.
}

現在,我的代碼看起來像這樣。 如何使用Python中的超聲波傳感器並將信號發送到Arduino程序? 換句話說,我可以讓我的Arduino文件從我擁有的Python文件中讀取還是僅僅是一個方向?

pySerial允許雙向雙向通訊。 在Arduino端,您需要在適當的地方調用Serial.read來從Python讀取數據流。 在Python中,您只需要使用serial.write函數發送數據。 如果使用Python 3,則serial.write輸入必須為byte格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM