spi的单片机源程序如下:
- #include"reg52.h"
- #define uchar unsigned char
- #define uint unsigned int
- uchar code s[9]={0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80,0x90};
- sbit cs=P3^4;
- sbit ck=P3^5;
- sbit di=P3^6;
- sbit d0=P3^7;
- #define readcode 0x0c
- #define writecode 0x0a
- void delay1ms()
- {
- unsigned char i,j;
- for(i=0;i<10;i++)
- for(j=0;j<33;j++)
- ;
- }
- /*****************************************************
- 函数功能:延时若干毫秒
- 入口参数:n
- ***************************************************/
- void delaynms(unsigned char n)
- {
- unsigned char i;
- for(i=0;i<n;i++)
- delay1ms();
- }
- void delay(uchar n)
- {
- int i;
- for(i=0;i<n;i++)
- ;
- }
- void clock(void)
- {
- ck=0;
- delay(2);
- ck=1;
- delay(2);
- }
- void send(uchar da_ta)
- {
- int i;
- for(i=0;i<8;i++)
- {
- di=(bit)(da_ta&0x80);
- da_ta<<=1;
- clock();
- }
- }
- uchar receive(void)
- {
- uchar data1=0;
- int i;
- clock();
- for(i=0;i<8;i++)
- {
- data1*=2;
- if(d0)
- data1++;
- clock();
- delay(2);
- }
- return(data1);
- }
- uchar readdata(uchar add)
- {
- uchar read_data;
- cs=1;
- send(readcode);
- send(add);
- read_data=receive();
- cs=0;
- return(read_data);
- }
- void writedata(uchar add,uchar write_data)
- {
- cs=1;
- send(writecode);
- send(add);
- send(write_data);
- cs=0;
- delay(4);
- cs=1;
- delay(4);
- while(!d0);
- cs=0;
- }
- void main()
- { int i;
- P2=0X00;
- while(1)
- {
- for(i=0;i<9;i++)
- {
- writedata(0x00+i,s[i]);
- P2=readdata(0x00+i);
- delaynms(1000);
- }
- }
- }
复制代码
所有资料51hei提供下载:
spi.rar
(27.01 KB, 下载次数: 30)
|