Изменение цвета шрифта в зависимости от температуры.

Тема в разделе "Arduino & Shields", создана пользователем Dioskuri, 8 окт 2015.

  1. Dioskuri

    Dioskuri Нерд

    Доброго времени суток!
    Собрал метеостанцию на Arduino UNO+TFTLCD shield+DHT11+BMP180+RTC DS1307. Скомпоновал скетч из разных источников, вроде все заработало. Хотелось бы украсить изменением цвета шрифта или ячейки за шрифтом в зависимости от изменения температуры. Все, что ни находил на просторах и-нета не подходит для моей библиотеки. Буду благодарен за помощь в этом деле и подсказку как дописать к скетчу такую функцию.
    Сам скетч:
    Код (C++):

    #include "SPI.h"
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_TFTLCD.h> // Hardware-specific library

    #include <Wire.h>
    #include <BMP180.h>
    #include "DHT.h"
    #include "RTClib.h"
    #define USE_ADAFRUIT_SHIELD_PINOUT

    // The control pins for the LCD can be assigned to any digital or
    // analog pins...but we'll use the analog pins as this allows us to
    // double up the pins with the touch screen (see the TFT paint example).
    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0

    #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin

    // Assign human-readable names to some common 16-bit color values:
    #define    BLACK        0x0000
    #define    BLUE         0x001F
    #define    RED          0xF800
    #define    GREEN        0x07E0
    #define CYAN         0x07FF
    #define MAGENTA      0xF81F
    #define YELLOW       0xFFE0
    #define WHITE        0xFFFF
    #define NAVY         0x000F
    #define DARKGREEN    0x03E0
    #define ORANGE       0xFD20
    #define GREENYELLOW  0xAFE5
    #define PINK         0xF81F
    #define SILVER       0xC618

    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
    // Модуль часов
    RTC_DS1307 RTC;
    DateTime now;
    DateTime time_old;
    DateTime date_old;
    boolean night_mode=true;
    // Сенсоры
    BMP180    sensor;
    DHT dht;
    #define DHTPIN 12
    // char array to print to the screen
    char tempPrintout[6];
    char humPrintout[6];
    char presPrintout[6];

    int cycleTime = 2000;

    void setup() {

    Serial.begin(9600);
      Serial.println(F("TFT LCD test"));
      Serial.println("DHT test!");
      Wire.begin();
      RTC.begin();
      dht.setup(12);  //DHT start
      sensor.begin();  // BMP start
     
    if (! RTC.isrunning()) {
        // Установка актуального времени и даты
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }
    #ifdef USE_ADAFRUIT_SHIELD_PINOUT
      Serial.println(F("Using Adafruit 2.8\" TFT Arduino Shield Pinout"));
    #else
      Serial.println(F("Using Adafruit 2.8\" TFT Breakout Board Pinout"));
    #endif

      Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height());
      tft.reset();
      uint16_t identifier = tft.readID();

      if(identifier == 0x9325) {
        Serial.println(F("Found ILI9325 LCD driver"));
      } else if(identifier == 0x9327) {
        Serial.println(F("Found ILI9327 LCD driver"));
      } else if(identifier == 0x9328) {
        Serial.println(F("Found ILI9328 LCD driver"));
      } else if(identifier == 0x7575) {
        Serial.println(F("Found HX8347G LCD driver"));
      } else if(identifier == 0x9341) {
        Serial.println(F("Found ILI9341 LCD driver"));
      } else if(identifier == 0x8357) {
        Serial.println(F("Found HX8357D LCD driver"));
      } else if(identifier == 0x0154) {
        Serial.println(F("Found S6D0154 LCD driver"));
      } else if(identifier == 0x9488) {
        Serial.println(F("Found ILI9488 LCD driver"));
    } else {
        Serial.print(F("Unknown LCD driver chip: "));
        Serial.println(identifier, HEX);
        Serial.println(F("If using the Adafruit 2.8\" TFT Arduino shield, the line:"));
        Serial.println(F("  #define USE_ADAFRUIT_SHIELD_PINOUT"));
        Serial.println(F("should appear in the library header (Adafruit_TFT.h)."));
        Serial.println(F("If using the breakout board, it should NOT be #defined!"));
        Serial.println(F("Also if using the breakout, double-check that all wiring"));
        Serial.println(F("matches the tutorial."));
        return;
      }
     
      tft.begin(identifier);

    // Вывод черного фона на экран
    tft.fillScreen(BLACK);
    // Вывод статического текста на экран
    tft.setTextColor(GREEN); // Установка цвета шрифта
    tft.setTextSize(2); // Установка размера шрифта
    tft.setCursor(40, 74); // Установка координат начала текста
    tft.println("Temperatura: C");
    tft.setCursor(55, 98);
    tft.println("IN");
    tft.setCursor(168, 98);
    tft.println("OUT");
    tft.setTextColor(BLUE);
    tft.setCursor(40, 160);
    tft.println("Vlazhnost: %");
    tft.setTextColor(RED);
    tft.setCursor(40, 230);
    tft.println("Davlenie:mmHg");

    }

    void loop() {
       // Дата и Часы
      tft.setTextSize(2);
      tft.setTextColor(SILVER, BLACK);
      tft.setCursor(50,10);
      DateTime now = RTC.now();
      tft.print(now.day(), DEC);
      tft.print('/');
      tft.print(now.month(), DEC);
      tft.print('/');
      tft.print(now.year(), DEC);
      tft.println(' ');
      tft.setCursor(30,35);
      tft.setTextSize(3);
      //tft.setFont(DGR);
      tft.setTextColor(BLUE, BLACK);
      tft.print(now.hour(), DEC);
      tft.print(':');
      tft.print(now.minute(), DEC);
      tft.print(':');
      tft.print(now.second(), DEC);
      tft.println(" ");

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.getHumidity();
    float t = dht.getTemperature();
    float p = sensor.pres; //for BMP180 uncomment
    float T = sensor.temp;

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    if(sensor.read())    {Serial.println((String)"CEHCOP BMP180: P="+sensor.pres+" MM.PT.CT - T="+sensor.temp+" *C - B="+sensor.alti+" M.");}
        else            {Serial.println(    "CEHCOP BMP180: HET OTBETA");}
        delay(3000);
    // Прорисовка блоков
    // Верхний блок для часов
      tft.fillRect(0, 0, 240, 2, WHITE); //1UH
      tft.fillRect(2, 2, 236, 2, BLUE); //2UH
      tft.fillRect(4, 4, 233, 2, RED); //3UH
      tft.fillRect(4, 63, 233, 2, RED); //1LH
      tft.fillRect(2, 65, 236, 2, BLUE); //2LH
      tft.fillRect(0, 67, 240, 2, WHITE); //3LH
      tft.fillRect(0, 0, 2, 67, WHITE); //1LEFTV
      tft.fillRect(2, 2, 2, 63, BLUE); //2LEFTV
      tft.fillRect(4, 4, 2, 59, RED); //3LEFTV
      tft.fillRect(235, 4, 2, 59, RED); //1RV
      tft.fillRect(237, 2, 2, 63, BLUE); //2RV
      tft.fillRect(239, 0, 2, 67, WHITE); //3RV
      // Блок температуры
      tft.fillRect(0, 69, 240, 3, GREEN); //1H
      tft.fillRect(0, 92, 240, 3, GREEN); //2H
      tft.fillRect(0, 115, 240, 3, GREEN); //3H
      tft.fillRect(0, 153, 240, 3, GREEN);//4H
      tft.fillRect(0, 68, 3, 88, GREEN); //LEFTV
      tft.fillRect(120, 92, 3, 62, GREEN); //MIDV
      tft.fillRect(237, 68, 3, 88, GREEN); //RV
      //Блок Влажности
      tft.fillRect(0, 155, 240, 3, BLUE); //1H
      tft.fillRect(0, 178, 240, 3, BLUE); //2H
      tft.fillRect(0, 220, 240, 3, BLUE);//3H
      tft.fillRect(0, 155, 3, 68, BLUE); //LEFTV
      tft.fillRect(237, 155, 3, 68, BLUE); //RV
      //Блок Давления
      tft.fillRect(0, 224, 240, 3, RED); //1H
      tft.fillRect(0, 247, 240, 3, RED); //2H
      tft.fillRect(0, 289, 240, 3, RED);//3H
      tft.fillRect(0, 224, 3, 68, RED); //LEFTV
      tft.fillRect(237, 224, 3, 68, RED); //RV
      //Показания датчиков
    tft.setTextSize(3);
    tft.setTextColor(WHITE, BLACK);
    tft.setCursor(20, 125);
    tft.println(t);
    tft.setCursor(140, 125);
    tft.println(T);
    tft.setCursor(60, 190);
    tft.println(h);
    tft.setCursor(60, 258);
    tft.println(p);

    // wait for a moment
    //delay(3000);
    // erase the text you just wrote
    //tft.setTextColor(BLACK);
    //tft.setCursor(60, 100);
    //tft.println(tempPrintout);
    //tft.setCursor(130, 100);
    //tft.println((float)sensor.temp);
    //tft.setCursor(60, 180);
    //tft.println(humPrintout);
    //tft.setCursor(60, 260);
    //tft.println(sensor.pres);
    //tft.fillRect(50, 25, 150, 25, BLACK);

    }

    //Rounds down (via intermediary integer conversion truncation)
    String doubleToString(double input,int decimalPlaces){
    if(decimalPlaces!=0){
    String string = String((int)(input*pow(10,decimalPlaces)));
    if(abs(input)<1){
    if(input>0)
    string = "0"+string;
    else if(input<0)
    string = string.substring(0,1)+"0"+string.substring(1);
    }
    return string.substring(0,string.length()-decimalPlaces)+"."+string.substring(string.length()-decimalPlaces);
    }
    else {
    return String((int)input);
    }
    }
     
  2. AlexVS

    AlexVS Гик

    Так пойдет?
    Код (C++):
    if (t < -10)
    {tft.setTextColor(BLUE, BLACK);}
    else if (t < 0)
    {tft.setTextColor(CYAN, BLACK);}
    else if (t == 0)
    {tft.setTextColor(MAGENTA, BLACK);}
    else if (t > 0)
    {tft.setTextColor(RED, BLACK);}
     
    Dioskuri нравится это.
  3. Megakoteyka

    Megakoteyka Оракул Модератор

    Либо как AlexVS говорит, либо вычислять компоненты цвета по формуле в зависимости от температуры, тогда цвет будет меняться плавно.
     
  4. Dioskuri

    Dioskuri Нерд

    Сейчас попробую как посоветовал AlexVS, но конечно же хотелось бы плавное изменение.
     
  5. Megakoteyka

    Megakoteyka Оракул Модератор

    А в чем проблема? Не получается формулу составить?
     
  6. Dioskuri

    Dioskuri Нерд

    Честно говоря, даже не знаю как её родимую и составлять то. Может направите на путь истинный? Буду крайне признателен!
     
  7. Dioskuri

    Dioskuri Нерд

    Да, все получилось. Спасибо!
     
  8. Megakoteyka

    Megakoteyka Оракул Модератор

    У вас цвет состоит из 3-х компонент - RGB.
    Можно менять яркость каждого компонента цвета отдельно. Например, при повышении температуры прибавлять красного и убавлять синий, а зеленый всегда нулем держать.
    У вас в коде определены базовые цвета:
    Код (C++):
    #define    BLUE        0x001F
    #define    RED          0xF800
    #define    GREEN     0x07E0
    Исходя из этой записи, получается 5 бит на синий, 5 на красный и 6 на зеленый.
    Чтобы собрать цвет из компонент, можно использовать такой макрос:
    Код (C++):
    #define COLOR(r, g, b)  ((((r) & 0x1F) << 11) | (((g) & 0x3F) << 5) | ((b) & 0x1F))
    Этот макрос можно использовать в коде как функцию, передавая в него значения компонентов цвета.
    Красный и синий могут меняться от 0 до 31, а зеленый - от 0 до 63.
    Формула должна получать на вход температуру и возвращать значение цвета. Фактически нужны 3 формулы - для каждого компонента цвета своя.
    Формулы должны выдавать цвет RGB=0,0,31 для самой низкой температуры и RGB=31,0,0 для самой высокой.
    Можно, например, подобрать формулу так, чтобы она обрабатывала диапазон температур от -10 до +22 и на входе формулы подправлять реальное значение температуры. Тогда для 32-х разных значений температуры получится 32 разных цвета - от синего через фиолетовый к красному.
    Код (C++):
    uint16_t ColorFromTemp(int temp)
    {
      if(temp < -10)
        temp = -10;
      if(temp > 22)
        temp = 22;
      t += 10;
      int r = t;
      int g = 0;
      int b = 31 - t;
      return COLOR(r, g, b);
    }
    Или в более лаконичном виде:
    Код (C++):
    uint16_t ColorFromTemp(int temp)
    {
      t += 10;
      if(temp > 31)
        temp = 31;
      return COLOR(t, 0, 31 - t);
    }
    Надеюсь, принцип понятен, функцию преобразования температуры в цвет можете подправить по вкусу.
     
    Dioskuri, AlexVS и vvr нравится это.
  9. AlexVS

    AlexVS Гик

    Сам подход и пример кода интересен! А на практике, вряд ли маленький дисплейчик в полной мере сможет отразить плавный переход цвета при изменении темпертуры. Хотя если использовать его при построении графика изменения температуры, ну скажем за сутки, то тогда это будет более наглядно.
    Надо самому попробывать с графиком.
     
  10. Megakoteyka

    Megakoteyka Оракул Модератор

    Если крупно выводить показания, то должно быть видно нормально, а для графика оно вроде и ни к чему, на графике и так все наглядно.
     
  11. Dioskuri

    Dioskuri Нерд

    Спасибо! Принцип понятен, но с воплощением проблемка. Теперь компилятор ругается:
    Meteo_TFT_NEW.ino: In function 'void loop()':
    Meteo_TFT_NEW.ino:55:82: error: return-statement with a value, in function returning 'void' [-fpermissive]
    Meteo_TFT_NEW.ino:235:10: note: in expansion of macro 'COLOR'
    Meteo_TFT_NEW.ino:237:24: error: 'r' was not declared in this scope

    Подскажите, где мне r, g, b задекларировать?
     
  12. Megakoteyka

    Megakoteyka Оракул Модератор

    error: return-statement with a value, in function returning 'void' - функция возвращает значение, но объявлена как void (т.е. как не возвращающая значение).
    Их не надо никак объявлять, макрос разворачивается прямо в исходнике.
    Например, объявлен такой макрос:
    Код (C++):
    #define SUM(a, b)  ((a) + (b))
    В программе пишем:
    Код (C++):
    int x = SUM(1 + 2, 5 - 3);
    Препроцессор развернет макрос так:
    Код (C++):
    int x = ((1 + 2) + (5 - 3));
    И уже эта строка пойдет на вход компилятору.
    То есть макрос - это просто подстановка текста с параметрами.

    Тащите сюда код, разберемся.
     
  13. Dioskuri

    Dioskuri Нерд

    Код (C++):

    #include "SPI.h"
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_TFTLCD.h> // Hardware-specific library
    #include <Wire.h>
    #include <BMP180.h>
    #include "DHT.h"
    #include "RTClib.h"
    #define USE_ADAFRUIT_SHIELD_PINOUT

    // The control pins for the LCD can be assigned to any digital or
    // analog pins...but we'll use the analog pins as this allows us to
    // double up the pins with the touch screen (see the TFT paint example).
    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0

    #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
    // Assign human-readable names to some common 16-bit color values:
    #define    BLACK        0x0000
    #define    BLUE         0x001F
    #define    RED          0xF800
    #define    GREEN        0x07E0
    #define CYAN         0x07FF
    #define MAGENTA      0xF81F
    #define YELLOW       0xFFE0
    #define WHITE        0xFFFF
    #define NAVY         0x000F
    #define DARKGREEN    0x03E0
    #define ORANGE       0xFD20
    #define GREENYELLOW  0xAFE5
    #define PINK         0xF81F
    #define SILVER       0xC618

    // Модуль часов
    RTC_DS1307 RTC;
    DateTime now;
    DateTime time_old;
    DateTime date_old;
    boolean night_mode=true;
    // Сенсоры
    BMP180    sensor;
    DHT dht;
    #define DHTPIN 12
    // char array to print to the screen
    char tempPrintout[6];
    char humPrintout[6];
    char presPrintout[6];

    int cycleTime = 2000;
    // Meter colour schemes
    #define COLOR(r, g, b) ((((r) & 0x1F) << 11) | (((g) & 0x3F) << 5) | ((b) & 0x1F))

    void setup() {

    Serial.begin(9600);
      Serial.println(F("TFT LCD test"));
      Serial.println("DHT test!");
      Wire.begin();
      RTC.begin();
      dht.setup(12);  //DHT start
      sensor.begin();  // BMP start

    if (! RTC.isrunning()) {
        // Установка актуального времени и даты
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }
    #ifdef USE_ADAFRUIT_SHIELD_PINOUT
      Serial.println(F("Using Adafruit 2.8\" TFT Arduino Shield Pinout"));
    #else
      Serial.println(F("Using Adafruit 2.8\" TFT Breakout Board Pinout"));
    #endif

      Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height());
      tft.reset();
      uint16_t identifier = tft.readID();

      if(identifier == 0x9325) {
        Serial.println(F("Found ILI9325 LCD driver"));
      } else if(identifier == 0x9327) {
        Serial.println(F("Found ILI9327 LCD driver"));
      } else if(identifier == 0x9328) {
        Serial.println(F("Found ILI9328 LCD driver"));
      } else if(identifier == 0x7575) {
        Serial.println(F("Found HX8347G LCD driver"));
      } else if(identifier == 0x9341) {
        Serial.println(F("Found ILI9341 LCD driver"));
      } else if(identifier == 0x8357) {
        Serial.println(F("Found HX8357D LCD driver"));
      } else if(identifier == 0x0154) {
        Serial.println(F("Found S6D0154 LCD driver"));
      } else if(identifier == 0x9488) {
        Serial.println(F("Found ILI9488 LCD driver"));
    } else {
        Serial.print(F("Unknown LCD driver chip: "));
        Serial.println(identifier, HEX);
        Serial.println(F("If using the Adafruit 2.8\" TFT Arduino shield, the line:"));
        Serial.println(F("  #define USE_ADAFRUIT_SHIELD_PINOUT"));
        Serial.println(F("should appear in the library header (Adafruit_TFT.h)."));
        Serial.println(F("If using the breakout board, it should NOT be #defined!"));
        Serial.println(F("Also if using the breakout, double-check that all wiring"));
        Serial.println(F("matches the tutorial."));
        return;
      }

      tft.begin(identifier);

    // Вывод черного фона на экран
    tft.fillScreen(BLACK);
    // Вывод статического текста на экран
    tft.setTextColor(SILVER); // Установка цвета шрифта
    tft.setTextSize(2); // Установка размера шрифта
    tft.setCursor(40, 74); // Установка координат начала текста
    tft.println("Temperatura: C");
    tft.setCursor(55, 98);
    tft.println("IN");
    tft.setCursor(168, 98);
    tft.println("OUT");
    tft.setTextColor(SILVER);
    tft.setCursor(40, 170);
    tft.println("Vlazhnost: %");
    tft.setTextColor(SILVER);
    tft.setCursor(40, 250);
    tft.println("Davlenie:mmHg");

    }

    void loop() {
       // Дата и Часы
      tft.setTextSize(2);
      tft.setTextColor(SILVER, BLACK);
      tft.setCursor(50,10);
      DateTime now = RTC.now();
      tft.print(now.day(), DEC);
      tft.print('/');
      tft.print(now.month(), DEC);
      tft.print('/');
      tft.print(now.year(), DEC);
      tft.println(' ');
      tft.setCursor(30,35);
      tft.setTextSize(3);
      //tft.setFont(DGR);
      tft.setTextColor(BLUE, BLACK);
      tft.print(now.hour(), DEC);
      tft.print(':');
      tft.print(now.minute(), DEC);
      tft.print(':');
      tft.print(now.second(), DEC);
      tft.println(" ");

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.getHumidity();
    float t = dht.getTemperature();
    float p = sensor.pres; //for BMP180 uncomment
    float T = sensor.temp;

    uint16_t ColorFromTemp(int temp);
    {
      if(temp < -10)
       temp = -10;
      else if(temp > 22)
        temp = 22;
      T += 10;
      int r = T;
      int g = 0;
      int b = 31 - T;
      return COLOR(r, g, b);
    }

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    if(sensor.read())    {Serial.println((String)"CEHCOP BMP180: P="+sensor.pres+" MM.PT.CT - T="+sensor.temp+" *C - B="+sensor.alti+" M.");}
        else            {Serial.println(    "CEHCOP BMP180: HET OTBETA");}
        delay(3000);
    // Прорисовка блоков
    // Верхний блок для часов
      tft.fillRect(0, 0, 240, 2, WHITE); //1UH
      tft.fillRect(2, 2, 236, 2, BLUE); //2UH
      tft.fillRect(4, 4, 233, 2, RED); //3UH
      tft.fillRect(4, 63, 233, 2, RED); //1LH
      tft.fillRect(2, 65, 236, 2, BLUE); //2LH
      tft.fillRect(0, 67, 240, 2, WHITE); //3LH
      tft.fillRect(0, 0, 2, 67, WHITE); //1LEFTV
      tft.fillRect(2, 2, 2, 63, BLUE); //2LEFTV
      tft.fillRect(4, 4, 2, 59, RED); //3LEFTV
      tft.fillRect(235, 4, 2, 59, RED); //1RV
      tft.fillRect(237, 2, 2, 63, BLUE); //2RV
      tft.fillRect(239, 0, 2, 67, WHITE); //3RV
      // Блок температуры
      tft.fillRect(0, 69, 240, 3, WHITE); //1H
      tft.fillRect(0, 92, 240, 3, WHITE); //2H
      tft.fillRect(0, 115, 240, 3, WHITE); //3H
      tft.fillRect(0, 161, 240, 3, WHITE);//4H
      tft.fillRect(0, 69, 3, 92, WHITE); //LEFTV
      tft.fillRect(120, 92, 3, 69, WHITE); //MIDV
      tft.fillRect(237, 69, 3, 92, WHITE); //RV
      //Блок Влажности
      tft.fillRect(0, 164, 240, 3, BLUE); //1H
      tft.fillRect(0, 190, 240, 3, BLUE); //2H
      tft.fillRect(0, 241, 240, 3, BLUE);//3H
      tft.fillRect(0, 164, 3, 88, BLUE); //LEFTV
      tft.fillRect(237, 164, 3, 88, BLUE); //RV
      //Блок Давления
      tft.fillRect(0, 244, 240, 3, RED); //1H
      tft.fillRect(0, 270, 240, 3, RED); //2H
      tft.fillRect(0, 317, 240, 3, RED);//3H
      tft.fillRect(0, 244, 3, 88, RED); //LEFTV
      tft.fillRect(237, 244, 3, 88, RED); //RV
      //Показания датчиков
      //Температура в комнате
    tft.setTextSize(3);
    if (t < -10)
    {tft.setTextColor(BLUE, BLACK);}
    else if (t < 0)
    {tft.setTextColor(CYAN, BLACK);}
    else if (t == 0)
    {tft.setTextColor(MAGENTA, BLACK);}
    else if (t > 25)
    {tft.setTextColor(RED, BLACK);}
    else if (t > 22)
    {tft.setTextColor(ORANGE, BLACK);}
    tft.setCursor(20, 130);
    tft.println(t);
    //Температура на улице
    tft.setTextColor(COLOR(r, g, b), BLACK);
    //if (T < -5)
    //{tft.setTextColor(SILVER, BLACK);}
    //else if (T < 0)
    //{tft.setTextColor(CYAN, BLACK);}
    //else if (T == 0)
    //{tft.setTextColor(NAVY, BLACK);}
    //else if (T > 23)
    //{tft.setTextColor(RED, BLACK);}
    //else if (T > 21)
    //{tft.setTextColor(ORANGE, BLACK);}
    //else if (T > 15)
    //{tft.setTextColor(GREEN, BLACK);}
    tft.setCursor(140, 130);
    tft.println(T);
    //Влажность в квартире
    if (h > 80)
    {tft.setTextColor(SILVER, BLACK);}
    else if (h > 70)
    {tft.setTextColor(CYAN, BLACK);}
    else if (h > 60)
    {tft.setTextColor(NAVY, BLACK);}
    else if (h < 30)
    {tft.setTextColor(RED, BLACK);}
    else if (h < 40)
    {tft.setTextColor(ORANGE, BLACK);}
    else if (h < 50)
    {tft.setTextColor(GREEN, BLACK);}
    tft.setCursor(70, 205);
    tft.println(h);
    //Атмосферное давление
    if (p > 760)
    {tft.setTextColor(RED, BLACK);}
    else if (h > 755)
    {tft.setTextColor(CYAN, BLACK);}
    else if (h > 750)
    {tft.setTextColor(SILVER, BLACK);}
    tft.setCursor(70, 285);
    tft.println(p);

    }

    //Rounds down (via intermediary integer conversion truncation)
    String doubleToString(double input,int decimalPlaces){
    if(decimalPlaces!=0){
    String string = String((int)(input*pow(10,decimalPlaces)));
    if(abs(input)<1){
    if(input>0)
    string = "0"+string;
    else if(input<0)
    string = string.substring(0,1)+"0"+string.substring(1);
    }
    return string.substring(0,string.length()-decimalPlaces)+"."+string.substring(string.length()-decimalPlaces);
    }
    else {
    return String((int)input);
    }
    }
     
    Последнее редактирование: 9 окт 2015
  14. Megakoteyka

    Megakoteyka Оракул Модератор

    Код (C++):
    uint16_t ColorFromTemp(int temp)
    {
      if(temp < -10)
       temp = -10;
      else if(temp > 22)
        temp = 22;
      temp += 10;
      int r = temp;
      int g = 0;
      int b = 31 - temp;
      return COLOR(r, g, b);
    }
     
  15. Megakoteyka

    Megakoteyka Оракул Модератор

    Неправильно:
    Код (C++):
    //Температура на улице
    tft.setTextColor(COLOR(r, g, b), BLACK);
    Правильно:
    Код (C++):
    //Температура на улице
    tft.setTextColor(ColorFromTemp(t), BLACK);
    Понятно, почему именно так?
     
  16. Dioskuri

    Dioskuri Нерд

    Вот теперь понятно! Вроде заработало. Спасибо!
     
  17. Megakoteyka

    Megakoteyka Оракул Модератор

    Даже цвет нормально меняется?
     
  18. Dioskuri

    Dioskuri Нерд

    Пока, честно говоря не очень, но продолжаю экспериментировать. Попробую сегодня поиграть с цифрами.
     
  19. Dioskuri

    Dioskuri Нерд

    Цвета меняются нормально, но переходы не красивые. Лучше получается если изменять не только синий, но и зелёный цвет допустим так:
    Код (C++):
    if(temp < -10)
       temp = -10;
      else if(temp > 22)
       temp = 22;
      temp += 15;
      int r = temp;
      int g = 20 - temp;
      int b = 31 - temp;
    Тогда смена цветов более естественная для температуры, от холодного голубого к красному через оранжевый и т.д.
     
    Megakoteyka нравится это.
  20. FlameWind

    FlameWind Нерд

    Тоже замарочился данным вопросом. Пробовал разные варианты, и тот который тут.
    Но нашел описание функции map. И прикрутил в свой проект такой вариант:
    Код (C++):
    if (Temp <= 19) { TempColor = tft.Color565(? ? ?); }
        else if (Temp >= 20 and Temp <= 27) { TempColor = TempColor = tft.Color565(map(Temp, 20, 27, 223, 255), map(Temp, 20, 27, 223, 159), map(Temp, 20, 27, 0, 7)); }
          else if (Temp >= 28) { TempColor = tft.Color565(? ? ?); }
    В нижнем и верхнем пределах нужно подбирать цвета.