LEDWidget.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. *
  3. * Copyright (c) 2021 Project CHIP Authors
  4. * Copyright (c) 2019 Google LLC.
  5. * All rights reserved.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. #include "LEDWidget.h"
  20. #include "cybsp.h"
  21. #include "cyhal.h"
  22. #include <platform/CHIPDeviceLayer.h>
  23. void LEDWidget::Init(int ledNum)
  24. {
  25. mLastChangeTimeUS = 0;
  26. mBlinkOnTimeMS = 0;
  27. mBlinkOffTimeMS = 0;
  28. mLedNum = ledNum;
  29. mState = CYBSP_LED_STATE_OFF;
  30. cyhal_gpio_init((cyhal_gpio_t) ledNum, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_STRONG, CYBSP_LED_STATE_OFF);
  31. }
  32. void LEDWidget::Invert(void)
  33. {
  34. Set(!mState);
  35. }
  36. void LEDWidget::Set(bool state)
  37. {
  38. mLastChangeTimeUS = mBlinkOnTimeMS = mBlinkOffTimeMS = 0;
  39. DoSet(state);
  40. }
  41. void LEDWidget::Blink(uint32_t changeRateMS)
  42. {
  43. Blink(changeRateMS, changeRateMS);
  44. }
  45. void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS)
  46. {
  47. mBlinkOnTimeMS = onTimeMS;
  48. mBlinkOffTimeMS = offTimeMS;
  49. Animate();
  50. }
  51. void LEDWidget::Animate()
  52. {
  53. if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
  54. {
  55. int64_t nowUS = ::chip::System::Clock::GetMonotonicMicroseconds();
  56. int64_t stateDurUS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS) * 1000LL;
  57. int64_t nextChangeTimeUS = mLastChangeTimeUS + stateDurUS;
  58. if (nowUS > nextChangeTimeUS)
  59. {
  60. DoSet(!mState);
  61. mLastChangeTimeUS = nowUS;
  62. }
  63. }
  64. }
  65. void LEDWidget::DoSet(bool state)
  66. {
  67. if (mState != state)
  68. {
  69. cyhal_gpio_write((cyhal_gpio_t) mLedNum, ((state) ? CYBSP_LED_STATE_ON : CYBSP_LED_STATE_OFF));
  70. }
  71. mState = state;
  72. }