给出下列实验的C语言代码外部中断与串口通行实验目的:掌握 ARDUINO 的外部中断引脚有哪些串行通行的接口是哪几个引脚 这在硬件层面上的应用很重要。掌握外部中断的触发与回调函数串口通行的启动等。内容:①连接 1 个按键至外部中断引脚 2 上ARDUINO 记录按键次数采用中断方式非查询方式并通过串口打印按键次数;②连接 2 个按键至外部中断引脚 23 上同时自己选取其它的 5 个端口接 5 个
#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));
原文地址: https://www.cveoy.top/t/topic/eijw 著作权归作者所有。请勿转载和采集!