下面是该实验的C语言代码:

const int buttonPin2 = 2;    // 外部中断引脚2连接的按键
const int buttonPin3 = 3;    // 外部中断引脚3连接的按键
const int ledPin1 = 4;       // LED1的引脚
const int ledPin2 = 5;       // LED2的引脚
const int ledPin3 = 6;       // LED3的引脚
const int ledPin4 = 7;       // LED4的引脚
const int ledPin5 = 8;       // LED5的引脚

volatile int count2 = 0;     // 外部中断引脚2上按键次数
volatile int count3 = 0;     // 外部中断引脚3上按键次数

void setup() {
  pinMode(buttonPin2, INPUT_PULLUP);  // 使能外部中断引脚2上的上拉电阻
  pinMode(buttonPin3, INPUT_PULLUP);  // 使能外部中断引脚3上的上拉电阻
  pinMode(ledPin1, OUTPUT);          // 将LED1引脚设为输出模式
  pinMode(ledPin2, OUTPUT);          // 将LED2引脚设为输出模式
  pinMode(ledPin3, OUTPUT);          // 将LED3引脚设为输出模式
  pinMode(ledPin4, OUTPUT);          // 将LED4引脚设为输出模式
  pinMode(ledPin5, OUTPUT);          // 将LED5引脚设为输出模式

  attachInterrupt(digitalPinToInterrupt(buttonPin2), button2ISR, FALLING);  // 附加外部中断2的回调函数
  attachInterrupt(digitalPinToInterrupt(buttonPin3), button3ISR, FALLING);  // 附加外部中断3的回调函数

  Serial.begin(9600);     // 打开串口通讯
}

void loop() {
  int num = count2 * 10 + count3;   // 获得按键次数组成的十进制数
  int bin = dec2bin(num);           // 转换为二进制数

  digitalWrite(ledPin1, (bin >> 0) & 0x01);   // 控制LED1
  digitalWrite(ledPin2, (bin >> 1) & 0x01);   // 控制LED2
  digitalWrite(ledPin3, (bin >> 2) & 0x01);   // 控制LED3
  digitalWrite(ledPin4, (bin >> 3) & 0x01);   // 控制LED4
  digitalWrite(ledPin5, (bin >> 4) & 0x01);   // 控制LED5

  Serial.println(bin, BIN);   // 打印二进制数
}

void button2ISR() {
  count2++;       // 按键次数加1
  Serial.println(count2);   // 打印按键次数
}

void button3ISR() {
  count3++;       // 按键次数加1
  Serial.println(count3);   // 打印按键次数
}

int dec2bin(int num) {
  int bin = 0;
  int base = 1;
  while (num > 0) {
    bin += (num % 2) * base;
    num /= 2;
    base *= 10;
  }
  return bin;
}
``
如何进行外部中断与串口通行实验给出C语言代码目的:掌握 ARDUINO 的外部中断引脚有哪些串行通行的接口是哪几个引脚 这在硬件层面上的应用很重要。掌握外部中断的触发与回调函数串口通行的启动等。内容:①连接 1 个按键至外部中断引脚 2 上ARDUINO 记录按键次数采用中断方式非查询方式并通过串口打印按键次数;②连接 2 个按键至外部中断引脚 23 上同时自己选取其它的 5 个端口接 5 个 L

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

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