Sei sulla pagina 1di 21

// Since AVR processors deal naturally with 8 bits at a time, I/O pins

// are grouped into sets of 8 to form I/O ports. Three registers


// are assigned to each I/O port to control the function and state of
// that port's pins. The registers are 8-bits wide, and each bit (#0-7)
// determines the operation of the corresponding number pin (pin 0-7).
// The three registers are:
// DDRx - this register determines the direction (input/output) of the pins on port[x]
//
A '0' bit in the DDR makes that port pin act as input
//
A '1' bit in the DDR makes that port pin act as output
// PORTx - this register contains the output state of the pins on port[x]
//
A '0' bit makes the port pin output a LOW (~0V)
//
A '1' bit makes the port pin output a HIGH (~5V)
// PINx - this register contains the input state of the pins on port[x]
//
A '0' bit indicates that the port pin is LOW (at ~0V)
//
A '1' bit indicates that the port pin is HIGH (at ~5V)
// The x should be replaced with A,B,C,D,E,F, or G depending on the
// desired port. Note that not all AVR processors have the same set
// or number of ports. Consult the datasheet for your specific processor
// to find out which ports it has.
// in the AVR-GCC C language, ports can be accessed using two kinds of
// commands:
// inb() and outb()
in-byte and out-byte
// cbi() and sbi()
clear-bit and set-bit
// inb() and outb() should be used when you intend to read or write
// several bits of a register at once. Here are some examples:
outb(DDRA, 0x00);
a = inb(PINA);

// set all port A pins to input


// read the input state of all pins on port A

outb(DDRB, 0xFF);
outb(PORTB, 0xF0);

// set all port B pins to output


// set PB4-7 to HIGH and PB0-3 to LOW

// Often you may wish to change only a single bit in the registers
// while leaving the rest unaltered. For this, use cbi() and sbi().
// For example:
sbi(DDRC, 0);
sbi(DDRC, 1);

// sets PC0 to be an output


// sets PC1 to be an output

cbi(PORTC, 1);

// sets PC1 to output a LOW without altering any other pin

// the lines below will cause PC0 to pulse twice,


// but will leave all other port C pins unchanged
cbi(PORTC, 0);
// sets PC0 to output a LOW
sbi(PORTC, 0);
// sets PC0 to output a HIGH
cbi(PORTC, 0);
// sets PC0 to output a LOW
sbi(PORTC, 0);
// sets PC0 to output a HIGH
cbi(PORTC, 0);
// sets PC0 to output a LOW

return 0;
}

--------------------------------MAKE THE PIN GO HIGH-----------------#include <avr/io.h>


#include <wdt.h> //included so we can call the function wdt_disable();
int main(void)
{
wdt_disable();

//All C programs need a function called main - when run, this is called first
//call this function to stop the watch-dog timer firing

outp(0xFF, DDRB);

//set all of PORTB to output by writing 0xFF (11111111) to the DDRB register

while (1) //loop forever


{
PORTB = 0x33; // 00110011
PORTB |=(1<<2);// make the physical third pin on port B go high (known as pin 2)
}
}

------------------MAKE

THE PIN GO LOW-------------------------------------------------

#include <avr/io.h>
//included so we can use the text label for ports, pins etc.
#include <wdt.h> //included so we can call the function wdt_disable();
int main(void)
{
wdt_disable();

//All C programs need a function called main - when run, this is called before anythign else
//call this function to stop the watch-dog timer firing

outp(0xFF, DDRD);

//set all PORTD pins to output by writing 0xFF (11111111) to the DDRB register

PORTD = 0xFF;
//make all pins high (PORTD = 11111111)
PORTD &= ~(1 << 5);//make the sixth pin go low. See website for explanation
}

/*********************************************

Project : led_on
Comments: This program lights up the LED attached to pin0 or PORTC
*********************************************/
#include <mega32.h>
void main(void)
{
PORTC=0xFF; //Set all pins of PORTC to output (p.87 in textbook)
DDRC=0xFF; //Set initial values for PORTC to high
while (1)
{
PORTC = 254; //pin0, PORTC = 0 (LED ON), pin1-7=1 (LEDs OFF)
};

}
/*********************************************
Project : dip_led
Comments: This program reads an eight bit digital word from PORTA, and writes
the digital word out to PORTC.
*********************************************/

#include <mega32.h>
void main(void)
{
PORTA=0x00; // Set all pins of PORTA to input
DDRA=0x00; // Set initial values for PORTA to low
PORTC=0xFF; //Set all pins of PORTC to output
DDRC=0xFF; //Set initial values for PORTC to high
while (1)
{
PORTC = PINA; //Input from PORTA is output to PORTC
};}

