#ifndef __24C02_H__ #define __24C02_H__ #include "msp430x14x.h" #define OP_READ 0xa1 // 器件地址以及读取操作 #define OP_WRITE 0xa0 // 器件地址以及写入操作 #define uchar unsigned char #define uint unsigned int
#define SDA_OUT P1DIR|=BIT3 #define SDA_IN P1DIR&=~BIT3 #define SCL_OUT P1DIR|=BIT2 #define SCL_IN P1DIR&=~BIT2
#define SDA_H P1OUT|=BIT3 #define SDA_L P1OUT&=~BIT3 #define SCL_H P1OUT|=BIT2 #define SCL_L P1OUT&=~BIT2
//8M晶振时大约20us延时程序 void delayus(uint z) { uint i,j; for(i = 0;i<20;i++) for(j=0;j<z;j++) {;;}; } // 开始位 void start() { SDA_OUT; SCL_OUT; SDA_H; SCL_H; delayus(1); //20 SDA_L; delayus(2);//40 SCL_L; } // 停止位 void stop() { SDA_OUT; SCL_OUT; SDA_L; delayus(2);//20 SCL_H; delayus(2); SDA_H; } // 从AT24Cxx移入数据到MCU uchar shin() { uchar i,read_data; SDA_OUT; SCL_OUT; for(i = 0; i < 8; i++) { SDA_H; delayus(1); SCL_H; SDA_IN; read_data <<= 1; if(P1IN&BIT3) read_data|=0x01; SDA_OUT; SCL_L; } return(read_data); } // 从MCU移出数据到AT24Cxx uchar shout(uint write_data) { uchar i; uchar ack_bit; SDA_OUT; SCL_OUT; for(i = 0; i < 8; i++) // 循环移入8个位 { if(write_data&0x80) SDA_H; else SDA_L; delayus(2);//2 SCL_H; delayus(2);//2 SCL_L; delayus(2);//2 write_data <<= 1; } SDA_H; // 读取应答 delayus(2); SCL_H; //注意拉高 delayus(2); SDA_IN; if(P1IN&BIT3) ack_bit=1; else ack_bit=0; SCL_L; return ack_bit; // 返回AT24Cxx应答位 } // 在指定地址addr处写入数据write_data void write_byte(uchar addr, uchar write_data) { SDA_OUT; SCL_OUT; SDA_H; SCL_H; start(); shout(OP_WRITE); shout(addr); shout(write_data); stop(); delayus(1000); // 写入周期 } // 在当前地址读取 uint read_current() { uint read_data; start(); shout(OP_READ); read_data = shin(); stop(); return read_data; } // 在指定地址读取 uchar read_random(uint random_addr) { SDA_IN; SCL_OUT; SDA_H; SCL_H; start(); shout(OP_WRITE); shout(random_addr); return(read_current()); } #endif
|