①代码:

int buttonPin = 2; //按键接口 volatile int buttonCount = 0; //按键次数

void setup() { Serial.begin(9600); pinMode(buttonPin, INPUT_PULLUP); //设置按键接口为输入并上拉 attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, FALLING); //设置中断回调函数 }

void loop() { Serial.print("Button count: "); Serial.println(buttonCount); //每隔一秒打印按键次数 delay(1000); }

void buttonInterrupt() { buttonCount++; //中断回调函数,按键次数加1 }

②代码:

int buttonPin1 = 2; //按键1接口 int buttonPin2 = 3; //按键2接口 int ledPins[5] = {4, 5, 6, 7, 8}; //LED接口 volatile int buttonCount1 = 0; //按键1次数 volatile int buttonCount2 = 0; //按键2次数 int decimalNum = 0; //十进制数 int binaryNum[5] = {0, 0, 0, 0, 0}; //二进制数

void setup() { Serial.begin(9600); pinMode(buttonPin1, INPUT_PULLUP); //设置按键1接口为输入并上拉 pinMode(buttonPin2, INPUT_PULLUP); //设置按键2接口为输入并上拉 for (int i = 0; i < 5; i++) { pinMode(ledPins[i], OUTPUT); //设置LED接口为输出 } attachInterrupt(digitalPinToInterrupt(buttonPin1), buttonInterrupt1, FALLING); //设置按键1中断回调函数 attachInterrupt(digitalPinToInterrupt(buttonPin2), buttonInterrupt2, FALLING); //设置按键2中断回调函数 }

void loop() { decimalNum = buttonCount1 * 10 + buttonCount2; //将按键次数组合成十进制数 for (int i = 0; i < 5; i++) { binaryNum[i] = decimalNum % 2; //将十进制数转化为二进制数 decimalNum /= 2; } for (int i = 0; i < 5; i++) { digitalWrite(ledPins[i], binaryNum[i]); //根据二进制数控制LED亮灭 } Serial.print("Binary number: "); for (int i = 4; i >= 0; i--) { Serial.print(binaryNum[i]); //打印二进制数 } Serial.println(); delay(100); }

void buttonInterrupt1() { buttonCount1++; //按键1中断回调函数,按键1次数加1 }

void buttonInterrupt2() { buttonCount2++; //按键2中断回调函数,按键2次数加1

该外部中断与串口通行实验的C语言代码怎么写目的:掌握 ARDUINO 的外部中断引脚有哪些串行通行的接口是哪几个引脚 这在硬件层面上的应用很重要。掌握外部中断的触发与回调函数串口通行的启动等。内容:①连接 1 个按键至外部中断引脚 2 上ARDUINO 记录按键次数采用中断方式非查询方式并通过串口打印按键次数;②连接 2 个按键至外部中断引脚 23 上同时自己选取其它的 5 个端口接 5 个 LE

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

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