#include <SoftwareSerial.h> // 软串口库

#define LED1 4 // LED 引脚定义 #define LED2 5 #define LED3 6 #define LED4 7 #define LED5 8 #define BTN1 2 // 按键引脚定义 #define BTN2 3

SoftwareSerial mySerial(10, 11); // 软串口定义

volatile int count1 = 0; // 记录按键次数 volatile int count2 = 0;

void setup() { pinMode(LED1, OUTPUT); // LED 引脚初始化 pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); pinMode(LED4, OUTPUT); pinMode(LED5, OUTPUT); pinMode(BTN1, INPUT_PULLUP); // 按键引脚初始化 pinMode(BTN2, INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(BTN1), btn1_isr, FALLING); // 外部中断初始化 attachInterrupt(digitalPinToInterrupt(BTN2), btn2_isr, FALLING);

mySerial.begin(9600); // 软串口初始化 }

void loop() { int num = count1 * 10 + count2; // 组合成十进制数 int bin = dec2bin(num); // 转化为二进制数 displayLED(bin); // 显示 LED mySerial.println(bin); // 打印二进制数 }

void btn1_isr() { // 按键 1 中断函数 count1++; mySerial.println('BTN1 pressed'); }

void btn2_isr() { // 按键 2 中断函数 count2++; mySerial.println('BTN2 pressed'); }

int dec2bin(int num) { // 十进制转二进制函数 int bin = 0; int k = 1; while (num) { bin += (num % 2) * k; k *= 10; num /= 2; } return bin; }

void displayLED(int bin) { // 显示 LED 函数 digitalWrite(LED1, bitRead(bin, 0)); digitalWrite(LED2, bitRead(bin, 1)); digitalWrite(LED3, bitRead(bin, 2)); digitalWrite(LED4, bitRead(bin, 3)); digitalWrite(LED5, bitRead(bin, 4)); }

Arduino 外部中断与串口通信实验:按键计数与LED显示

原文地址: https://www.cveoy.top/t/topic/nP9h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录