////////////////////////////////////////////////////////////////////////////////
// Name:       KY-001                                                         //
//             Dallas 1-wire protocol, DS1820                                 //
// Platform:   Arduino Mega 2560                                              //
// Created by: HARB rboek2@gmail.com July 2016 GPL copyrights                 //
// http://robotigs.com/robotigs/includes/parts_header.php?idpart=180          //
// The Signal-pin can be connecteded to any input pin.                        //
// Library can be installed through IDE menu.                                 //
// Sketch example based on: https://github.com/PaulStoffregen/OneWire         //
////////////////////////////////////////////////////////////////////////////////

// Define the needed header files for the precompiler, no charge if not used ---
#include <OneWire.h>         //Library can be installed through Arduino IDE menu
OneWire ds(7);      //The DS1820 is connected to pin 7, but may be any input pin

// Define variables ------------------------------------------------------------
bool ledBinVal = LOW;         //You can chose HIGH-on or LOW-off for LED_BUILTIN
byte present = 0;                       //Used for oneWire, present = ds.reset() 
byte i;
byte data[12];
byte type_s = 0; //0 always ok, except old DS1820 = 1, results in different calc
float celsius, fahrenheit;
byte addr[8];    //Array with the first 8 bytes of DS1820 ROM, including address


void setup() { //Setup runs once ***********************************************
  Serial.begin(9600);   //Nothing more needed for the Serial Monitor to function
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  toggle_ledBin();                                           //Show we are awake
  DS1820_init();                                  //Determins the type of DS1820
  DS1820_init();                                  //Determins the type of DS1820
}//--(end setup )---------------------------------------------------------------


void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  DS1820_read();                  //Reads the temperature from DS1820 in Celcius
  Serial.print("Tmp1=");
  Serial.print(celsius);
  Serial.println("C");
  toggle_ledBin();                                           //Show we are awake
  delay(60000);
} //End of void loop()                       //KEEP ON RUNNING THIS LOOP FOREVER
//345678911234567892123456789312345678941234567895123456789612345678971234567898


void DS1820_read(void) {          //Reads the temperature from DS1820 in Celcius
  ds.reset();
  ds.select(addr);
  ds.write(0x44);      // start conversion, with parasite power on at the end    
  delay(800);     // maybe 750ms is enough, maybe not
  present = ds.reset(); 
  ds.select(addr);    
  ds.write(0xBE);         // Read Scratchpad
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }
  int16_t raw = (data[1] << 8) | data[0];
  celsius = (float)raw / 16.0;
}


void DS1820_init(void) {                          //Determins the type of DS1820
  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }
  
  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();
 
  switch (addr[0]) {   // the first ROM byte indicates which chip
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  } 

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end
  
  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.
  
  present = ds.reset();
  ds.select(addr);    
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

void toggle_ledBin(void) { //Toggles the LED_BUILTIN on-board LED on or off ****
  ledBinVal = !ledBinVal;                                         //Toggle value
  digitalWrite(LED_BUILTIN, ledBinVal);         //Set Arduino boards onboard LED
} //Exit toggle_ledBin ---------------------------------------------------------


////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=1)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS                                                            //
// Prog=List=Chip                                                             //
// A0  = 97 = PF0 ADC0             =                                      ADC //
// A1  = 96 = PF1 ADC1             =                                      ADC //
// A2  = 95 = PF2 ADC2             =                                      ADC //
// A3  = 94 = PF3 ADC3             =                                      ADC //
// A4  = 93 = PF4 ADC4/TMK         =                                      ADC //
// A14 = 83 = PK6 ADC14/PCINT22    = Battery monitor H=1/2 6Vdc pack      ADC //
// A15 = 82 = PK7 ADC15/PCINT23    = Battery monitor H=1/3 9Vdc battery   ADC //
// 0   =  2 = PE0 RXD0/PCINT8      = Serial monitor, also on-board LED    RX0 //
// 1   =  3 = PE1 TXD0             = Serial monitor, also on-board LED    TX0 //
// 2   =  6 = PE4 OC3B/INT4        = IR TV remote control receiver        INT //
// 3   =  7 = PE5 OC3C/INT5        = Motorshield                          INT //
// 4   =  1 = PG5 OCOB             = Motorshield                          PWM //
// 5   =  5 = PE3 OC3A/AIN1        = Motorshield M3 => Free PWM pin       PWM //
// 6   = 15 = PH3 OC4A             = Motorshield M4 => Buzzer             PWM //
// 7   = 16 = PH4 OC4B             = Motorshield                          PWM //
// 8   = 17 = PH5 OC4C             = Motorshield                          PWM //
// 9   = 18 = PH6 OC2B             = Motorshield                          PWM //
// 10  = 23 = PB4 OC2A/PCINT4      = Motorshield                          PWM //
// 11  = 24 = PB5 OC1A/PCINT5      = Motorshield                          PWM //
// 12  = 25 = PB6 OC1B/PCINT6      = Motorshield                          PWM //
// 13  = 26 = PB7 OCOA/OC1C/PCINT7 = On board user LED, on=high off=low   PWM //
// 18  = 46 = PD2 TXD1/INT3        = Speed encoder Right                  TX1 //
// 19  = 45 = PD2 RXD1/INT2        = Speed encoder Left                   RX1 //
// 20  = 44 = PD1 SDA/INT1         = SDA Yellow SRF10                     TWI //
// 21  = 43 = PD0 SCL/INT0         = SCL White  SRF10                     TWI //
// 44  = 40 = PL5 OC5C             = 3 Color led Blue                     PWM //
// 45  = 39 = PL4 OC5B             = 3 Color led Red                      PWM //
// 46  = 38 = PL3 OC5A             = 3 Color led Green                    PWM //
// 50  = 22 = PB3 MISO/PCINT3      =                                      SPI //
// 51  = 21 = PB2 MOSI/PCINT2      =                                      SPI //
// 52  = 20 = PB1 SCK/PCINT1       =                                      SPI //
// 53  = 19 = PB1 SS/PCINT0        =                                      SPI //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898