由于室内温度有点冷,所以想测量一下温度有多高,正好手头有DS18B20,就动手写写代码测一下,最终结果是12℃左右,真是受不了啊,看来下个月真要换个地方住了。
电路很简单,DS18B20+4.7K电阻一只+MSP-EXP430FR5739开发套件。DS18B20的GND接板子GND,VDD接板子VCC,DQ接430的P1.7引脚。DQ与VCC之间接4.7K电阻。当然数据线接哪个引脚无所谓,只要稍微改下程序即可。DS18B20的操作程序是我以前在STM32上写的,只是改了一下宏定义就轻松的移植到了430上。
功能说明:
本程序通过430的P1.7引脚读取DS18B20的温度数据,通过串口(9600,8N1)发送给PC机显示。时钟:ACLK=VLO,SMCLK=DCO,MCLK=DCO,使用DCO(8M/8=1M)来产生9600波特率,温度结果保留三位小数。
上传整个工程
贴部分代码,需下载整个工程才能有效果
#include <stdio.h>
#include <msp430.h>
#define DQ_reset() ((P1OUT &= ~BIT7), P1DIR |= BIT7)
#define DQ_set() (P1DIR &= ~BIT7)
#define read_DQ() (P1IN&BIT7)
#define delayus(n) __delay_cycles(n)
static unsigned char reset(void)
{
unsigned char presence=0;
DQ_reset();
delayus(600);
DQ_set();
delayus(70);
presence = read_DQ();
delayus(600);
return presence;
}
static unsigned char read_bit(void)
{
unsigned char rbit=0;
DQ_reset();
delayus(2);
DQ_set();
delayus(12);
rbit = read_DQ();
delayus(50);
return rbit;
}
static void write_bit(unsigned char rbit)
{
DQ_reset();
delayus(2);
if (rbit) DQ_set();
delayus(60);
DQ_set();
delayus(5);//wait for DQ line pull high and hold 1 us
}
unsigned char read_byte(void)
{
unsigned char rbyte = 0;
int i=0;
for (i=0; i<8; ++i)
{
if (read_bit()) rbyte |= (1<<i);
}
return rbyte;
}
void write_byte(unsigned char rbyte)
{
int i=0;
for (i=0; i<8; i++)
{
write_bit(rbyte&(1<<i));
}
delayus(60);
}
unsigned short GetTemperature(void)
{
int i=0, j=1;
unsigned short rval;
do {
j = reset();
} while (j!=0);
write_byte(0xCC);
write_byte(0x44);
delayus(1000000);
reset();
write_byte(0xCC);
write_byte(0xBE);
rval = read_byte();
rval |= (read_byte()<<8);
for (i=0; i<7; i++)
{
read_byte();
}
return rval;
}
int put_char(int ch)
{
UCA0TXBUF = (unsigned char)ch;
while (!(UCA0IFG&UCTXIFG));
return 0;
}
int main( void )
{
// Stop watchdog timer to prevent time out reset
WDTCTL = WDTPW + WDTHOLD;
CSCTL0_H = 0xA5;
CSCTL1 |= DCOFSEL0 + DCOFSEL1; // Set max. DCO setting
CSCTL2 = SELA_1 + SELS_3 + SELM_3; // set ACLK = VLO; MCLK = DCO
CSCTL3 = DIVA_0 + DIVS_3 + DIVM_3; // set all dividers
// Configure UART pins
P2SEL1 |= BIT0 + BIT1;
P2SEL0 &= ~(BIT0 + BIT1);
// Configure UART 0
UCA0CTL1 |= UCSWRST;
UCA0CTL1 = UCSSEL_3; // Set SMCLK = 1M as UCBRCLK
UCA0BR0 = 104; // 9600 baud
UCA0BR1 = 0;
UCA0MCTLW |= 0x1100; // 1M/9600 - INT(1M/9600)=0.16
UCA0CTL1 &= ~UCSWRST; // release from reset
while(1)
{
printf("%.3f\n", GetTemperature()/16.0);
__no_operation();
}
return 0;
}
[
本帖最后由 lcofjp 于 2011-12-1 20:56 编辑 ]