⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.c

📁 一个关于AVR单片机的例程
💻 C
字号:
//ICC-AVR application builder : 2007-6-9 0:33:58
// Target : M16
// Crystal: 1.0000Mhz
// 用途:演示定时器的工作原理
// 作者:古欣
// AVR与虚拟仪器 http://www.avrvi.com
#include <iom16v.h>
#include <macros.h>

void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0x03; //PA0 PA1 输出
 PORTB = 0x00;
 DDRB  = 0xFF; //PB 输出
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x00;
}

//TIMER0 initialize - prescale:8
// WGM: Normal
// desired value: 1KHz
// actual value:  1.000KHz (0.0%)
void timer0_init(void)
{
 TCCR0 = 0x00; //stop
 TCNT0 = 0x83; //set count
 OCR0  = 0x7D;  //set compare
 TCCR0 = 0x02; //start timer
}

//比较匹配中断
#pragma interrupt_handler timer0_comp_isr:20
void timer0_comp_isr(void)
{
 //compare occured TCNT0=OCR0
 if(OCR0==0x7D) //调整0x7D
 {
  OCR0=0x7F;
 }
 else
 {
  OCR0=0x7D;
 }
  PORTA ^= 0x01; //PA0取反
}

//溢出中断中断
#pragma interrupt_handler timer0_ovf_isr:10
void timer0_ovf_isr(void)
{
 TCNT0 = 0x83; //reload counter value
 PORTA ^= 0x01; //PA0取反
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 port_init();
 timer0_init();

 MCUCR = 0x00;
 GICR  = 0x00;
 TIMSK = 0x03; //timer interrupt sources 允许定时器零匹配和溢出中断
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}

void main(void)
{
 init_devices();
 PORTA=0x00;
 while(1)
 {
  PORTB = TCNT0; //任何时候都可以读TCNT0
 }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -