調(diào)試通過的AVR mega16 SPI雙機(jī)通訊例子 (為新手設(shè)計(jì),簡單易懂)本程序?qū)崿F(xiàn)的功能:主機(jī)發(fā)送1~255,叢機(jī)接收并在LED上顯示出來。連接方式: 兩個mega16最小系統(tǒng)板 PB4到PB7全部對連。
本程序在本站的最小系統(tǒng)板上測試通過,我向你擔(dān)保本程序的正確性。
查看商品:ATmega16 開發(fā)板 AVR學(xué)習(xí)板 Mega16 核心板 (特價)
[code="C"]
//ICC-AVR application builder : 2007-7-18 13:01:11
// Target : M16
// Crystal: 7.3728Mhz
// 作者:古欣
// AVR與虛擬儀器 [url]http://www.avrvi.com[/url]
// 功能:SPI主機(jī)模式,循環(huán)發(fā)送從1~255
#include <iom16v.h>
#include <macros.h>
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
//SPI initialize
// clock rate: 57599hz
void spi_init(void)
{
PORTB |= (1<<PB4) | (1<<PB5) | (1<<PB6) | (1<<PB7);
DDRB |= (1<<DDB5) | (1<<DDB7) | (1<<DDB4); //Set MOSI, SCK AND SS as outputs
SPCR = 0x73; //setup SPI
SPSR = 0x00; //setup SPI
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
spi_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
void SPI_MasterTransmit(char cData)
{
PORTB &=~ (1<<PB4); //強(qiáng)制接收方進(jìn)入從模式
SPCR |= (1<<MSTR); // MSTR有時會被清零,這里強(qiáng)制進(jìn)入主機(jī)模式
/* 啟動數(shù)據(jù)傳輸 */
SPDR = cData;
/* 等待傳輸結(jié)束 */
while(!(SPSR & (1<<SPIF)))
;
PORTB |= (1<<PB4);
}
void Delay(void) //延時,沒有詳細(xì)計(jì)算
{
unsigned int i,j;
for(i=1000;i>0;i--)
{
for(j=200;j>0;j--)
;
}
}
void main(void)
{
unsigned char i=0;
init_devices();
while(1)
{
for(i=255;i>0;i--)
{
SPI_MasterTransmit(i);
Delay();
}
}
}
[/code]
[code="c"]
//ICC-AVR application builder : 2007-7-18 12:56:10
// Target : M16
// Crystal: 7.3728Mhz
// 作者:古欣
// AVR與虛擬儀器 [url]http://www.avrvi.com[/url]
// 功能:從機(jī)模式,中斷方式接收,并在LED上顯示
#include <iom16v.h>
#include <macros.h>
void port_init(void)
{
PORTA = 0x00;
DDRA = 0xFF;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
//SPI initialize
// clock rate: 57599hz
void spi_init(void)
{
SPCR = 0xE3; //setup SPI
SPSR = 0x00; //setup SPI
}
#pragma interrupt_handler spi_stc_isr:11
void spi_stc_isr(void)
{
//byte in SPDR has been sent/received
PORTA = SPDR;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
spi_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
void main(void)
{
init_devices();
DDRB|=(1<<PB6); //MOSI 設(shè)置為輸出
while(1)
;//等待中斷
}
[/code]