#include "reg51.h"
sbit SPICS = P1^0 ;
sbit SPISK = P1^1 ;
sbit SPIDI = P1^2 ;
sbit SPIDO = P1^3 ;
void delay ( unsigned int timeM )
{ unsigned int count;
TH0 = 0x06 ;
TL0 = 0x06 ;
TMOD = 0x02 ;
TF0 = 0 ;
TR0 = 1 ;
for ( ; timeM > 0 ; timeM-- )
{ for ( count=4 ; count>0 ; )
if ( TF0 ) { count-- ;
TF0 = 0;
}
}
}
void SPIstart ( void )
{ SPICS = 0 ; SPISK = 0 ;
SPIDI = 1 ;
SPIDO = 1 ;
delay ( 10 ) ;
return ;
}
void SPIewen ( void )
{ unsigned char command , count; SPIstart () ;
SPICS = 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPIDI = 0 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
command = 0xC0 ;
for ( count = 0 ; count < 7 ; count ++ )
{ if ( command & 0x80 ) SPIDI = 1 ;
else SPIDI = 0 ;
command <<= 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
}
SPICS = 0 ;
delay ( 10 ) ;
return ;
}
void SPIwrite ( unsigned char address , unsigned int wdata )
{ unsigned char count , waddress ; unsigned int databuf ;
waddress = address , databuf = wdata ;
SPIewen () ;
SPIstart () ;
SPICS = 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPIDI = 0 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPIDI = 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
for ( count = 0 ; count < 7 ; count ++ ) /* send the address */
{ if ( waddress & 0x80 ) SPIDI = 1 ;
else SPIDI = 0 ;
waddress <<= 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
}
for ( count = 0 ; count < 8 ; count ++ )
{ if ( databuf & 0x80 ) SPIDI = 1 ;
else SPIDI = 0 ;
databuf <<= 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
}
SPICS = 0 ;
delay ( 10 ) ;
return ;
}
unsigned char SPIread ( unsigned char address )
{ unsigned char count , waddress ; unsigned int wdata ;
waddress = address ;
SPIstart () ;
SPICS = 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
SPIDI = 0 ; SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
for ( count = 0 ; count < 7 ; count ++ )
{ if ( waddress & 0x80 ) SPIDI = 1 ;
else SPIDI = 0 ;
waddress <<= 1 ;
SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
}
SPIDO = 1 ;
someNOP () ;
for ( count = 0 ; count < 8 ; count ++ )
{ SPISK = 1 ;
someNOP() ;
SPISK = 0 ;
wdata <<= 1 ;
if ( SPIDO == 1 ) wdata = wdata + 1 ;
}
SPICS = 0 ;
return ( wdata );
} void main()
{ unsigned char buf [ 8 ] ;
SPIwrite ( 0x00 , 0x00 ) ;
buf [ 0 ] = SPIread ( 0x00 ) ;
} 我的51程序,读写93C46的,一直不成功,不知道是什么原因.请大虾指点,不胜感激!!! |