KEY-DEMO2.ino 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. *******************************************************************************
  3. * Copyright (c) 2022 by M5Stack
  4. * Equipped with M5Core sample source code
  5. * 配套 M5Core 示例源代码
  6. * Visit for more information: https://docs.m5stack.com/en/unit/key
  7. * 获取更多资料请访问: https://docs.m5stack.com/zh_CN/unit/key
  8. *
  9. * Describe: KEY. 按键.
  10. * Date: 2022/6/1
  11. *******************************************************************************
  12. Please follow the steps below to add FastLED library:
  13. - Arduino menu --> Manage Libraries... --> FastLED --> install
  14. 在烧录前请按以下步骤添加 FastLED 库:
  15. - Arduino menu --> Manage Libraries... --> FastLED --> install
  16. */
  17. #include <FastLED.h>
  18. #include <M5Stack.h>
  19. uint8_t ledColor = 0;
  20. #define KEY_PIN 22 // Define Key Pin. 定义Key引脚
  21. #define DATA_PIN 21 // Define LED pin. 定义LED引脚.
  22. CRGB leds[1]; // Define the array of leds. 定义LED阵列.
  23. void LED(void *parameter);
  24. void changeLedColor();
  25. void setup() {
  26. M5.begin(); // Init M5Stack 初始化M5Stack
  27. M5.Lcd.setTextSize(3);
  28. M5.Lcd.print(("\n UNIT-KEY Example\n\n Key State:"));
  29. pinMode(KEY_PIN, INPUT_PULLUP); // Init Key pin. 初始化Key引脚.
  30. FastLED.addLeds<SK6812, DATA_PIN, GRB>(leds,
  31. 1); // Init FastLED. 初始化FastLED.
  32. xTaskCreate(
  33. LED, "led", 1000, NULL, 0,
  34. NULL); // Create a thread for breathing LED. 创建一个线程用于LED呼吸灯.
  35. }
  36. void loop() {
  37. if (!digitalRead(KEY_PIN)) { // If Key was pressed. 如果按键按下.
  38. M5.Lcd.setCursor(75, 130);
  39. M5.Lcd.print(("Pressed "));
  40. changeLedColor(); // Change LED color. 更换LED呼吸灯颜色.
  41. while (!digitalRead(
  42. KEY_PIN)) // Hold until the key released. 在松开按键前保持状态.
  43. ;
  44. } else {
  45. M5.Lcd.setCursor(75, 130);
  46. M5.Lcd.println(("Released"));
  47. }
  48. delay(100);
  49. }
  50. void LED(void *parameter) {
  51. leds[0] = CRGB::Red;
  52. for (;;) {
  53. for (int i = 0; i < 255;
  54. i++) { // Set LED brightness from 0 to 255. 设置LED亮度从0到255.
  55. FastLED.setBrightness(i);
  56. FastLED.show();
  57. delay(5);
  58. }
  59. for (int i = 255; i > 0;
  60. i--) { // Set LED brightness from 255 to 0. 设置LED亮度从255到0.
  61. FastLED.setBrightness(i);
  62. FastLED.show();
  63. delay(5);
  64. }
  65. }
  66. vTaskDelete(NULL);
  67. }
  68. void changeLedColor() {
  69. ledColor++;
  70. if (ledColor > 2) ledColor = 0;
  71. switch (
  72. ledColor) { // Change LED colors between R,G,B. 在红绿蓝中切换LED颜色.
  73. case 0:
  74. leds[0] = CRGB::Red;
  75. break;
  76. case 1:
  77. leds[0] = CRGB::Green;
  78. break;
  79. case 2:
  80. leds[0] = CRGB::Blue;
  81. break;
  82. default:
  83. break;
  84. }
  85. }