大家好! 我在用飞思卡尔单片机(MC9S08DZ16)和温度传感器(DS1624)使用IIC通讯时,总是不能设单片机为主机模式,报仲裁丢失位置1.我的具体程序如下: //用DZ16自带的SDA SCL完成温度采集
#include<hidef.h> #include"derivative.h" #define uchar unsigned char #define uint unsigned int //定义函数 void MCU_Init(void); void Time2_Init(void); void I2C_Init(void); void delay(void); void delay10ms(void); void I2C_Start(void); void wait_ack(void); void I2C_WriteByte(uchar data); uchar I2C_ReadByte(void); void I2C_Stop(void); void DS1624_Init(void); void Start_temperature_T(void); void Read_temperature_T(uchar*p); void Stop_temperature_T(void); void Time2_Overflow(void); double HexToDec(uchar H,uchar L); //定义变量 uint flag; uint k; uint Acount; uchar temperature[2]; double result_T; uchar temp; //定义时钟,总线频率为4M void MCU_Init(void){ SOPT1=0x00; MCGC1=0xB8; MCGC2=Ox36; MCGC3=0x00; PTEDS_PTEDS5=0; PTEDS_PTEDS4=0; } //定时器TPM2初始化,定义溢出中断时间为10ms void Time2_Init(void){ TPM2SC=Ox49; TPM2MODH=0x4E; TPM2MODL=0x20; }
//1us的延时 void delay(void){ _asm("nop"); _asm("nop"); _asm("nop"); _asm("nop"); } //10ms的延时 void delay10ms(void){ uint n; for(n=0;n<10000;n++) delay(void); }
void I2C_Init(void){ IICC1=0x80; IICC2=0x00; IICF=0x07; } void I2C_Start(void){ IICC1|=Ox30; } void wait_ack(void){ while (IICS_RXAK); } void I2C_WriteByte(uchar data){ IICS_IICIF=1; IICD=data; while (!IICS_IICIF); } uchar I2C_ReadByte(void){ while(!IICS_IICIF); IICS_IICIF=1; return IICD; } void I2C_Stop(void){ IICC1&=0xDF; } void DS1624_Init(void){ I2C_WriteByte(0x90); wait_ack(); I2C_WriteByte(0xAC); wait_ack(); I2C_WriteByte(0x4A); wait_ack(); I2C_Stop(); delay10ms(); } void Start_temperature_T(void){ I2C_WriteByte(0x90); wait_ack(); I2C_WriteByte(0xEE); wait_ack(); I2C_Stop(); } void Read_temperature_T(uchar*p){ I2C_WriteByte(0x90); wait_ack(); I2C_WriteByte(0xAA); wait_ack(); IICC1_RSTA=1; I2C_WriteByte(0x91); wait_ack(); IICS_IICIF=1; IICC1_TX=O; *(p+1)=I2C_ReadByte(); *p=I2C_ReadByte(); IICC1_TXAK=1; I2C_Stop(); } void Stop_temperature_T(void){ I2C_WriteByte(0x90); wait_ack(); I2C_WriteByte(0x22); wait_ack(); I2C_Stop(); } void Time2_Overflow(void){ TPM2SC_TOIE=0; TPM2SC_TOF=0; k++; if(k==100){ flag=1; k=0; Acount++; } TPM2SC_TOIE=1; } double HexToDec(uchar H,uchar L){ //省略 } void main (void){ uint i; k=0; Acount=0; flag=0; result_T=0; temp=0x00; for (i=0;i<2;i++) temperature=0; MCU_Init(); I2C_Init(); while(IICS_BUSY); I2C_Start(); while(!IICS_BUSY); DS1624_Init(); Start_temperature_T(); Stop_temperature_T(); Time2_Init(); EnableInterrupts; for(;;) { if(flag==1){ flag=0; if(Acount<5) { I2C_Start(); Read_temperature_T(temperature); } else{ TPM2SC_TOIE=0; break; } } else{} } result_T=HexToDec(temperature[1],temperature[0]); } |