|
问题: 共享一下。改自ZLG的i2c程序 :)
i2c.h ==================== #include <AVR/io.h>
#include "type.h"
#define SDA PB1 #define SCL PB0 #define I2C_PORT DDRB
#define SCL_1 cbi(I2C_PORT, SCL); #define SCL_0 sbi(I2C_PORT, SCL); #define SDA_1 cbi(I2C_PORT, SDA); #define SDA_0 sbi(I2C_PORT, SDA);
uchar ack; /*应答标志位*/ uchar UartRecFlag; uchar RecData;
void Start_I2c(); void Stop_I2c(); void SendByte(uchar c); uchar RcvByte(); void Ack_I2c(uchar a); void ReadIC(uchar icadder, uchar adder, uchar count, uchar *buff); void SetIC(uchar icadder, uchar adder, uchar value);
i2c.c ================================ #include "i2c.h"
void _Nop(uchar dly) /*定义空指令*/ { uchar i; for(i=0;i<dly;i++); }
void Start_I2c() { SDA_1; /*发送起始条件的数据信号*/ _Nop(1); SCL_1; _Nop(5); /*起始条件建立时间大于4.7us,延时*/ SDA_0; /*发送起始信号*/ _Nop(5); /* 起始条件锁定时间大于4μs*/ SCL_0; /*钳住I2C总线,准备发送或接收数据 */ _Nop(2); }
void Stop_I2c() { SDA_0 /*发送结束条件的数据信号*/ _Nop(1); /*发送结束条件的时钟信号*/ SCL_1 /*结束条件建立时间大于4μs*/ _Nop(5); SDA_1 /*发送I2C总线结束信号*/ _Nop(4); }
void SendByte(uchar c) { uchar BitCnt; for(BitCnt=0;BitCnt<8;BitCnt++) /*要传送的数据长度为8位*/ { if((c<<BitCnt)&0x80) SDA_1 /*判断发送位*/ else SDA_0 _Nop(1); SCL_1 /*置时钟线为高,通知被控器开始接收数据位*/ _Nop(5); SCL_0 } _Nop(2); SDA_1 /*8位发送完后释放数据线,准备接收应答位*/ _Nop(2); SCL_1 _Nop(3); if(bit_is_set(PINB,SDA))ack=0; else ack=1; /*判断是否接收到应答信号*/ SCL_0 _Nop(2); }
uchar RcvByte() { uchar retc; uchar BitCnt; retc=0; SDA_1 /*置数据线为输入方式*/ for(BitCnt=0;BitCnt<8;BitCnt++) { _Nop(1); SCL_0 /*置时钟线为低,准备接收数据位*/ _Nop(4); SCL_1 /*置时钟线为高使数据线上数据有效*/ _Nop(2); retc=retc<<1; if(bit_is_set(PINB,SDA))retc=retc+1; /*读数据位,接收的数据位放入retc中 */ _Nop(2); } SCL_0 _Nop(2); return(retc); }
void Ack_I2c(uchar a) { if(a==0)SDA_0 /*在此发出应答或非应答信号 */ else SDA_1 _Nop(3); SCL_1 _Nop(5); SCL_0 /*清时钟线,钳住I2C总线以便继续接收*/ _Nop(2); }
void ReadIC(uchar icadder, uchar adder, uchar count, uchar *buff) { uchar i; Start_I2c(); SendByte(icadder); _Nop(10); SendByte(adder); _Nop(10); Stop_I2c();
Start_I2c(); SendByte(icadder+1); _Nop(10);
for (i=0;i<count;i++) { buff[i]=RcvByte(); if (i!=count-1) Ack_I2c(0);//除最后一个字节外,其他都要从MASTER发应答。 } //SendAck();//除最后一个字节外,其他都要从MASTER发应答。
Ack_I2c(1); Stop_I2c(); }
void SetIC(uchar icadder, uchar adder, uchar value) { Start_I2c(); SendByte(icadder); //写入IC命令 _Nop(1); SendByte(adder); //写入地址 _Nop(1); SendByte(value); //写入值 _Nop(1); Stop_I2c(); } 回答1:好东西啊! 回答2:好东西啊!好东西啊!好东西啊!好东西啊! 回答3:好象uchar还没有定义! 回答4:你自己typedef 或者#define 一下不行啊! |