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

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

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

问题

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

#include "iom324pb.h"
#include <ioavr.h>
#include <intrinsics.h>

void set_output(int pin)
{
  DDRC |= (1 << pin);
}

void set_pin(int pin)
{    
    PORTC |= (1 << pin);  
}

void turn_off(int pin)
{ 
  PORTC &= ~(1 << pin);
}

int main(void)
{     
 set_output(7);
 
 while (1)
 {
   set_pin(7);
  
   turn_off(7);
 }
}

我已经在互联网上搜索过,但我找到的代码对我来说过于复杂。我还尝试使用__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:


include &quot;iom324pb.h&quot;
#include &lt;ioavr.h&gt;

#include &lt;intrinsics.h&gt;

void set_output(int pin)
{
  DDRC |=(1&lt;&lt; pin);
}

void set_pin(int pin)
{    
    PORTC |=(1 &lt;&lt; pin);  
}

void turn_off(int pin)
{ 
  PORTC &amp;= ~(1 &lt;&lt; pin);
}

int main(void)
{     
 set_output(7);
 
 while (1)
 {
   set_pin(7);
  
   turn_off(7);
 }
  
}

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:

确定