/*
  LM75A Custom Wokwi Chip Example

  See for more info: https://docs.wokwi.com/chips-api/getting-started
*/

#include <LM75A.h>
#include <LiquidCrystal_I2C.h>

// Create I2C LM75A instance
LM75A lm75a_sensor(false,  // A0 LM75A pin state (connected to ground = false)
                   false,  // A1 LM75A pin state (connected to ground = false)
                   false); // A2 LM75A pin state (connected to ground = false)
                  
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

float temperature = 0.0f;

uint8_t DegreeBitmap[] = { 0x6, 0x9, 0x9, 0x6, 0x0, 0, 0, 0 };

void setup()
{
  Serial.begin(115200);

  // Initialize the lcd
  lcd.init();

  // Storage the custom degree symbol as character #1
  lcd.createChar(1, DegreeBitmap);

  // Print a message to the LCD
  lcd.backlight();
  lcd.setCursor(5, 0);
  lcd.print("LM75A");
  lcd.setCursor(2, 1);
  lcd.print("Address 0x48");
  delay(1000);
  lcd.clear();

  // Initialise the LM75A.
  Wire.beginTransmission(0x48);
  Wire.write(0x01);              // Configuration register.
  Wire.write(0x18 | 0x02);       // Fault queue: 6; Interrupt Mode on.
  Wire.endTransmission();
}

void loop()
{
  // 11-bit ADC that offers a temperature resolution of 0.125 °C
  temperature = lm75a_sensor.getTemperatureInDegrees();

  if (temperature != INVALID_LM75A_TEMPERATURE)
  {
    lcd.setCursor(2, 0);
    lcd.print("Temperature:");

    // Temperatures range from −55 °C to +125 °C
    // Bug in M2M library: Negative values ​​are above this value
    //if (temperature > 126)
    //  temperature -= 256.00;

    // Bug fix. This will work with the library whether they fix it or not.
    uint16_t i_temperature = temperature * 256.0f;
    temperature = float(int16_t(i_temperature)) / 256.0f;

    // Round temperature to 2 decimal places.
    temperature = round2dp(temperature);

    lcd.setCursor(4, 1);
    lcd.print(temperature);
    lcd.print("\001C   "); // Print char 1 (which is the degree) followed by C
    delay(1000);
  }
  else
  {
    Serial.println("Did you create lm75a.chip.c?");
    Serial.println("See the steps in the header of the \"lm75a-chip.ino\" file.");
    delay(60000);
  }
}

float round2dp(float f)
{
  return round(f * 100.0f) / 100.0f;
}
LM75ABreakout