/*********************************************
Project : led_count
Comments: This program counts from 0 to 255
in binary with LEDs. There is a
two second pause between each count.
*********************************************/
#include <mega32.h>
unsigned int timecount = 0; // Global timer counter
unsigned int counter = 255; // Global counter set
// When Timer 0 overflows, conduct this routine
interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
TCNT0 = 110; // 146 clock cycles equals 0.025 seconds.
Setting
// the clock counter to 110 allows 146 clock cycles
// (256-146=110)
if (++timecount == 80) // 80 250us ticks in two seconds
{
PORTC = --counter; // Subtract one from counter and send it to
// PORTC every two seconds
// Note: high is off and low is on for each LED
timecount = 0; // Reset time counter
}
}
void main(void)
{
PORTC=0xFF; // Set all eight bits of PORTC to output
DDRC=0xFF; // Set all eight bits of PORTC High
TCCR0=0x05; // Clock value: 5.859 kHz (6MHz / 1024)
TCNT0=110; // Timer/Counter 0 initialization
TIMSK=0x01; // Timer Interrupt initialization
#asm("sei") // Global enable interrupts
while (1)
; // Do Nothing

Timer
All of the AVR MCUs have hardware support for measuring time. The Mega32 has three hardware timers, two 8-bit
(timer0 and timer2) and one 16-bit timer (timer1). Each timer has a prescalar that divides the cpu clock by 1, 8, 64,
256, 1024. At each prescaled clock tick the timer counter register is automatically incremented by one. In addition,
each timer can be stopped. Each timer can be used is several different ways. A short list follows for each timer.

Timer0 and timer2


* Clock Sources
o Timer0 can use a prescalar or increment based on input from an i/o pin.
o Timer2 can use a prescalar or increment based on a separate crystal.
* Count to overflow.
o Count to 255, then roll over to zero and keep counting.
o Overflow may trigger an interrupt if enabled.
* Count to a preset value specified in the Output Compare Register (OCR0 or OCR2).
o Reaching the preset value can trigger an interrupt if enabled.
o Reaching the preset value can cause the timer to be reset. Counting to a preset value, folllowed by reset
(and automatic continued counting) is the best way to generate a precision time base.
o Reaching the preset value can cause an output pin to be set, cleared, or toggled. This feature can be used to
generate a square wave of aribtrary frequency with no software overhead.
* Pulse-width modulator (PWM) mode.
o A PWM signal is output to a pin based on a preset value which can be changed on every PWM cycle.
o An interrupt can be generated on every PWM cycle if enabled.
Timer1
* Clock Sources
o Timer1 can use a prescalar or increment based on input from an i/o pin.
* Count to overflow.
o Count to 216-1, then roll over to zero and keep counting.
o Overflow may trigger an interrupt if enabled.
* Count to two preset values specified in Output Compare Register 1A or 1B (OCR1A, OCR1B).
o Reaching either preset value can trigger interrupts if enabled.
o Reaching the preset value in OCR1A can cause the timer to be reset. Counting to a preset value, folllowed
by reset (and automatic continued counting) is the best way to generate a precision time base.
o Reaching the preset value in OCR1A or OCR1B can cause an output pin to be set, cleared, or toggled. This
feature can be used to generate square waves of aribtrary frequencies with no software overhead.
* Pulse-width modulator (PWM) mode.
o A PWM signal is output to a pin based on a preset value which can be changed on every PWM cycle.
o An interrupt can be generated on every PWM cycle if enabled.
* Copy the value in the timer counter (current time) into an input capture register (ICR1) when an external event
occurs.
o The event can be a logic transition on one i/o pin.
o The event can be a change in state of a built-in analog comparator. This allows the cpu to determine when an
analog voltage equals an arbitrary reference voltage.
o This feature allows the cpu to determine the exact time of an external event.
Using Timers
# Timing a short interval.
For timing very short intervals, you can get good resolution (1 cycle) by simply clearing the timer, starting it,
then stopping and reading it. This is particularly useful for profiling execution time of code. It could also be
useful for generating small delays by using a null-bodied while loop to test for the count value.

TCCR1B = 1 ;
TCNT1 = 0;
//C code to be profiled
TCCR1B = 0;
printf(" cycles=%d\n\r",TCNT1) ;
//used as an example in the program organization doc.
#include <Mega32.h>
//timeout values for each task
#define t1 250
#define t2 125
#define t3 60
#define begin {

#define end }
//the three task subroutines
void task1(void); //blink at 2 or 8 Hz
void task2(void); //blink at 1 Hz
void task3(void); //detect button and modify task 1 rate
void initialize(void); //all the usual mcu stuff
unsigned char time1, time2, time3; //timeout counters
unsigned char tsk2c;
//task 2 counter to get to 1/2 second
unsigned char tsk3m;
//task 3 message to task 1
unsigned char led;
//light states
//**********************************************************
//timer 0 compare ISR
interrupt [TIM0_COMP] void timer0_compare(void)
begin
//Decrement the three times if they are not already zero
if (time1>0)
--time1;
if (time2>0)
--time2;
if (time3>0)
--time3;
end
//**********************************************************
//Entry point and task scheduler loop
void main(void)
begin
initialize();
//main task scheduler loop
while(1)
begin
if (time1==0) task1();
if (time2==0) task2();
if (time3==0) task3();
end
end
//**********************************************************
//Task subroutines
//Task 1
void task1(void)
begin
time1=t1; //reset the task timer
if (tsk3m != 0) time1 >>= 2; //check for task 3 message
//toggle the zeros bit
led = led ^ 0x01;
PORTB = led;
end
//*******************************
//Task 2
void task2(void)
begin
time2=t2; //reset the task timer
if (--tsk2c == 0) //have we waited 1/2 second?
begin
tsk2c = 4;
//reload the 1/2 sec counter
//toggle the ones bit
led = led ^ 0x02;

PORTB = led;
end
end
//*******************************
//Task 3
void task3(void)
begin
time3=t3; //reset the task timer
tsk3m = ~PIND & 0x01; //generate the message for task 1
end
//**********************************************************
//Set it all up
void initialize(void)
begin
//set up the ports
DDRD=0x00;
// PORT D is an input
DDRB=0xff; // PORT B is an ouput
PORTB=0;
//set up timer 0
TIMSK=2;
//turn on timer 0 cmp match ISR
OCR0 = 250;
//set the compare re to 250 time ticks
//prescalar to 64 and turn on clear-on-match
TCCR0=0b00001011;
//init the LED status (all off)
led=0xff;
//init the task timers
time1=t1;
time2=t2;
time3=t3;
//init the task 2 state variable
//for four ticks
tsk2c=4;
//init the task 3 message
//for no message
tsk3m=0;
//crank up the ISRs
#asm
sei
#endasm
end

3timer-----------------------------------------------------------------//Run all three timers in different modes


// timer 0 -- compare-match timebase
// timer 1 -- input capture from analog comp
// timer 2 -- stand alone square wave gen
// main will schedule task1, and poll the ACO bit
// task 1 will print the periods
// timer0 compare ISR will increment a timer
// timer1 capture ISR will compute a period

// MUST connect port B.3 (AIN1) to port D.7 (OC2)


#include <Mega32.h>
// define a new I/O register for easier programming
sfrw ICR1=0x26;
#include <stdio.h>
//time for task
#define t1 250
#define begin {
#define end }
//the task subroutine
void task1(void); //execute at 2 Hz
void initialize(void); //all the usual mcu stuff
//timeout counter
unsigned char time1;
//capture variables
unsigned int T1capture, lastT1capture, period ;
//polling variables
unsigned int periodPoll, T1poll, lastT1poll ;
//comparator output bit
char ACO, lastACO ;
//**********************************************************
//timer 0 overflow ISR
interrupt [TIM0_COMP] void timer0_compare(void)
begin
//Decrement the time if not already zero
if (time1>0)
--time1;
end
//**********************************************************
// timer 1 capture ISR
interrupt [TIM1_CAPT] void timer1_capture(void)
begin
// read timer1 input capture register
T1capture = ICR1 ;
// compute time between captures
period = T1capture - lastT1capture;
lastT1capture = T1capture ;
end
//**********************************************************
//Entry point and task scheduler loop
void main(void)
begin
initialize();
//main task scheduler loop
while(1)
begin
if (time1==0) task1();
//poll for ACO 0->1 transition (ACSR.5)
// and record Timer1
ACO = ACSR.5 ;
if ((ACO==1) && (lastACO==0))

begin
T1poll = TCNT1 ;
periodPoll = T1poll - lastT1poll ;
lastT1poll = T1poll ;
end
lastACO = ACO ;
end
end
//**********************************************************
//Timed task subroutine
//Task 1
void task1(void)
begin
time1=t1; //reset the task timer
// print capture interval
printf("%d %d\n\r", period, periodPoll);
end
//**********************************************************
//Set it all up
void initialize(void)
begin
//set up timer 0 for 1 mSec timebase
TIMSK=2;
//turn on timer 0 cmp match ISR
OCR0 = 250;
//set the compare re to 250 time ticks
//prescalar to 64 and turn on clear-on-match
TCCR0=0b00001011;
//set up timer1 for full speed and
//capture an edge on analog comparator pin B.3
// Set capture to positive edge, full counting rate
TCCR1B = 0b01000001;
// Turn on interrupt-on-capture
TIMSK = TIMSK | 0b00100000 ;
// Set analog comp to connect to timer capture input
// and turn on the band gap reference on the positive input
ACSR = 0b01000100 ;
// Comp negative input is B.3
DDRB.3 = 0 ;
// set up timer 2 for square wave
// 200 cycle period from OC2
OCR2 = 249 ; //100 cycles/half-period
TCCR2 = 0b00011001 ;
DDRD.7 = 1 ; // PORT D.7 is OC2
//set up UART
UCSRB = 0x18 ;
UBRRL = 103 ;
printf("starting...\n\r") ;
//init the task timer
time1=t1;
//crank up the ISRs
#asm
sei
#endasm

end
----------------------------------------------------------------------------------------------------------------------------------------

PWM
#include <Mega32.h>
#include <delay.h>
#include <math.h> // for sine
//I like these definitions
#define begin {
#define end }
#define countMS 62 //ticks/mSec
unsigned long accumulator @0x2f0;
unsigned char highbyte @0x2f3; //the HIGH byte of the accumulator variable
unsigned long increment;
char sineTable[256] @0x300; //need loc to avoid glitch
unsigned int i, time ;
char amp, count;
interrupt [TIM0_OVF] void sgen(void)
begin
//the DDR code and scaling
accumulator = accumulator + increment ;
OCR0 = 128 + sineTable[highbyte] >> amp ;
//generate rising amplitude
// 62 counts is about 1 mSec
count--;
if (0 == count )
begin
count=countMS;
time++; //in mSec
end
end
void main(void)
begin
DDRB=0xff;
//fast PWM mode, full clock rate, toggle oc0 (pin B3)
//16 microsec per PWM cycle implies max freq for 16 samples of
// 1/(16e-6*16) = 3900 Hz.
//TCCR0 = 0b01101001 ;
//turn on timer 0 overflow ISR
TIMSK = 0b00000001 ;
//init the sine table
for (i=0; i<256; i++)
begin
sineTable[i] = (char)(127.0 * sin(6.283*((float)i)/256.0)) ;
end
//init the DDS phase increment
increment = 0x08ffffff ;
time=0;
TCCR0 = 0b00000001 ;
#asm
sei

#endasm
while(1)
begin
if (time==50)
begin
time=0;
//phase lock the sine gen and timer
accumulator = 0;
TCNT0 = 0;
OCR0 = 0;
//generate the amplitude scaling -- start with divide by 16
amp = 4;
//turn on pwm
TCCR0 = 0b01101001 ;
end //if
if (time==1) amp=3; //ramp up
if (time==2) amp=2;
if (time==3) amp=1;
if (time==4) amp=0;
if (time==10) amp=1; //ramp down
if (time==11) amp=2;
if (time==12) amp=3 ;
if (time==13) amp=4;
if (time==14) TCCR0=0b00000001 ;
end // end while
end //end main

UART
Most of the AVR mcus have a hardware UART. You can use the UART in CodevisionC with the
usual stdio library functions, plus a few designed for this small mcu. You should note that all of
the CodevisionC stdio functions are blocking. This means that any cooperative multitasking
scheme you use will halt if you use stdio functions. A couple of approachs to solving this problem
will be outlined below.
Near the bottom of the page there is code for using the UART in assembler.
If you use the UART to talk to a PC, the UART should be connected to a COM port of the PC. You
should use a simple terminal program, such as Hyperterminal, on the PC. The terminal program
should be set to 9600 baud, no parity, one stop bit, and no flow control. The connection to the PC
for the AVR development board assumes a RS232 cable with straight-through connection. The
STK500 board requires a jumper from port pins D0 and D1 to the RS232-spare header.
//For Mega32:
UCSRB = 0b00011000 ; //hex 0x18
UBRRL = 103 ; //using a 16 MHz crystal (9600 baud)
In addition if you want to enable the receive-complete interrupt you must instead set
USCRB = 0b10011000; //hex 0x98
Bit 7 enables the interrupt, bit 4 enables the receiver, and bit 3 the transmitter.
Printf and scanf are supplied. Floating point conversion support costs you a lot of code space if
you use it. There are also put-string and get-string commands (puts, gets), as well as putsf, which
means put-string-from-flash-memory. The lower-level commands putchar and getchar are also
available. Since there are 32 kbytes of flash memory and only 2 kbytes of RAM, you should always

store constant strings in flash. In the following example, the fragment of code prompts the user
with a string from flash memory, then waits for an 's' from the serial port. All quoted literal strings
used as parameters are automatically stored in flash.
putsf("Press s to stop\r");
sflag = 0;
while(sflag!='s') sflag = getchar() ;
---EXAMPLE---------------------------------------------------------------------------------------#include <90s8515.h>
#include c:\cvavr\inc\stdio.h
#include c:\cvavr\inc\ftoa.h
#include c:\cvavr\inc\atof.h
char instr[10], outstr[10];
float fltin, fltout;
//======================================
float getfloat()
//get chars, print them back, handle backspace,
//add decimal if it is not in input (to fix atof bug)
{
char input_dec;
//flag for existing decimal
char in_str[32];
//The input to be converted to a float
char current_char;
//the last char to be inputted
char in_count;
//the current char number
input_dec=0;
in_count=0;
while ( (current_char=getchar()) != '\r' ) //carriage return
{
putchar(current_char);
if (current_char == 0x08)
//backspace
--in_count;
else
in_str[in_count++]=current_char;
if (current_char == '.') //set decimal flag
input_dec=1;
}
putchar(current_char); //emit carriage return
putchar('\n');
//line feed makes output nicer
if ( input_dec == 0 ) in_str[in_count++]='.'; //add decimal if necessary
in_str[in_count]=0x00;
//null terminate
return atof(in_str);
}
//======================================
void main(void)
{
UCR = 0x10 + 0x08 ;
UBRR = 25 ;
putsf("\r\n pgm start\r\n");
while(1)
{
putsf("Enter a float.\r");
fltin = getfloat();
ftoa(fltin/2,2,outstr);
printf("input/2=%s\r\n\r\n",outstr);
}
}

ADC
// A to D test code
// NOTE -- You MUST MOUNT the Aref jumper
#include <Mega32.h>
#include <stdio.h>
//I like these definitions
#define begin {
#define end }
char Ain ;

//raw A to D number

void main(void)
begin
//init the A to D converter
//channel zero/ left adj /EXTERNAL Aref
//!!!CONNECT Aref jumper!!!!
ADMUX = 0b00100000;
//enable ADC and set prescaler to 1/128*16MHz=125,000
//and clear interupt enable
//and start a conversion
ADCSR = 0b11000111;
//init the UART
UCSRB = 0x18;
UBRRL = 103;
printf("starting...\n\r");
// measure and display loop
while (1)
begin
//get the sample
Ain = ADCH;
//start another conversion
ADCSR.6=1;
//results to hyperterm
printf("%d\n\r",Ain);
end
end
--------------------------------------------------------------------------------------------------------------------------------------------------------------

LCD
/*****************************************************
De: Nhan du lieu tu may tinh va xuat ra LCD
PORTC ket noi voi LCD
[LCD] [AVR Port]
RS (pin4) -----bit 0
RD (pin 5) ------ bit 1
EN (pin 6) ------ bit 2
DB4 (pin 11) --- bit 4
DB5 (pin 12) --- bit 5
DB6 (pin 13) --- bit 6
DB7 (pin 14) --- bit 7

****************************************************************
Project :
Version :
Date : 6/13/2008
Author : F4CG
Company : F4CG
Comments:

Chip type
: ATmega32
Program type
: Application
Clock frequency : 4.000000 MHz
Memory model
: Small
External SRAM size : 0
Data Stack size : 512
*****************************************************/
#include <mega32.h>
// Alphanumeric LCD Module functions
#asm
.equ __lcd_port=0x15 ;PORTC
#endasm
#include <lcd.h>
#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7
#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)
// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];
#if RX_BUFFER_SIZE<256
unsigned char rx_wr_index,rx_rd_index,rx_counter;
#else
unsigned int rx_wr_index,rx_rd_index,rx_counter;
#endif
// This flag is set on USART Receiver buffer overflow
bit rx_buffer_overflow;
// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
{
rx_buffer[rx_wr_index]=data;
if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
if (++rx_counter == RX_BUFFER_SIZE)
{
rx_counter=0;
rx_buffer_overflow=1;
};
};
}
#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer

