您的位置 首页 产品

STM8S-Discovery第三个程序 – DS18B20

/********STM8S-DiscoveryDS18B20Test*********版本………:1.0*目标………:STM8S105C6*文件名…….:main.c

/******** STM8SDiscovery DS18B20 Test ********
* 版别………: 1.0
* 方针………: 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//开漏
#define DS18B20_DQ_VALUE PG_IDR_IDR0//DQ值

//串口装备
//数据位:8
//中止位:1
//校验位: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);//复位脉冲

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 *********\r\n”);
printf(“Build: %s %s\r\n”,__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);
}
}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/xinpin/chanpin/254898.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部