STM8S-Discovery第三個(gè)程序 - DS18B20
* 版本.........: 1.0
* 目標(biāo).........: STM8S105C6
* 文件名.......: main.c
* 編譯器.......: IAR for STM8 V1.1
**********************************************/
#include
#include
#define UART_BAUD 9600//波特率
#define F_MASTER 16000000//主頻率
#define DS18B20_DQ_OUT PG_DDR_DDR0 = 1//輸出
#define DS18B20_DQ_IN PG_DDR_DDR0 = 0//輸入
#define DS18B20_DQ_HIGH PG_ODR_ODR0 = 1//拉高
#define DS18B20_DQ_LOW PG_ODR_ODR0 = 0//拉低
#define DS18B20_DQ_PULL_UP PG_CR1_C10 = 1//上拉
#define DS18B20_DQ_FLOATING PG_CR1_C10 = 0//浮空
#define DS18B20_DQ_PUSH_PULL PG_CR1_C10 = 1//推挽
#define DS18B20_DQ_OPEN_DRAIN PG_CR1_C10 = 0//開(kāi)漏
#define DS18B20_DQ_VALUE PG_IDR_IDR0//DQ值
//串口配置
//數(shù)據(jù)位:8
//停止位:1
//校驗(yàn)位:None
voidUART_Init(void)
{
UART2_CR2_TEN=1;
UART2_CR2_REN=1;
UART2_CR2_RIEN=1;
UART2_BRR2=((unsignedchar)((F_MASTER/UART_BAUD)&0x0f))+(((unsignedchar)((F_MASTER/UART_BAUD)>>8))&0xf0);
UART2_BRR1=((unsignedchar)((F_MASTER/UART_BAUD)>>4));
}
voidUART_TxByte(unsignedchar_data)
{
while(UART2_SR_TXE==0);
UART2_DR=_data;
}
intputchar(intc)
{
UART_TxByte(c);
returnc;
}
void_delay_us(unsignedinti)
{
i*=3;
while(--i);
}
void_delay_ms(unsignedinti)
{
while(i--)
{
_delay_us(1000);
}
}
voidDS18B20_Init(void)
{
DS18B20_DQ_OUT;
DS18B20_DQ_PUSH_PULL;
DS18B20_DQ_HIGH;
_delay_us(10);
DS18B20_DQ_LOW;
_delay_us(600);//復(fù)位脈沖
DS18B20_DQ_IN;
DS18B20_DQ_PULL_UP;
_delay_us(100);
while(DS18B20_DQ_VALUE==1);
_delay_us(400);
}
voidDS18B20_WriteByte(unsignedchar_data)
{
unsignedchari=0;
DS18B20_DQ_OUT;
for(i=0;i<8;i++)
{
DS18B20_DQ_LOW;
_delay_us(2);
if(_data&0x01)
{
DS18B20_DQ_HIGH;
}
_data>>=1;
_delay_us(60);
DS18B20_DQ_HIGH;
}
}
unsignedcharDS18B20_ReadByte(void)
{
unsignedchari=0,_data=0;
for(i=0;i<8;i++)
{
DS18B20_DQ_OUT;
DS18B20_DQ_LOW;
_delay_us(5);
_data>>=1;
DS18B20_DQ_HIGH;
DS18B20_DQ_IN;
if(DS18B20_DQ_VALUE)
{
_data|=0x80;
}
DS18B20_DQ_OUT;
DS18B20_DQ_HIGH;
_delay_us(60);
}
return_data;
}
floatDS18B20_ReadTemperature(void)
{
unsignedchartemp=0;
floatt=0;
DS18B20_Init();
DS18B20_WriteByte(0xcc);
DS18B20_WriteByte(0x44);
DS18B20_Init();
DS18B20_WriteByte(0xcc);
DS18B20_WriteByte(0xbe);
temp=DS18B20_ReadByte();
t=(((temp&0xf0)>>4)+(temp&0x07)*0.125);
temp=DS18B20_ReadByte();
t+=((temp&0x0f)<<4);
returnt;
}
intmain(void)
{
CLK_SWCR_SWEN=1;
CLK_SWR=0xB4;//HSE selected as master clock source
UART_Init();
printf("********* STM8S-Discovery DS18B20 Test *********rn");
printf("Build: %s %srn",__DATE__,__TIME__);
asm("rim");
while(1)
{
_delay_ms(1000);
printf("%.3f ",DS18B20_ReadTemperature());
}
}
#pragma vector = UART2_R_RXNE_vector
__interruptvoidUART2_IRQHandler(void)
{
if(UART2_SR_RXNE==1)
{
UART_TxByte(UART2_DR);
}
}
評(píng)論