改成基于STC8h芯片的来写
时间: 2023-07-29 18:10:44 浏览: 68
好的,以下是一个基于STC8h芯片的DS18B20温度传感器的示例代码:
```
#include <intrins.h>
// 定义 DS18B20引脚
#define DS1820_PIN P3_4
// 定义 OneWire 操作函数
void OneWire_Reset(void);
void OneWire_WriteByte char dat);
unsigned char OneWire_ReadByte(void);
void main() {
unsigned char data[12];
unsigned char addr[8];
TMOD &= 0x0F;
TMOD |= 0x10;
TH1 = 0xFA;
TL1 = 0xFA;
PCON |= 0x80;
SCON = 0x50;
TR1 = 1;
ES = 1;
EA = 1;
while (1) {
if (!OneWire_Search(addr)) {
OneWire_Reset();
delay(1000);
continue;
}
if (OneWire_CRC( addr, 7) != addr[7]) {
UART_SendString("CRC is not valid!\r\n");
continue;
}
OneWire_Reset();
OneWire_WriteByte(0x55);
for (unsigned char i = 0; i < 8; i++) {
OneWire_WriteByte(addr[i]);
}
OneWire_WriteByte(0x44);
delay(1000);
OneWire_Reset();
OneWire_WriteByte(0x55);
for (unsigned char i = 0; i < 8; i++) {
OneWire_WriteByte(addr[i]);
}
OneWire_WriteByte(0xBE);
for (unsigned char i = 0; i < 9; i++) {
data[i] = OneWire_ReadByte();
}
int16_t raw = (data[1] << 8) | data[0];
float celsius = (float)raw / 16.0;
UART_SendFloat(celsius);
UART_SendString(" °C\r\n");
}
}
void OneWire_Reset(void) {
DS18B20_PIN = 0;
_nop_();
_nop_();
_nop_();
_nop_();
DS18B20_PIN = 1;
_nop_();
_nop_();
_nop_();
_nop_();
}
void OneWire_WriteByte(unsigned char dat) {
for (unsigned char i = 0; i < 8; i++) {
DS18B20_PIN = 0;
_nop_();
_nop_();
_nop_();
_nop_();
DS18B20_PIN = dat & 0x01;
_nop_();
_nop_();
_nop_();
_nop_();
dat >>= 1;
DS18B20_PIN = 1;
}
}
unsigned char OneWire_ReadByte(void) {
unsigned char dat = 0;
for (unsigned char i = 0; i < 8; i++) {
DS18B20_PIN = 0;
_nop_();
_nop_();
_nop_();
_nop_();
DS18B20_PIN = 1;
_nop_();
_nop_();
_nop_();
_nop_();
dat >>= 1;
if (DS18B20_PIN) {
dat |= 0x80;
}
}
return dat;
}
unsigned char OneWire_Search(unsigned char *addr) {
unsigned char i, j, flag;
OneWire_Reset();
OneWire_WriteByte(0xF0);
for (i = 0; i < 8; i++) {
addr[i] = 0;
}
for (i = 0; i < 64; i++) {
flag = 0;
for (j = 0; j < 8; j++) {
if (OneWire_ReadByte() != ((i & (1 << j)) ? 0x80 : 0x00)) {
flag = 1;
break;
}
}
if (flag) {
continue;
}
for (j = 0; j < 8; j++) {
addr[j] |= (OneWire_ReadByte() << i);
}
return 1;
}
return 0;
}
unsigned char OneWire_CRC(unsigned char *addr, unsigned char len) {
unsigned char i, j, crc = 0;
for (i = 0; i < len; i++) {
unsigned char inbyte = addr[i];
for (j = 0; j < 8; j++) {
unsigned char mix = (crc ^ inbyte) & 0x01;
crc >>= 1;
if (mix) {
crc ^= 0x8C;
}
inbyte >>= 1;
}
}
return crc;
}
void UART_SendString(char *str) {
while (*str) {
SBUF = *str++;
while (!TI);
TI = 0;
}
}
void UART_SendFloat(float num) {
char buffer[10];
sprintf(buffer, "%.2f", num);
UART_SendString(buffer);
}
```
请注意,该代码中的 DS18B20_PIN 变量需要根据您实际使用的引脚进行修改。此外,代码中的 UART_SendString 和 UART_SendFloat 函数需要根据您实际使用的串口进行修改。
阅读全文