实验代码如下:

// 定义外部中断引脚和LED引脚 #define INT_PIN_2 2 #define INT_PIN_3 3 #define LED_PIN_1 4 #define LED_PIN_2 5 #define LED_PIN_3 6 #define LED_PIN_4 7 #define LED_PIN_5 8

// 定义变量 volatile int count_2 = 0; volatile int count_3 = 0; int decimal = 0; int binary = 0;

void setup() { // 初始化串口通讯 Serial.begin(9600);

// 设置外部中断引脚为输入模式 pinMode(INT_PIN_2, INPUT_PULLUP); pinMode(INT_PIN_3, INPUT_PULLUP);

// 设置LED引脚为输出模式 pinMode(LED_PIN_1, OUTPUT); pinMode(LED_PIN_2, OUTPUT); pinMode(LED_PIN_3, OUTPUT); pinMode(LED_PIN_4, OUTPUT); pinMode(LED_PIN_5, OUTPUT);

// 设置外部中断触发方式为下降沿触发 attachInterrupt(digitalPinToInterrupt(INT_PIN_2), count_2_isr, FALLING); attachInterrupt(digitalPinToInterrupt(INT_PIN_3), count_3_isr, FALLING); }

void loop() { // 将十进制数转化为二进制数并控制LED显示 decimal = count_2 * 10 + count_3; binary = dec2bin(decimal); digitalWrite(LED_PIN_1, bitRead(binary, 0)); digitalWrite(LED_PIN_2, bitRead(binary, 1)); digitalWrite(LED_PIN_3, bitRead(binary, 2)); digitalWrite(LED_PIN_4, bitRead(binary, 3)); digitalWrite(LED_PIN_5, bitRead(binary, 4));

// 串口输出二进制数 Serial.println(binary, BIN); }

// 外部中断回调函数,计数器加一 void count_2_isr() { count_2++; }

void count_3_isr() { count_3++; }

// 十进制数转化为二进制数 int dec2bin(int dec) { int bin = 0; for (int i = 0; dec > 0; i++) { bin += (dec % 2) * pow(10, i); dec /= 2; } return bin;

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

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

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