首页 > 解决方案 > Arduino code to python

问题描述

I have arduino code for reading two inputs and them using them to make 3 or 4 different outputs bassed on input state, i need to make that in python, but im not good with it yet. Any help would be appreciated. I would use some leds to represent states for start later on when i learn something more i would like to do something more advanced.

    int A = 3;
        int B = 4;
        int C = 5;
        int D = 6;
        int E = 7;

        void setup(){

        Serial.begin(9600);
        pinMode (A, INPUT);
        pinMode (B, INPUT);
        pinMode (C, OUTPUT);
        pinMode (D, OUTPUT);
        pinMode (E, OUTPUT);
    }

    void loop(){
        pic();
        delay (100);
        }

    void pic(){

          int a = digitalRead(A);
          int b = digitalRead(B);

        if(a == LOW && b == LOW){
        Serial.print("something");  
    digitalWrite(C, HIGH) 
    digitalWrite(D, LOW)
    digitalWrite(E, LOW)
        }

         if(a == LOW && b == HIGH){
  Serial.print("something");  
    digitalWrite(C, LOW) 
    digitalWrite(D, HIGH)
    digitalWrite(E, LOW)     
        }

        if(a == HIGH && b == LOW{
  Serial.print("something");  
    digitalWrite(C, LOW) 
    digitalWrite(D, HIGH)
    digitalWrite(E, LOW)
        }

        if(a == HIGH && b == HIGH){
  Serial.print("something");  
    digitalWrite(C, LOW) 
    digitalWrite(D, LOW)
    digitalWrite(E, HIGH)
        }

        }

标签: pythoninputarduinooutputraspberry-pi3

解决方案


Try this You must install RPi.GPIO if not

pip install RPi.GPIO
import RPi.GPIO as GPIO
from time import sleep

# Use on of this. (visit https://pinout.xyz/ for more details)
# GPIO.setmode(GPIO.BOARD)  # If you are using number on the board (1 --> 3.3V, 2 --> 5V)
GPIO.setmode(GPIO.BCM)    # If you are using the Broadcom numbering

A = 5
B = 6
C = 13
D = 19
E = 26


def pic():
    a = GPIO.input(A);
    b = GPIO.input(B);

    if a == GPIO.LOW and b == GPIO.LOW:
        print("something");
        GPIO.output(C, GPIO.HIGH)
        GPIO.output(D, GPIO.LOW)
        GPIO.output(E, GPIO.LOW)

    if a == GPIO.LOW and b == GPIO.HIGH:
        print("something");
        GPIO.output(C, GPIO.LOW)
        GPIO.output(D, GPIO.HIGH)
        GPIO.output(E, GPIO.LOW)

    if a == GPIO.HIGH and b == GPIO.LOW:
        print("something")
        GPIO.output(C, GPIO.LOW)
        GPIO.output(D, GPIO.HIGH)
        GPIO.output(E, GPIO.LOW)

    if a == GPIO.HIGH and b == GPIO.HIGH:
        print("something")
        GPIO.output(C, GPIO.LOW)
        GPIO.output(D, GPIO.LOW)
        GPIO.output(E, GPIO.HIGH)


GPIO.setup(A, GPIO.IN)
GPIO.setup(B, GPIO.IN)
GPIO.setup(C, GPIO.OUT)
GPIO.setup(D, GPIO.OUT)
GPIO.setup(E, GPIO.OUT)

while True:
    pic()
    sleep(100 / 1000)

To run execute in a terminal

python filename.py

推荐阅读