#define _ALTERNATE_GETCHAR_
#pragma used+
char getchar(void)
{
char data;
while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
#asm("cli")
--rx_counter;
#asm("sei")
return data;
}
#pragma used#endif
// Standard Input/Output functions
#include <stdio.h>
// Declare your global variables here
void main(void)
{
char x,bien_tam;
// Declare your local variables here
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;
// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0x00;
DDRB=0x00;
// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0x00;
// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0x00;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;
// Timer/Counter 1 initialization
// Clock source: System Clock

// Clock value: Timer 1 Stopped


// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;
// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: Off
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0x90;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x19;
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;
// LCD module initialization
lcd_init(16);

// Global enable interrupts


#asm("sei")
bien_tam=0;
x=0;
while (1)
{
while (x==bien_tam)
x=getchar();
bien_tam=x;
//lcd_clear();
lcd_putchar(x);
};
}
*****************************************************

De: thiet mach giao tiep led ma tran voi may tinh
gui ky tu tu may tinh xuat ra led matrix
PORTA dung quyet cot
PORTB dung quet hang
chu y: Tao chi gui so 1 va 2 anh em muon khac thi thay doi o ham number1() hoac number2()
*********************************************************************************

Chip type
: ATmega32
Program type
: Application
Clock frequency : 4.000000 MHz
Memory model
: Small
External SRAM size : 0
Data Stack size : 512
*****************************************************/
#include <mega32.h>
#include <delay.h>
char x=0;
interrupt [USART_RXC] void usart_rx_isr(void)
{
x=UDR;
}
void number1()
{
PORTA=1;
PORTB=253;
delay_us(50);
PORTA=2;
PORTB=0;
delay_us(50);
}
void number2()
{
PORTA=2;
PORTB=191;
delay_us(20);
PORTA=4;
PORTB=153;
delay_us(20);
PORTA=8;
PORTB=174;
delay_us(20);
PORTA=16;
PORTB=182;
delay_us(20);

PORTA=32;
PORTB=185;
delay_us(20);
}
void main(void)
{
PORTA=0x00;
DDRA=0x0ff;
PORTB=0x00;
DDRB=0x0ff;
PORTC=0x00;
DDRC=0x00;
PORTD=0x00;
DDRD=0x00;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;
// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;
// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;

MCUCSR=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: Off
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0x90;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x19;
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;
// Global enable interrupts
#asm("sei")
while (1)
{
if (x=='1')
number1();
else if (x=='2')
number2();
else {
PORTA=0;
PORTB=0;
}
};
}

