您当前的位置:五五电子网电子知识单片机-工控设备AVR单片机ATMEGA8 SPI 总线读写 93C46 正文
ATMEGA8 SPI 总线读写 93C46

ATMEGA8 SPI 总线读写 93C46

点击数:7698 次   录入时间:03-04 11:40:50   整理:http://www.55dianzi.com   AVR单片机
// PIN assignment

#define SS PB2 //Chip select

#define SCK PB5 //cLOCk

#define MOSI PB3 //input

#define MISO PB4 //output


#define SS_SET (PORTB|=(1<<SS))
#define SCK_SET (PORTB|=(1<<SCK))
#define MOSI_SET (PORTB|=(1<<MOSI))

#define SS_CLR (PORTB &= ~(1<<SS))
#define SCK_CLR (PORTB &= ~(1<<SCK))
#define MOSI_CLR (PORTB &= ~(1<<MOSI))


void spi_init(void)
{
    DDRB |= (1<<SCK) | (1<<MOSI) |(1<<SS);
    DDRB &=~(1<<MISO); 
    
    SPCR = 0x53;
    SPSR = 0x00;        
}


void SendByte(u8 sData)
{
    SPDR = sData;
    while(!(SPSR & (1<<SPIF)));
}



u8 spi_read(void)
{
    SPDR = 0x00;
    while(!(SPSR & (1<<SPIF)));
    return SPDR;
}

//////////////////////////////////////////////////

//start and stop condition of 93C46


void Start(void)
{
    u8 temp;

    temp = SPCR;
    SPCR = 0; // 禁止SPI功能

//-----------------------------------------------

    SCK_CLR; // 手工产生一个起始位,93C46特殊的地方

    MOSI_SET; // 所以要特殊处理

    SS_SET;
    SCK_SET;
//----------------------------------------------- 

    SPCR = temp; // 使能SPI功能

}

void Stop(void)
{
    SS_CLR;
}

//////////////////////////////////////////////////

// write enable / diable

void EWEN(void)
{
    Start();
    SendByte(0x30); // EWEN command

    Stop();
}

void EWDS(void)
{
    Start();
    SendByte(0x00); // EWDS command

    Stop();
}


//////////////////////////////////////////////////

// read word

u16 ReadWord(u8 addr)
{
    u16 temp=0;
    u8 hig,low;
    
    Start();
    SendByte(addr | 0x80); // read command

    //------------------------ 切换到SPI模式1 

    SPCR = 0x5b;
    hig = spi_read();
    low = spi_read(); 
       //------------------------ 切换回SPI模式0

    SPCR = 0x53;
    Stop();
    temp = (hig<<8) + low ;
    return temp;
}

//////////////////////////////////////////////////

// write a word

void WriteWord(u16 data,u8 addr)
{
    EWEN();
    Start();
    SendByte(addr | 0x40); // write command

    SendByte((u8)(data>>8)); // send hig byte

    SendByte((u8)data); // send low byte

    Stop(); // wait at lease 2ms

}

void WriteAll(u16 data)
{
    EWEN(); // write enable

    Start();
    SendByte(0x10); // write command

    SendByte((u8)(data>>8)); // send hig byte

    SendByte((u8)data); // send low byte

    Stop(); // wait at lease 10MS

}



本文关键字:暂无联系方式AVR单片机单片机-工控设备 - AVR单片机