python 和 arduino 之间的串行通信

serial communictation between python and arduino

我将值 arduino 发送到 python。这是我的代码的一部分。

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "Timer.h"



int IR_sensor = A0;
int value;

void setup(void)
{
  Serial.begin(9600);
  pinMode(IR_sensor, INPUT);
}

void loop() {

  long IR_value = analogRead(IR_sensor);
  long IR_range = gp2y0a21yk(IR_value);

  //Serial.println(IR_value);
  //Serial.print(IR_range);
  //Serial.println("cm");
  //Serial.println();
  if (IR_range < 50)
  {
    value = 1;
    Serial.println(value);
  }

  else {
    value = 0;
    Serial.println(value);
  }
  delay(1000);

      if (value == 1)
      {
        Serial.println("1234"); 

      }

    }

long gp2y0a21yk(long IR_value)
{
  if (IR_value < 10)
  {
    IR_value = 10;
  }

  return ((67870.0 / (IR_value - 3.0)) - 40.0) / 10;
}

所以这个代码有两个选项。第一个值 =0 或值 = 1 然后 1234

这是我的python代码

import serial
import time
import MySQLdb
from datetime import datetime
import cv2
import boto3


port ="COM15"
brate = 9600
arduino =serial.Serial(port, baudrate = brate, timeout=None)


while True:

    data= arduino.readline()str = data[:-2].decode()
    print(str)


    if str=="0":
        print("nobody")

我想知道的是这部分。 data=arduino.readline() 此代码读取值 0 或 1 和 1234。我想做的是将此值保存到 data1 和 data2,我想使用此值!例如,如果 python 获取值=0 我想将此值保存到 a=0 然后使用 if 子句,如果 python 获取值 =1 和 1234 我想保存此 a= 1 和 b=1234 并将其用于 if 子句。你有什么想法?我真的很感激!

由于您的 arduino 将仅输出 0 或 1 和 1234,只需在 if 语句后添加 else

a = int(str)
if str=="0":
    print("nobody")
else:
    b = int(arduino.readline()[:-2].decode())