/*****************************************************

De: chuyen doi ADC va xuat ra LCD


Giai: PortC ket noi voi LCD
bien tro noi voi PORTA.1 de tao dien ap analog
Anh em muon bien doi o chan khac cua PORTA thi thay doi o dong
"x=read_adc(1)"

************************************************************************************
Project :
Version :
Date : 6/14/2008
Author : F4CG
Company : F4CG
Comments:

Chip type
: ATmega32
Program type
: Application
Clock frequency : 4.000000 MHz
Memory model
: Small
External SRAM size : 0
Data Stack size : 512
*****************************************************/
#include <mega32.h>
#include <delay.h>
// Alphanumeric LCD Module functions
#asm
.equ __lcd_port=0x15 ;PORTC
#endasm
#include <lcd.h>
#define ADC_VREF_TYPE 0x00
// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input|ADC_VREF_TYPE;
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}
// Declare your global variables here
void main(void)
{
unsigned int x;
char don_vi,chuc,tram,nghin;
// Declare your local variables here
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;
// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0x00;
DDRB=0x00;
// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0x00;
// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T

PORTD=0x00;
DDRD=0x00;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;
// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;
// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;
// ADC initialization

// ADC Clock frequency: 1000.000 kHz


// ADC Voltage Reference: AREF pin
ADMUX=ADC_VREF_TYPE;
ADCSRA=0x82;
// LCD module initialization
lcd_init(16);
while (1)
{
x=read_adc(1);
nghin=x/1000;
x=x%1000;
tram=x/100;
x=x%100;
chuc=x/10;
x=x%10;
don_vi=x;
lcd_putchar(nghin+48);
lcd_putchar(tram+48);
lcd_putchar(chuc+48);
lcd_putchar(don_vi+48);
delay_ms(500);
lcd_clear();
}
}

Potrebbero piacerti anche