|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2008-12-6 09:55:51
|
显示全部楼层
附上代码(用ICC生成的GCC代码):
//ICC-AVR application builder : 2008-12-05 10:45:44
// Target : M8
// Crystal: 8Mhz
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define in_485 PORTC&=~_BV(PC5)
#define out_485 PORTC|=_BV(PC5)
#define led_on PORTD&=~_BV(PD5)
#define led_off PORTD|=_BV(PD5)
volatile char start_recv=0,tc=0,sc=0;
void sonic_send(void)
{
unsigned char pulsecnt;
cli();
PORTB|= (1<<PB3);
TCNT2 = 0x9C; //setup
OCR2 = 0x64;
TCCR2 = 0x19; //start
for (pulsecnt=0;pulsecnt<4;pulsecnt++)
{
while (PINB&(1<<PB3)); //1
while (!(PINB&(1<<PB3))); //0
}
TCCR2 = 0x00; //stop
PORTB|= (1<<PB3);
start_recv=1;
sc=0;
tc=0;
TIMSK|=_BV(TICIE1);
sei();
}
void port_init(void)
{
PORTB = 0xFF;
DDRB = _BV(DDB3);
PORTC = ~_BV(PC5); //m103 output only
DDRC = _BV(DDC5);
PORTD = 0xFF;
DDRD = _BV(DDD1)|_BV(DDD5);
}
//TIMER1 initialize - prescale:1
// WGM: 0) Normal, TOP=0xFFFF
// desired value: 1KHz
// actual value: 1.000KHz (0.0%)
void timer1_init(void)
{
TCCR1B = 0x00; //stop
TCNT1H = 0xE0; //setup
TCNT1L = 0xC0;
OCR1AH = 0x1F;
OCR1AL = 0x40;
OCR1BH = 0x1F;
OCR1BL = 0x40;
ICR1H = 0x1F;
ICR1L = 0x40;
TCCR1A = 0x00;
TCCR1B = 0x01; //start Timer
}
SIGNAL(SIG_INPUT_CAPTURE1)
{
//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
volatile unsigned int sd=ICR1L;
sd|=(unsigned int)(ICR1H<<8);
sc++;
if(tc>40)
{
TIMSK&=~_BV(TICIE1);
start_recv=0;
if(sc<=4)led_on;
out_485;
UDR=(unsigned char)(sc>>8);
while(!(UCSRA&(1<<UDRE)));
_delay_ms(1);
out_485;
UDR=(unsigned char)(sc&0x00FF);
sc=0;
tc=0;
}
}
SIGNAL(SIG_OVERFLOW1)
{
//TIMER1 has overflowed
if(start_recv)tc++; //接收开始后tc累加,当tc=122时,经过了1秒
}
//TIMER2 initialize - prescale:1
// WGM: CTC
// desired value: 80KHz
// actual value: 79.208KHz (1.0%)
void timer2_init(void)
{
TCCR2 = 0x00; //stop
ASSR = 0x00; //set async mode
TCNT2 = 0x9C; //setup
OCR2 = 0x64;
TCCR2 = 0x00; //stop
}
//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
void uart0_init(void)
{
UCSRB = 0x00; //disable while setting baud rate
UCSRA = 0x00;
UCSRC = (1<<URSEL) | 0x06;
UBRRL = 0x33; //set baud rate lo
UBRRH = 0x00; //set baud rate hi
UCSRB = 0xD8;
}
SIGNAL(SIG_UART_RECV)
{
//uart has received a character in UDR
volatile unsigned char c = UDR;
}
SIGNAL(SIG_UART_TRANS)
{
//character has been transmitted
in_485;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
cli(); //disable all interrupts
port_init();
timer1_init();
timer2_init();
uart0_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x24; //timer interrupt sources
sei(); //re-enable interrupts
//all peripherals are now initialized
}
int main(void)
{
init_devices();
while(1)
{
sonic_send();
while((start_recv==1)&&(tc<50));
TIMSK&=~_BV(TICIE1);
start_recv=0;
_delay_ms(1000);
led_off;
}
} |
|