文档库

最新最全的文档下载
当前位置:文档库 > 单片机

单片机

#include

#include

/*******预编译******/

#define uchar unsigned char

#define uint unsigned int

#define ulong unsigned long

/*******全局变量*******/

uchar Flag=0; //捕获次数定义

uchar ReadFlag=0; //发送数据标志

ulong rpm=0; //转速

uchar i;

uint CNT1=0; //第一次捕获值

uint CNT2=0; //第二此捕获值

uint CNT=0; //捕获差值

uchar ZHSH=0x00,ZHSL=0x00;

struct UARTSJ

{

uchar tou0,tou1,CDH,ZHSH,ZHSL,temp3,temp4,Crc;

};

struct UARTSJ TXout; //发送的数据帧

void port_init(void)

{

PORTA = 0x00;

DDRA = 0x00;

PORTB = 0x00;

DDRB = 0x00;

PORTC = 0x00; //m103 output only

DDRC = 0x00;

PORTD = 0x00;

DDRD = 0x0E;

}

//Watchdog initialize

// prescale: 256K

void watchdog_init(void)

{

WDR(); //this prevents a timout on enabling

WDTCR = 0x0C; //WATCHDOG ENABLED - dont forget to issue WDRs }

//TIMER1 initialize - prescale:1

// WGM: 0) Normal, TOP=0xFFFF

// desired value: 1uSec

// actual value: 0.995uSec (0.5%)

void timer1_init(void)

{

TCCR1B = 0x00; //停止

TCNT1H = 0x00;

TCNT1L = 0x00;

ICR1H = 0x00;

ICR1L = 0x00;

TCCR1A = 0x00;

TCCR1B = 0xC1; //start Timer

}

#pragma interrupt_handler timer1_capt_isr:6

void timer1_capt_isr(void)

{

//timer 1 input capture event, read (int)value in ICR1 using;

// value=ICR1L; //Read low byte first (important)

// value|=(int)ICR1H << 8; //Read high byte and shift into top byte while(TIFR&0x20) //捕获检测

{

TIFR|=0x20; //清除捕获标志

CNT2=(ICR1H<<8)+ICR1L; //CNT2存放当前捕获值if(CNT2>CNT1)

CNT=CNT2-CNT1; //CNT存放两次时间差else

CNT=0xffff-CNT2+CNT1;

CNT1=CNT2; //CNT1存放上次捕获值rpm=(ulong)120E6/(ulong)CNT;

Flag++; //检测到第一次捕获

}

if(Flag==2) //检测到第二此捕获

{

Flag=0;

i=(uchar)rpm; //清除捕获检测标志

ZHSH=i&0xff00;

ZHSL=i&0x00ff; //数据处理

ReadFlag=1; //标志传输有效

CNT=0;CNT1=0;CNT2=0;

} //清除捕获值及捕获差值

}

#pragma interrupt_handler timer1_compa_isr:7

void timer1_compa_isr(void)

{

//compare occured TCNT1=OCR1A

}

//UART0 initialize

// desired baud rate: 4800

// actual: baud rate:4800 (0.0%)

// char size: 8 bit

// parity: Disabled

void uart0_init(void)

{

UCSRB = 0x00; //disable while setting baud rate

UCSRA = 0x00;

UCSRC = BIT(URSEL) | 0x06;

UBRRL = 0x8F; //set baud rate lo

UBRRH = 0x00; //set baud rate hi

UCSRB = 0xB8;

}

#pragma interrupt_handler uart0_rx_isr:12

void uart0_rx_isr(void)

{

//uart has received a character in UDR

}

#pragma interrupt_handler uart0_udre_isr:13

void uart0_udre_isr(void)

{

//character transferred to shift register so UDR is now empty }

//call this routine to initialize all peripherals

void init_devices(void)

{

//stop errant interrupts until set up

CLI(); //disable all interrupts

port_init();

watchdog_init();

timer1_init();

uart0_init();

MCUCR = 0x00;

GICR = 0x00;

TIMSK = 0x20; //timer interrupt sources

SEI(); //re-enable interrupts

//all peripherals are now initialized

}

//

void main(void)

{

init_devices();

while(1)

;

//insert your functional code here...

}

//转速=1E6微秒/秒×1脉冲/时间间隔(微秒表示)×2圈/脉冲(看有几个汽缸)×60秒/分钟