MSP430F149单片机驱动DS2762读写操作C语言程序
/******************************************************************************
从DS2762读出一位
Read a bit from the 1-Wire bus and return it. Provide 10us recovery time.
******************************************************************************/
uchar OWReadBit(void)
{
uchar result;
P30 = 0; // Drives DQ low
tickDelay(A);
P30 = 1; // Releases the bus
tickDelay(E);
result = P3IN & 0X01; // Sample the bit value from the slave
tickDelay(F); // Complete the time slot and 10us recovery
return result;
}
/******************************************************************************
像写DS2762写入一个字节
Send a 1-Wire write . Provide 10us recovery time.
DS2762特性发送所有的命令和数据都是字节的低位在前,这与多数串行通信格式相反
******************************************************************************/
void OWWriteByte(uchar data)
{
uchar loop;
// Loop to write each bit in the byte, LS-bit first
for (loop = 0; loop < 8; loop++)
{
OWWriteBit(data & 0x01);
// shift the data byte for the next bit
data >>= 1;
}
}
/******************************************************************************
从DS2762中读一个字节
******************************************************************************/
uchar OWReadByte(void)
{
uchar loop, result=0;
for (loop = 0; loop < 8; loop++)
{
// shift the result to get it ready for the next bit
result >>= 1;
// if result is one, then set MS bit
if (OWReadBit())
result |= 0x80;
}
return result;
}
/******************************************************************************
发送字符函数
按照论文图时序进行的操作
目前不清楚连续读需要通过测试进行优化。
方案一:发出读命令 发出一个地址 读两次 应该是正确的
方案二:发出读命令 发出两个地址 读两次
******************************************************************************/
uint readvoltage(void)
{
uchar j = 1;
unsigned char volhigh,vollow;
while(j) //检查2762是否应答
{
j = OWTouchReset();
}
OWWriteByte(0xcc); //
OWWriteByte(0x69);
OWWriteByte(0x0c);
vollow = OWReadByte();
volhigh = OWReadByte();
return ((volhigh<<8)|(vollow)); //将两个字节进行合并
}
/******************************************************************************
时钟初始化
注意,需要选用8M晶振,时钟周期125ns
******************************************************************************/
void Init_clk(void)
{unsigned char i;
//时基模块的时钟设置
//单片机上电时,MCLK主时钟的源默认选择为DCO提供.F1系列DCO默认800KHZ.
//ACLK辅助时钟默认为XT1,XT1一般接32768HZ晶体.
//SMCLK子时钟默认为DCO,同样是800KHZ.
//XT2需要人为开启,并要检测其开启是否成功.
BCSCTL1 &= ~(XT2OFF + XTS); //启动XT2高速时钟模块
BCSCTL2 |= SELM1; //MCLK主时钟选XT2为时钟源.TX2输入不分频.
BCSCTL2 &= ~SELS; //SMCLK选为DCO为时钟源.(参考)
//刚才开启了XT2,需要一定时间XT2才进入稳定状态.所以需要等待并检测稳定状态.
//通常采用do...for语法,这是TI推荐的程序写法
do
{
IFG1 &=~OFIFG; //清OSCFault 标志
for(i=0xff;i>0;i--) //延时等待其开启稳定
;
}
while((IFG1 & OFIFG) !=0); //检查OSCFault标志位是否为0,若为0则表示XT2开启稳定.
//否则一直等下去...
}
/******************************************************************************
主函数
注意,需要选用8M晶振,时钟周期125ns
******************************************************************************/
void main()
{
WDTCTL = WDTPW | WDTHOLD; // 停止看门狗
Init_clk();
SetSpeed(1);
while(1)
{
data = readvoltage();
}
评论