本帖最后由 greenfort 于 2012-8-13 01:49 编辑
初学Arduino,制作的通过12864显示多个18B20温度的程序
接线
请参考本论坛中的18B20及LCD12864与Arduino接线,这里不再重复,只是强调一点,18B20的PIN1和PIN3要同时接地,否则会在返回若干值后出现一次错误值(85.00)不知道什么原因
鉴于12864的显示大小,程序最多接9个18B20传感器,多了显示不了
程序代码如下- /*
- LCD Arduino
- PIN1 = GND
- PIN2 = 5V
- RS(CS) = 8;
- RW(SID)= 9;
- EN(CLK) = 3;
- PIN15 PSB = GND;
- */
- #include <OneWire.h>
- #include <DallasTemperature.h>
- #include <stdlib.h>
- #define ONE_WIRE_BUS 2
- #include "LCD12864RSPI.h"
- #define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
- OneWire oneWire(ONE_WIRE_BUS);
- DallasTemperature sensors(&oneWire);
- char str[4]; //定义温度值存储数组,4位,其中3位为数字,1位为小数点
- double temp =0; //定义中间变量,用于将获取的float型温度值转变为unsigned char数组
- unsigned char show[]={
- 0xB5,0xB1,0xC7,0xB0,0xBB,0xB7,0xBE,0xB3,0xCE,0xC2,0xB6,0xC8};//当前环境温度
- int numberOfDevices;
- void setup()
- {
- Serial.begin(9600);
- sensors.begin(); //传感器初始化
- numberOfDevices = sensors.getDeviceCount();
- LCDA.Initialise(); // 屏幕初始化
- LCDA.DisplayString(0,0,show,AR_SIZE(show));//第一行第1格开始,显示文字“当前环境温度”
- }
- void loop()
- {
- sensors.requestTemperatures(); //获取温度值
- for(int i=0;i<numberOfDevices; i++) //逐个获取传感器的温度
- {
- temp=sensors.getTempCByIndex(i); //使用索引序号获得摄氏度数值
- dtostrf(temp,4,2,str); //将获取的数值转换为字符型数组
- if (i<=2)
- {
- LCDA.DisplayString(1,i*3,(unsigned char *)str,sizeof(str));
- } //自第2行第1列开始显示温度值
- else
- {
- if(i>2&&i<=5)
- {
- LCDA.DisplayString(2,(i-3)*3,(unsigned char *)str,sizeof(str));
- }
- else
- {
- LCDA.DisplayString(3,(i-6)*3,(unsigned char *)str,sizeof(str));
- }
- }
- }
- }
复制代码
|