Example-Button

Button: Digital Input

This Python code uses a button to control the on and off state of the onboard LED of an Arduino UNO. The Arduino main control board is connected to a Windows or Linux computer, and the button module is connected to the D8 pin of the main control board.

# -*- coding: UTF-8 -*-
# Experiment effect: Use a button to control the Arduino UNO onboard light on and off
# Connection: Use a Windows or Linux computer to connect to an Arduino main control board, the main control board D8 is connected to a button module
import time
from pinpong.board import Board, Pin

Board("uno").begin()  # Initialization, select board type (uno, leonardo, xugu) and port number. If no port number is entered, automatic detection will be performed
# Board("uno", "COM36").begin()  # Initialization with specified port on Windows
# Board("uno", "/dev/ttyACM0").begin()  # Initialization with specified port on Linux
# Board("uno", "/dev/cu.usbmodem14101").begin()  # Initialization with specified port on Mac

btn = Pin(Pin.D8, Pin.IN)  # Initialize the pin for digital input
led = Pin(Pin.D13, Pin.OUT)

while True:
  # v = btn.value()  # Method 1 to read pin level
  v = btn.read_digital()  # Method 2 to read pin level
  print(v)  # Print the read level status in the terminal
  # led.value(v)  # Set the button status to the LED pin  Output level Method 1
  led.write_digital(v)  # Set the button status to the LED pin  Output level Method 2
  time.sleep(0.1)