Trích:
Nguyên văn bởi fidel
Đây là code của mình, SRF05/mode1/Atmega128.
#define F_CPU 14745600UL
#define STOP_CLK 0x08 // Stop clock
#define START_CLK 0x0A // Start clock with 1:8 prescaler CTC mode
#define START_CLK_N 0x02 // Start clock running 1:8 prescaler in normal mode
#include <avr/io.h>
#include <string.h>
#include <stdio.h>
#include <util/delay.h>
#include <stdint.h>
#include "knihovnaLCD.c"
float s;
char buffer [50];
void setup(void)
{
DDRA = 0x00; // Port A asIN
DDRC = 0xFF; // Port C as OUT
TCCR1A = 0x00; // Set timer up in CTC mode
TCCR1B = 0x08;
TWBR = 0x20; // 100MHz I2C clock frequency
}
void waitForTimer(void)
{
while(!(TIFR&0x10)); // wait for timer to set compare match flag
TCCR1B = STOP_CLK; // Stop the timer
}
void startTimer(unsigned int time)
{
OCR1A = time; // Time set to count to
TIFR = 0x10; // Clear timer campare match flag
TCNT1 = 0x00; // Clear timer to zero
TCCR1B = START_CLK; // Start timer running 1:8 prescaler
}
unsigned int getEcho(void)
{
unsigned int range;
TCNT1 = 0x00; // Clear timer to zero
TCCR1B = START_CLK_N;
while(bit_is_clear(PINA,0) && TCNT1 < 0xC350) // Wait for echo pin to go high, this indicates the start of the incoming pulse
{
}
if (TCNT1 > 0xC300) //Time over
{
TCCR1B = STOP_CLK;
return(999);
}
TCCR1B = STOP_CLK;
TCNT1 = 0x00; // Clear timer to zero
TCCR1B = START_CLK_N; // Start timer running 1:8 prescaler in normal mode
while(bit_is_set(PINA,0)); // Echo pin goes high
{ // Just wait
}
TCCR1B = STOP_CLK; // Echo pin has just fallen down. Stop the timer
range = TCNT1/107; // Read back value in the timer counter register
return(range);
}
int main(void)
{
setup();
startTimer(0xFFFF);
waitForTimer();
LCD_Init();
LCD_Clear();
while (1)
{
PORTC=255;
_delay_us(10);
PORTC=0;
s = getEcho();
sprintf (buffer, "s =%u ", (int)s);
LCD_Position(1 , 1);
LCD_WriteString(buffer);
_delay_ms(100);
};
}
|
Không biết Topic này có chuyển sang Forum nào không mà không thấy tiếp tục? Bạn có thể cho mình địa chỉ mail để liên lạc hỏi về vấn đề này nhé? Mình đang quan tâm! Thanks!