MEGA32下的HC595驱动,已测试
#ifndef _HC595_H #define _HC595_H
//SPI initialize // clock rate: 250000hz void spi_init(void) { DDRB |= (1<<PB5) | (1<<PB7) | (1<<PB4); /* 设置MOSI 和SCK 为输出,其他为输入 */ SPCR = (1<<SPE) | (1<<MSTR) | (1<<SPR1) | (1<<SPR0); /* 使能SPI主机模式,设置时钟速率为fck/128 */ }
#pragma interrupt_handler spi_stc_isr:13 void spi_stc_isr(void) { //byte in SPDR has been sent/received
}
/*SPI数据发送*/ void SPI_MasterTransmit(unsigned char i) {
SPDR = i; /* 启动数据传输 */ while (!(SPSR & (1<<SPIF))); /* 等待传输结束 */ } /*595数据输出*/ void SPI_595_Out(unsigned int i) { uint j; PORTB &= ~(1 << 4); /*准备锁存*/ SPI_MasterTransmit(i>>8); SPI_MasterTransmit(i); PORTB |= (1 << 4); /*锁存数据*/ } /* void write595(unsigned char DATA) //写数据到74HC595函数 { uchar i; SPDR=DATA; //开始发送数据 //while((SPSR>>7)==0); //等待发送接收结束 while(!(SPSR & (1<<SPIF))) ; i=SPDR; //读,是为了清零中断标志 } */
void TurnOnDigitalOutput(uchar n) { if ( n>16 ) return; DigitalOutputStatus[n] = 1; DATA_74HC595 |= (0x0001<<n); SPI_595_Out(DATA_74HC595); }
void TurnOffDigitalOutput(uchar n) { if ( n>16 ) return; DigitalOutputStatus[n] = 0; DATA_74HC595 &= ~(0x0001<<n); SPI_595_Out(DATA_74HC595); } #endif
|