【R78/G15 开发板测评】按键测试、计数器设计

【R78/G15 开发板测评】按键测试、计数器设计

这里提供了一个按键计数器的实现项目,扫描按键,当监测到按键被按下时,计数器自加1,同时LED点亮,直到监测到按键松开,进入下一个循环。

原理

当按键被按下的瞬间,电平不稳定,这种不稳定会导致单片机多次检测到低电平,并触发多次控制,因此采用延时消抖的解决方案。

延时消抖

shake

硬件和开发环境准备

1.下载和安装 Arduino IDE 软件;

2.在 文件 - 首选项 - 附加开发板管理URLs 添加如下链接

https://raw.githubusercontent.com/renesas/Arduino/master/hardware/package_index_rl78g15_fpb_p20_bundled.json

参考:renesas/Arduino Wiki .

3.在开发板管理器中搜索并安装 RL78/G15 开发板程序包;

4.连接开发板,菜单栏 工具 选项,设置目标开发板型号和硬件端口号。
详见:【R78/G15 开发板测评】简介、环境搭建、工程测试 .

代码

程序流程图

flow

根据原理图可知,用户自定义按键连接 MCU 的 P137 引脚,对应 Arduino 的 2 号引脚,两个板载 LED 分别对应 47 引脚,于是编译代码如下

/*
Name: Key switch module
Time: 2023-12-27
Author: Jin-Lei Li
Email: lijinlei0907@163.com
Version: 1.0
Function: Send key IO level by serial port. 
Line Connection: Out -> 2
*/
int SwitchPin = 2; // define IO
int SwitchValue = HIGH; // define IO value
int count = 0;
int LED_down = 4; // switch down
int LED_up = 7; // switch up

void setup() {
  // put your setup code here, to run once:
  pinMode(SwitchPin, INPUT); // define IO mode
  pinMode(LED_up, OUTPUT);
  pinMode(LED_down, OUTPUT);
  Serial.begin(9600); // define baud
}

void loop() {
  // put your main code here, to run repeatedly:
  KeyScan();
  delay(100);
}

void KeyScan()
{
  SwitchValue = digitalRead(SwitchPin); // read KeySwitch digital value
  if(SwitchValue == LOW) // button was down
  {
    delay(20); // eliminate the jitter
    if(SwitchValue == LOW) // Judge again
    {
      //Serial.print("Value of the key switch: ");//Send text
      //Serial.println(SwitchValue);// Send value
      count++;
      Serial.println(count);
      digitalWrite(LED_up, HIGH);
      digitalWrite(LED_down, LOW);
      while (SwitchValue == HIGH);
    }
  }
  else // button was up (without press)
  {
    //Serial.print("Value of the key switch: ");//Send text
    //Serial.println(SwitchValue);
    digitalWrite(LED_up, LOW);
    digitalWrite(LED_down, HIGH);
  }
}

上传成功提示

burn_done

效果展示

count

串口打印效果

println

按键计数及LED闪烁效果

【R78/G15 开发板测评】按键测试、计数器设计

可见在按键按下时,计数器 count 加 1,两个LED的亮灭状态切换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值