如何让我的 LED 亮一秒,然后熄灭一秒?

huangapple go评论84阅读模式
英文:

How can I make my led turn on for 1 second then turn off for 1 second?

问题

我正在学习嵌入式系统,我有一个简单的任务,要点亮一个LED灯,但我还想要实现一个定时器,让LED点亮一秒,然后熄灭一秒(依此类推),但我不确定如何做到这一点。我正在使用IAR Embedded Workbench开发ATmega324PB微控制器。以下是我的代码:

  1. #include "iom324pb.h"
  2. #include <ioavr.h>
  3. #include <intrinsics.h>
  4. void set_output(int pin)
  5. {
  6. DDRC |= (1 << pin);
  7. }
  8. void set_pin(int pin)
  9. {
  10. PORTC |= (1 << pin);
  11. }
  12. void turn_off(int pin)
  13. {
  14. PORTC &= ~(1 << pin);
  15. }
  16. int main(void)
  17. {
  18. set_output(7);
  19. while (1)
  20. {
  21. set_pin(7);
  22. turn_off(7);
  23. }
  24. }

我已经在互联网上搜索过,但我找到的代码对我来说过于复杂。我还尝试使用__delay_cycles(1000);函数,但它没有任何效果。

英文:

I am learning embedded and I had the simple task of lighting up a led, but also i want to implement a timer that turns the led on for a second and then turns it off for another seconds(and so on), but i am not sure how to do it. I am working on a ATmega324PB microcontroller using the IAR Embedded Workbench. Here is my code:

  1. include &quot;iom324pb.h&quot;
  2. #include &lt;ioavr.h&gt;
  3. #include &lt;intrinsics.h&gt;
  4. void set_output(int pin)
  5. {
  6. DDRC |=(1&lt;&lt; pin);
  7. }
  8. void set_pin(int pin)
  9. {
  10. PORTC |=(1 &lt;&lt; pin);
  11. }
  12. void turn_off(int pin)
  13. {
  14. PORTC &amp;= ~(1 &lt;&lt; pin);
  15. }
  16. int main(void)
  17. {
  18. set_output(7);
  19. while (1)
  20. {
  21. set_pin(7);
  22. turn_off(7);
  23. }
  24. }

I have searched on the internet but the codes I've found were far too complex for my understanding.I've also tried using the __delay_cycles(1000); function but it doesn't do anything.

答案1

得分: 2

ATmega324PB内置了一个8MHz的RC振荡器,但是代码中没有明确的MCU外设的初始过程。因此,假设ATmega324PB默认以8MHz主时钟运行,那么__delay_cycles(1000);将等待大约125微秒甚至更多。相反,__delay_cycles(8000000);或者一个有限的循环,例如for(i=2000000;i>0;i--);,可能会起作用。

建议:尝试使用内部定时器来实现延迟功能。应用笔记AVR130:使用tinyAVR和megaAVR设备上的定时器可能是一个可行的参考。

英文:

ATmega324PB has an internal 8MHz RC oscillator, while the code has no explicit initial process for the peripheral of MCU. Then, assuming ATmega324PB runs with a main clock of 8MHz by default, so a __delay_cycles(1000); would wait for about 125uS and some more. Instead, __delay_cycles(8000000); or a finite-loop, e.g. for(i=2000000;i&gt;0;i--);, might work.

Suggestion: Try to use its internal Timer to implement the functionality of delay. The application note AVR130: Using the timers on tinyAVR and megaAVR devices would be a viable reference.

huangapple
  • 本文由 发表于 2023年2月16日 18:01:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定