单片机cc2530写一个代码:读取片内温度传感器值并发送至串口显示,注意保留小数点后2位
时间: 2024-05-07 08:19:08 浏览: 93
以下是CC2530读取片内温度传感器值并发送至串口显示的代码,已经在代码中保留了小数点后2位。
```
#include <ioCC2530.h>
#define BAUDRATE 115200
void uart_init()
{
PERCFG &= ~0x10; // UART1位置设为P0.5和P0.6
P0SEL |= 0x30; // P0.5和P0.6设为UART1_TX和UART1_RX
U1CSR |= 0x80; // UART模式设为UART模式
U1GCR |= 0x08; // 设置波特率发生器时钟源为16MHz晶振
U1BAUD = 216; // 设置波特率为115200
U1UCR |= 0x80; // UART使能
}
void send_char(unsigned char c)
{
while(!(U1CSR & 0x02));
U1CSR &= ~0x02;
U1DBUF = c;
}
void send_string(char *str)
{
while(*str != '\0')
{
send_char(*str++);
}
}
void send_float(float num)
{
int a = (int)(num * 100);
send_string("Temperature: ");
send_char(a / 100 + '0');
send_char('.');
send_char(a % 100 / 10 + '0');
send_char(a % 10 + '0');
send_string("C\r\n");
}
void adc_init()
{
ADCCON3 |= 0x80; // 温度传感器使能
}
float read_temperature()
{
float temperature = 0;
int adc_value = 0;
ADCCON1 |= 0x30; // 选择温度传感器输入通道
ADCCON3 |= 0x04; // 启动ADC转换
while(ADCCON1 & 0x30);
adc_value = ADCL;
adc_value |= ADCH << 8;
temperature = (float)(adc_value - 600) * 0.01 + 25; // 计算温度
return temperature;
}
void main(void)
{
uart_init();
adc_init();
while(1)
{
float temperature = read_temperature();
send_float(temperature);
for(int i = 0; i < 10000; i++); // 等待一段时间
}
}
```
注意,由于CC2530的温度传感器的精度较低,所以计算得到的温度可能存在一定误差。
阅读全文
相关推荐


















