2017/12/27

Display Temperature on 8-digit 7-segment Max7219 LED Display using DS18B20

Photo



Sketch
/*
pin 13 (D7) is connected to the DataIn 
pin 14 (D5) is connected to the CLK 
pin 15 (D8) is connected to LOAD 

Modified by Befun Hung on Mar. 26, 2017
to correct errors in comments and data displayed
Modified by Befun Hung on Mar. 27, 2017
to add and correct errors in printNumber() by circuits4you.com 
Modified by Befun Hung on Mar. 30, 2017
to display temperature to 8-digits 7-segment module
*/

// 匯入程式庫標頭檔 
#include <OneWire.h>
#include <DallasTemperature.h>
#include "LedControl.h" 

#define DIN 13
#define CLK 14
#define LOAD 15
#define lowLimit 0.0
#define upLimit 37.3
LedControl lc=LedControl(DIN,CLK,LOAD,1);

// Arduino數位腳位2接到1-Wire裝置
#define ONE_WIRE_BUS D4

float myTemp;
long dispTemp;

// 運用程式庫建立物件
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void)
{
   Serial.begin(115200);
   Serial.println("Temperature Sensor");
   // 初始化 
   sensors.begin();

   // Initialize the MAX7219 
   // Serial.println("14CORE TEST CODE FOR LED MAX7219 LED TUBE");
   // Serial.println(" --- Modified by Befun Hung on Mar. 26, 2017");
   lc.shutdown(0,false); // To Enable the Display 
   lc.setIntensity(0,7); // To set the brightness level (0 is min, 15 is max) 
   lc.clearDisplay(0); // To Clear the display register 
  
}

void loop(void)
{
  // 要求匯流排上的所有感測器進行溫度轉換(不過我只有一個) 
  sensors.requestTemperatures();

  // 取得溫度讀數(攝氏)並輸出,
  // 參數0代表匯流排上第0個1-Wire裝置 
  // Serial.println(sensors.getTempCByIndex(0));

  myTemp = (sensors.getTempCByIndex(0));
  if (myTemp<lowLimit) {myTemp=lowLimit;}
  if (myTemp>upLimit)  {myTemp=upLimit;}
  Serial.print(myTemp);
  Serial.print(" C, ");
  dispTemp = (long) round(myTemp * 10);
  printC(dispTemp);
  
  Serial.print(DallasTemperature::toFahrenheit(myTemp));
  Serial.println(" F");
  dispTemp = (long) round(DallasTemperature::toFahrenheit(myTemp) * 10);
  printF(dispTemp);

  delay(1000);
}

void printC( long v)
{
   // Variable value digit 
   int digito6;
   int digito7;
   int digito8;

   // Calculate the value of each digit 
   digito6 = (v % 10) ;
   digito7 = (v / 10 )% 10 ;
   digito8 = (v / 100 )% 10 ;  
  
   // Display the value of each digit in the display 
   lc.setDigit ( 0 , 7 , (byte) digito8, false);
   lc.setDigit ( 0 , 6 , (byte) digito7, true);
   lc.setDigit ( 0 , 5 , (byte) digito6, false);
   lc.setRow(0, 4, B1001110);
}

void printF( long v)
{
   // Variable value digit 
   int digito2;
   int digito3;
   int digito4;

   // Calculate the value of each digit 
   digito2 = (v % 10) ;
   digito3 = (v / 10 )% 10 ;
   digito4 = (v / 100 )% 10 ;  
  
   // Display the value of each digit in the display 
   lc.setDigit ( 0 , 3 , (byte) digito4, false);
   lc.setDigit ( 0 , 2 , (byte) digito3, true);
   lc.setDigit ( 0 , 1 , (byte) digito2, false);
   lc.setRow(0, 0, B1000111);
}