Cada clima es bueno: un indicador del clima que cosplay



Imaginemos que después de una escaramuza con Dave Bowman, los restos de la inteligencia una vez poderosa de HAL 9000 fueron suficientes para traer Discovery One de vuelta a la Tierra y, bajo el lema "muerte a todas las personas", aplastarlo en el planeta, para que no sea más malo hacer esto con las computadoras.

El cataclismo que estalló, por supuesto, destruyó a toda la humanidad racional, y solo quedaron individuos como yo, con un martillo en una mano y un Arduino en la otra. Por lo tanto, no es sorprendente que el misterioso dispositivo encontrado por los restos aún misteriosos de la nave espacial que se encuentra en la montaña solo se pueda usar en una estación meteorológica. Bueno, con razón!

Si descartamos el romance, la dura realidad de la vida fue que el notorio ITEAD ofreció la pantalla Nextion HMI NX4832T035 para probar .

Dado que los productos de Nextion se han descrito repetidamente aquí, es conciso sobre sus capacidades. Esta es una pantalla con su propia API simple y panel táctil para hacer unidades de control con menús gráficos sin mucha molestia.

Para este propósito, Nextion tiene un sistema de comando simple para mostrar imágenes (y sus partes), elementos de texto, campos de entrada, gráficos. Además, hay un tipo de lenguaje de script para realizar acciones, por ejemplo, presionando los botones en pantalla o por temporizador. Y al mismo tiempo, un puerto para recibir comandos externos de microcontroladores o similares y devolver datos sobre tocar la pantalla para saber a qué botones llegaron las manos juguetonas del propietario y en qué estado se encuentra este botón (presionado, liberado) en este momento.

En términos generales, no hay necesidad de sufrir y recopilar conjuntos de puntos o conectar una nube de todo tipo de bibliotecas. Una línea, y el fondo ha cambiado en la pantalla. Al hacer clic, se abre un menú. Conectamos Arduino: construimos gráficos de acuerdo con los datos recibidos a través del puerto serie.

Es decir, a juzgar por la descripción, la pantalla es tan inteligente que puede mostrar y responder (hay un panel táctil) a cualquier cosa. Pero no tengo nada en casa, pero los datos climáticos vuelan periódicamente por el aire. Desde el mismo BDS-M , por ejemplo, o desde el sensor meteorológico PI-TV-2 .

Por supuesto, todos ellos se transfieren finalmente a Monitoreo de personas , desde donde tengo la suerte de verlos a través de un navegador o una aplicación en mi teléfono inteligente. Pero no pude resistir la idea de hacer "otra estación meteorológica en el Arduino".

Y, para ser honesto, no era tanto una cuestión de tecnología como tal, sino del hecho de que me atraía obstinadamente diseñar interfaces. Probablemente, tira con la misma fuerza con la que tira para cantar a todos a quienes el oso le ha pisado la oreja.

Por lo tanto, me disculpo de inmediato por el hecho de que habrá menos equipos más y más fantasías de fantasía. Pero primero, una pequeña demostración del producto terminado, según la cual puede decidir, seguir leyendo o pasar al siguiente material.



Entonces, tenía 3.5 pulgadas, 480x320 píxeles, lo que parecía una API bastante simple y siete parámetros que debían mostrarse (entre paréntesis están los sensores unidos a esto):

1) La temperatura interior y exterior (BMP085 / DHT22)
2) La humedad dentro y exterior (DHT22 / DHT22)
4) Presión atmosférica (BMP085)
5) La concentración de gases no muy útiles en la habitación, especialmente CO2 (MQ135)
6) La concentración de sólidos en el aire de la habitación, especialmente PM2.5 (Sharp GP2Y1010AU0F)

Aquí debe notarse que los camaradas que se han familiarizado con las características de los últimos dos sensores concluyen que la mayor respuesta se logra solo en el campo de CO2 y PM2.5, respectivamente. Esto, de hecho, explica mi elección: no es una pena gastar dos centavos y ver qué sucede, mientras que los sensores especializados son mucho más caros y, en caso de falla, el sapo siempre tiene algo que mostrar.

Está claro que no esperaba mucha precisión de los sensores baratos; más bien, esperaba correlacionar mis propios sentimientos con sus lecturas. Y, por cierto, todo es bastante obvio: vale la pena cerrar la ventana, ya que al mismo tiempo que aumenta la temperatura y la congestión, los valores de concentración de gas de MQ135 comienzan a aumentar.

Sin embargo, a los parámetros. Me pareció aburrido mostrar solo siete dígitos, por lo tanto, la tarea técnica para el dispositivo se expandió: se me ocurrió que cada parámetro mostrara un gráfico de cambios a lo largo del tiempo. Y para que en una pantalla fuera posible ver hasta cuatro curvas al mismo tiempo para la percepción visual de los patrones (si los hay) en los cambios en varios indicadores.

Un lector atento y propietario de cualquier dispositivo portátil con una diagonal de 3.5 pulgadas o más, probablemente dirá que no hay nada complicado en esto. Al igual, en tal pantalla y más datos encajarán fácilmente.

Pero hay un truco: para un electrodoméstico, los números y las firmas deben ser lo más grandes posible para que no tengan que mirar la pantalla durante mucho tiempo con una lupa, tratando de perforar la mente del creador.

En general, quería la interfaz más grande y no demasiado desordenada, cuya lógica podría entenderse sin una educación superior. Teniendo esa imagen en mi cabeza, la transferí al editor de Nextion y obtuve dos tipos principales de pantalla.

Pantalla principal con lecturas actuales de sensores:




Además de las lecturas reales, también puede ver una indicación de la tendencia de cambio (arriba / abajo) y marcadores de parámetros seleccionados para mostrar en el gráfico. Los cuadrángulos translúcidos son las áreas sensoriales invisibles en el trabajo.

Pantalla con gráficos. En realidad, hay cuatro de ellos para mostrar de uno a cuatro gráficos, pero de hecho, todos son idénticos. Por ejemplo, una pantalla con uno y cuatro gráficos:




Aquí, para cada parámetro, también se muestran su máximo y mínimo para comprender los límites. Pero no hay una línea de tiempo: en primer lugar, el dispositivo no tiene reloj y, en segundo lugar, simplemente no hay lugar para la báscula. Al menos no encontré dónde adjuntarlo, dado que quería mostrar un máximo de cuatro gráficos.

En este caso, el código prevé la adición de los indicadores obtenidos al archivo cada media hora con una profundidad total de archivo de 48 valores, es decir por alrededor de un día Aproximadamente, debido a que los datos se transmiten a través del canal de radio de 433 MHz, que no está protegido de la interferencia, por lo que son posibles huecos.

Y en el caso de estas brechas, el tiempo de vida de los sensores también se proporciona en la misma media hora. Y si no hubo recepción de datos en media hora, las lecturas del sensor no se muestran y no se ingresan en el archivo.

Las tendencias en los indicadores se calculan mediante el primer algoritmo que aparece en los últimos seis puntos de la historia, es decir. de acuerdo con las seis indicaciones más recientes. Y dado que las lecturas se realizan a intervalos de media hora, resulta que la tendencia refleja cambios en las últimas tres horas.

Como cualquier diseñador, tuve que "jugar con las fuentes". En el proceso de dibujar las opciones, resultó que mi simetría favorita se vio obligada a romperse no solo por la combinación de indicadores de humedad en la esquina superior derecha, sino también por un fenómeno mucho más decepcionante en forma de temperaturas negativas.

Es decir, los inconvenientes estropearon toda la imagen. Por lo tanto, actué a mi manera: coloque un signo negativo sobre el valor. Para los matemáticos, esto, por supuesto, parecerá una solución bárbara, y los involucrados, por supuesto, se estremecerán involuntariamente, reflexionando sobre por qué las estaciones meteorológicas deben ser moduladas. Pero resultó bastante bien y los números no bailan.

La lógica de la interfaz es la siguiente. El modo de funcionamiento principal es el modo de espera con un brillo de pantalla del 15% del valor nominal y actualización periódica de las lecturas.

Toque en cualquier lugar: conéctese con un brillo del 100% Después de esto, al hacer clic en las lecturas, selecciónelas para su posterior visualización en el gráfico, y al hacer clic en el "ojo", HAL cambia a la pantalla con gráficos.

Hay exactamente cinco segundos para esto. Luego se borran las marcas, y después de otros cinco minutos de inactividad, el dispositivo vuelve al modo de espera.

En la pantalla del gráfico, la parte izquierda es un paso hacia atrás (la pantalla principal o la pantalla con gráficos), y la parte derecha es un aumento en el gráfico seleccionado en pantalla completa o, de nuevo, vaya a la pantalla principal si hay un gráfico.

Me pareció que este esquema es lo suficientemente simple como para no agregar botones adicionales, lo que realmente no quiero ver aquí.

Por cierto, las imágenes de fondo se pueden cambiar si se desea. Incluso preparé algunas opciones adicionales.

Para colonos:


Para hobbits:


Para los románticos:


Para los amantes del café:


En concepto, todo el dispositivo no es tanto una estación meteorológica como una pantalla inalámbrica especializada. Por lo tanto, el diseño es extremadamente simple: solo la pantalla, el Arduino Pro Mini y el receptor de 433 MHz con modulación de amplitud están dentro. No hay características en el ensamblaje en absoluto: la pantalla es para alimentación y puerto serie, el receptor es para alimentación y el pin 2 del controlador. Y, aparte de la necesidad de sensores externos compatibles, eso es todo.

Para comprender la simplicidad, muestro una de las opciones de alojamiento con un relleno casi instalado: por





supuesto, no insisto en dicha configuración, pero en mi caso fue óptima tanto en términos de laboriosidad como de compatibilidad con otros componentes de la automatización del hogar.

Bueno, la separación de la pantalla y los sensores le permite colocar esta misma pantalla en el lugar más conveniente, como, de hecho, cualquier estación meteorológica con sensores externos.

Por supuesto, para que todo esto funcione y no cause horror animal al ver trozos de cables, un montón de sensores y microcontroladores colgando en el aire, debe resolver los casos.

La dura verdad de la vida era que la caja donde BDS-M había vivido hasta ahora no podía acomodar tres sensores adicionales. Por lo tanto, di rienda suelta a los sentimientos e imprimí una impresionante lámpara de Markellov .

Desde el punto de vista del sensor meteorológico, es ideal, ya que es arrastrado por todos los vientos y al mismo tiempo oculta el desorden de manera efectiva y efectiva. Después de tales metamorfos, BDS-M dejó de existir: ahora es glamoroso (si no te acercas) Multisensor:

Shell:



montado y en su lugar:



resultó ser más difícil con la unidad de visualización. En general, quería verlo bastante masivo y brutal. Bueno, por supuesto, como si el aborigen que había encontrado parte de la nave espacial lo enmarcara en piedra. Por lo tanto, el marco, cuyo modelo ya se ofrecía en Nextion, no se ajustaba de ninguna manera. En primer lugar, daba miedo, y en segundo lugar, la pantalla estaba en un hueco allí, lo que categóricamente no me convenía: quería enjuagarme con la superficie.

Empecé, sin embargo, de todos modos con plástico, solo para romper la forma. Las opciones intermedias se parecían a esto:



en general, me gustó (decidí no notar un poco de descontento), pero el peso, por supuesto, es bastante ridículo, no de piedra. Por lo tanto, uno de los edificios utilizado como encofrado interno para la fabricación de hormigón "marco".

El proceso me sorprendió hasta la médula: rara vez criaba tanta suciedad en casa. El resultado es el mismo. Aunque en algunos lugares resultó ser incluso nada, resultó que la mezcla de reparación reforzada no es muy adecuada para tales productos.

Quizás el concreto de arena pura sería ideal, pero en este momento ya estaba decepcionado de mis propias habilidades de construcción y me puse en camino como lo es mi colega. Y él, habiendo pensado un poco, dijo que tuvo la felicidad en su vida de trabajar con pintura en aerosol debajo de la piedra.

Bingo, pensé para mí mismo, e inmediatamente comencé a sacar los detalles. Después de todo, imprimir un estuche y pintarlo es mucho más estético que convertir una casa en un sitio de construcción de gran tamaño. En general, la pintura era inhumanamente costosa, pero muy fresca (para aquellos interesados ​​- Rust-Oleum American Accents Stone).

En el camino, también llegué a la conclusión de que, sin embargo, no me gustaba el cuerpo con algo (muy probablemente, con marcos gruesos en todo el perímetro), por lo que me recuperé y, después del interrogatorio con una adicción, llegué a una forma aparentemente final.

Fue: se



convirtió en:







Es fácil ver que no hay rastro de masividad, pero por alguna razón esta forma es de mi agrado. Me detendré en eso. Adios

La vista, por supuesto, es un aficionado, ya que se ven algunos despojos de la pantalla (el mismo bucle del panel táctil), y no se puede hacer nada de esto de manera razonable. Irrazonable, en mi opinión, - superposiciones, pintura, cintas adhesivas.

Y como imprimí con plástico transparente, por la noche en el espacio general:



Ahora sobre algunos, digamos, los matices del diseño. Empezaré, tal vez, desde el mismo edificio. El deseo de belleza jugó un chiste malo: como quería que la pantalla estuviera al ras de la superficie, el recorte se hizo lo más posible correspondiente a las dimensiones externas de la pantalla. Y después de aproximadamente una docena de accesorios, hizo su trabajo: rompió el cable del panel táctil o rompió el contacto con la placa, pero ahora es muy difícil hacer que el sensor funcione.

Por lo tanto, probablemente no puedo recomendar tal diseño. Bueno, o lo recomiendo, pero tenga en cuenta que esta es una de las formas más fáciles y hermosas (sí, me halago descaradamente) para romper la pantalla.

Además, tuve que repasar varias características de la pantalla en sí, una descripción de la cual personalmente puedo encabezar como "no puedes tomarlo y ...".

Entonces, uno no puede simplemente levantar y mostrar cualquier fuente. Es decir, teóricamente, sí. Cualquier fuente de Windows se puede descargar en el convertidor integrado en el entorno de Nextion y la salida será una trama bastante dentuda que no se verá mejor.

Por ejemplo, compare la fuente convertida con la original:


Por lo tanto, tuve que ir por el triste camino. A saber: para componer números y firmas a partir de elementos gráficos previamente preparados en GIMP.

Luego me topé con las listas. Resultó que no puede simplemente tomar y alimentar un conjunto de datos arbitrarios al elemento de forma de onda destinado a dibujar curvas. Primero, debe llevar todo al formato requerido: de 0 a 255 y terminar los puntos intermedios, si hay menos del ancho de la pantalla.

Bueno, entonces descubrí que eso no es todo. Resulta que la pantalla no escala 255 puntos lógicos cuando cambia la altura del elemento del gráfico de forma de onda. Por lo tanto, al cambiar la altura del elemento del gráfico de forma de onda, es necesario cambiar proporcionalmente la escala de los valores, de lo contrario, el gráfico se "cortará".

Aún así, no puede usar imágenes con un fondo transparente, lo que limita un poco el ancho útil de los campos de información, de modo que no haya una superposición fea en el área de degradado de la imagen de fondo. En mi opinión, el foro de Nextion discutió esto y parece que ITEAD prometió agregar la capacidad de trabajar con imágenes transparentes, pero aún no lo ha hecho.

Esto, como mi tormento al cambiar la velocidad del puerto (que es necesario para el dibujo rápido de gráficos), sin duda, parecerá ridículo para los camaradas experimentados. Sin embargo, no puedo permanecer en silencio: gasté decentemente las fuerzas para vencer.

Pero en general me siento como un ganador. Lo que quería, lo hice, y la colección de electrodomésticos se reponía con otra. Además, no es del todo inútil: es conveniente ver de inmediato lo que muestran los sensores domésticos sin alcanzar un teléfono inteligente y no encender una computadora.

Además, esto no depende de Internet y en este contexto parece un dispositivo anti-IoT, ya que almacena todo en sí mismo. Y luego me imagino, como si un pirata informático con un sentido del humor absurdo cortara mi estación meteorológica y la hiciera cerrar la puerta.

Luego me raspaba afuera con solicitudes como:

- Abrir las puertas de la bahía de Pod, HAL

Verdadero, ¿sería divertido?

PD En la fabricación del dispositivo se guiaron los manuales:

" Solución Nextion HMI
" FLProg + Nextion HMI. Lección 1
» FLProg + Nextion HMI. Lección 2
» FLProg + Nextion HMI. Lección 3

que también puedo ofrecer:

" El diseño de la interfaz para editar en Nextion Editor
"Mostrar archivo de interfaz de descarga

Mostrar código de pieza para Arduino
// v5:     Serial - Arduino, Serial1 - Nextion
// v6:  
// v7:     
// v8:      ( ,    ,  )
// v9:       DHT.h Adafruit
// v10:     ,      
// v11:    CO2/PM2.5
// v12:     , reDraw   statusBoolean = true
// ToDo:   40 ,     ,     (  )


#include <DHT.h>
#include <RCSwitch.h> //   http://code.google.com/p/rc-switch/
#include <MQ135.h> //    CO2

#define measurePin  A1  // analog
#define ledPower  12 // digital

#define samplingTime 280
#define deltaTime 40
#define sleepTime 9680

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;
float ppm = 0;


#define analogPin A0 //   MQ135    A0 Arduino

MQ135 gasSensor = MQ135(analogPin); //   


//   



#define tempInX 10
#define tempOutX 380 // 415
#define humidityInX 320 //325
#define humidityOutX 410
#define pressureX 20 // 10
#define ppmX 20
#define pmX 370
#define Y0 0 //    
#define Y1 5 // , 
#define Y2 125 // 
#define Y3 230 // ppm&pm
#define dotY 125 //  
#define minusY 115// 

//    
#define minusXOut 380

//    
#define minusXIn 10

//  
#define minusH 3 

//    
#define minusPicID 2 

#define symbolID 1 //     

#define statusTimeOut 2200000 //  ""   (,       ) 900000
#define updateTimeOut 300000 //      60000 (300000)
#define historyTimeOut 1800000 //      (1800000)
#define selectionTimeOut 5000 //      
#define backLightTimeOut 300000 //      
#define waveLimit 254

int parameterS[7]; //  . : tempIn, tempOut, humidityIn, humidityOut, pressure, ppm, pm
byte statusS[7]; //         ( /  )
boolean statusBoolean[7]; //   

/*
//      
int coordinateX[7] = {tempInX, tempOutX, humidityInX, humidityOutX, pressureX, ppmX, pmX};
int coordinateY[7] = {Y2, Y2, Y1, Y1, Y1, Y3, Y3};
*/

//  
//  : tempIn, tempOut, humidityIn, humidityOut, pressure, ppm, pm
int historyArray[7][48]; // 7   48 
boolean drawArray[7]; //       
int arrayMax; //       
int arrayMin;
byte waveShift; //        waveform 0 - 255
float arrayNorm; //        

byte count=0; //    
byte arrayCounter; //   
byte waveCount; //    
int splitData[4]; //       [, , , ]
byte thousands, hundreds, tens, ones; //    
int tempIn, tempOut, humidityIn, humidityOut, pressure;
// int tempIn, tempOut, humidityIn, humidityOut, pressure, ppm, pm;
int symbolX0;
int posX; //    X  
byte tempInStatus, tempOutStatus, humidityInStatus, humidityOutStatus, pressureStatus, ppmStatus, pmStatus; //       StatusTimeOut
byte symbolCount, symbolWidth;
boolean minusIn = false; //   
boolean minusOut = false;
byte i = 0; //  
unsigned long statusTime, updateTime, historyTime, selectionTime, backLightTime;
String stringToNextion;
byte historyCount;
boolean backLight; //           

int weatherData = 0;
int dht22Humidity = 0;


//CLICKER VARIABLE SECTION
byte buffer[30]; // buffer for bytes coming from HMI.
byte waveCounter = 0; //    
// boolean drawArray[7]; //     
boolean allClear;
byte currentPage = 0; //   
byte searchTarget, searchNumber, searchCounter, pageNum, drawCounter, channelToDraw;
// int historyArray[7][48]; // 7   48 
// int arrayMax; //       
// int arrayMin;
// byte waveShift; //        waveform 0 - 255
// float arrayNorm; //        
byte iconCounter = 0;

// int splitData[4]; //       [, , , ]
// int posX; //    X  
// byte count = 0; //    
// String stringToNextion;
// int symbolX0;
// byte symbolCount;

//  
#define minusH 3 

//    
#define minusPicID 2 

//       
int axisX[5][7] = {{10, 380, 320, 410, 20, 20, 370}, //  0
               {0, 0, 0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0, 0, 0},
               {0, 0, 0, 0, 0, 0, 0}}; //  1-4

int axisY[5][7] = {{115, 115, 5, 5, 5, 230, 230}, //  0
               {145,0, 0, 0, 0, 0, 0}, //  1
               {63, 226, 0, 0, 0, 0, 0}, //  2 
               {37, 145, 253, 0, 0, 0, 0 }, //  3
               {25, 105, 185, 265, 0, 0, 0}}; //  4


byte symbolW[5][11] = {{25, 15, 30, 25, 30, 30, 25, 30, 25, 30, 5},
                       {11, 6, 12, 12, 14, 13, 12, 13, 12, 12, 3},
                       {11, 6, 12, 12, 14, 13, 12, 13, 12, 12, 3},
                       {11, 6, 12, 12, 14, 13, 12, 13, 12, 12, 3},
                       {11, 6, 12, 12, 14, 13, 12, 13, 12, 12, 3}};//   0, 1, 2, 3, 4, 5, 6, 7, 8, 9

// {13, 7, 15, 13, 17, 15, 13, 14, 14, 14, 5}   25 Comfortaa Light

byte numberPic[5] = {1, 3, 3, 3, 3}; // ID   

byte symbolH[5] = {60, 18, 18, 18, 18}; //     25   25 Comfortaa Light

// CLICKER VARIABLE SECTION ENDS    

// TREND VARIABLE SECTION

#define x2 70 //    

int trendArray[3][6] = {{0, 0, 0, 0, 0, 0}, //    
                        {-5, -3, -1, 1, 3, 5},
                        {0, 0, 0, 0, 0, 0}};

int sumY, sumXY;
byte trendCount;
int trend; 

// TREND VARIABLE SECTION ENDS                  

#define DHTPIN 7
#define DHTTYPE DHT22

// Setup a DHT22 instance
DHT dht(DHTPIN, DHTTYPE);




// Setup RC-Switch
RCSwitch mySwitch = RCSwitch();


void sendToNextion() {
  Serial.write(0xff);
  Serial.write(0xff);
  Serial.write(0xff);
}



//      
void drawMark(byte mark, byte markNum) {

int markX;

//        
if (allClear == true) {
  allClear = false;
}

markX = axisX[0][markNum];

if (markNum == 1 || markNum == 3 || markNum == 6) {
  markX = 475;
} 

if (markNum == 0 || markNum == 4 || markNum == 5) {
  markX = 0;
}

if (markNum == 2) {
  markX = markX - 15;
}

    stringToNextion = String("fill ");
    stringToNextion = stringToNextion + String(markX); // String(axisX[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(axisY[0][markNum]+30); // String(axisY[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("5");
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("30");
    stringToNextion = stringToNextion + String(",");

if (mark == 1) {

    stringToNextion = stringToNextion + String("RED"); //     0, 0
    // Serial2.println("Mark set");

}

if (mark == 0) {

    stringToNextion = stringToNextion + String("BLACK"); //     0, 0
    // Serial2.println("Mark clear");

}

    // Serial2.println(stringToNextion);
    Serial.print(stringToNextion);
    sendToNextion();
  
}

//  :     
void clearSelection() {

  for (byte jj = 0; jj < 7; jj++) {
   if (drawArray[jj] == true) {
    drawArray[jj] = false;
    drawMark(0, jj);
   }
  }

  allClear = true; //   
  waveCounter = 0;
}





void updateHistory() {
mySwitch.disableReceive();

//   ,       -   ,       
for (arrayCounter = 0; arrayCounter < 7; arrayCounter++) {
  // Serial2.print("StatusBoolean for array #");// Serial2.print(arrayCounter);// Serial2.print(" = "); // Serial2.println(statusBoolean[arrayCounter]);
  if (statusBoolean[arrayCounter] == true) { //       
    for (i = 47; i > 0; i--) {
      historyArray[arrayCounter][i] = historyArray[arrayCounter][i-1]; // 
    }
    historyArray[arrayCounter][0] = parameterS[arrayCounter]; //  
  }

// statusBoolean[arrayCounter] = false; // ,       

  }

for (arrayCounter = 0; arrayCounter < 7; arrayCounter++) {
 for (i = 0; i < 47; i++) {
   // Serial2.print(historyArray[arrayCounter][i]);// Serial2.print(", ");
  }
 // Serial2.println();
}

// Serial2.println();  

mySwitch.enableReceive(0);
  
}



void drawTrend(byte arrayToTrend) {

int markX;

markX = axisX[0][arrayToTrend];

//   X   
if (arrayToTrend == 1 || arrayToTrend == 3 || arrayToTrend == 6) {
  markX = 472;
} 

if (arrayToTrend == 0 || arrayToTrend == 4 || arrayToTrend == 5) {
  markX = 0;
}

if (arrayToTrend == 2) {
  markX = markX - 15;
}

    stringToNextion = String("xpic ");
    stringToNextion = stringToNextion + String(markX); //   X
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(axisY[0][arrayToTrend]); //   Y
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("8"); //    7x18
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("18"); //
    stringToNextion = stringToNextion + String(",");

if (trend > 0) {


    stringToNextion = stringToNextion + String("0"); //    0
    stringToNextion = stringToNextion + String(","); // 
    stringToNextion = stringToNextion + String("0"); //  Y    0

  
}

if (trend < 0) {

    stringToNextion = stringToNextion + String("8"); //    5
    stringToNextion = stringToNextion + String(","); // 
    stringToNextion = stringToNextion + String("0"); //  Y    0
    
}

if (trend == 0) {

    stringToNextion = stringToNextion + String("16"); //     10
    stringToNextion = stringToNextion + String(","); // 
    stringToNextion = stringToNextion + String("0"); //  Y    0
 
}

    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("5"); // ID    
    // Serial2.println(stringToNextion);    
    Serial.print(stringToNextion);
    sendToNextion();
 
}



void splitRoutine(int input) {



input = abs(input); //      ,   

for (count = 0; count < 4; count++) {
  splitData[count] = 0; //   
}

count = 0;

if (input > 9999) { //     
  count = 5;
} else {

if (input > 999) { //  9999
  splitData[3] = input/1000;
  input = input - splitData[3]*1000;
  count = 4;
/*
  Serial.print("SplitData Count 4:");
  Serial.println(splitData[3]);
*/
}

if (input > 99) { //  999
  splitData[2] = input/100;
  input = input - splitData[2]*100;
  if (count == 0) {
    count = 3;
/*
  Serial.print("SplitData Count 3:");
  Serial.println(splitData[2]);
*/  
  }
}

if (input > 9) { //  99
  splitData[1] = input/10;
  input = input - splitData[1]*10;
  if (count == 0) {
    count = 2;
/*
  Serial.print("SplitData Count 2:");
  Serial.println(splitData[1]);
*/  
  }
} 

if (input < 10) {
  splitData[0] = input;
  if (count == 0) {
    count = 1;
/*
  Serial.print("SplitData Count 1:");
  Serial.println(splitData[0]);
*/  
  }
}

}
/*
  Serial.print("Input = ");
  Serial.println(input);
  Serial.print("Count = ");
  Serial.println(count);
*/

}




void drawRoutine(byte page, int value, byte type, int drawX, int drawY) { 

mySwitch.disableReceive();  
// page -  ; value = ; type =       ; drawX    X, drawY -  Y
  
  boolean minusSign = false;

  splitRoutine(value);  

if (page == 0) { //    
//   (  pm25)         ( 470 = 480 - 10)
  if (type == 1) { //   
    drawX = 470 - count*30 - 5; //       10      ,  30    + 5  
    if (count == 1) {
      drawX = drawX - 30; //   0,        
    }
  }

  if (type == 6) { //  pm25
    drawX = 470 - count*30 - 5; //       20      ,  30   
    if (count == 1) {
      drawX = drawX - 30;
    }
  }
}

  int posX = drawX;

 if (value < 0) {
  minusSign = true;
 }

 

 if (count < 5) { //    9999

  if ((count == 1) && ((type == 0) || (type  == 1) || (type  == 6))) { //    pm2.5     0,  0   
  // xpic X, Y, , , X, Y, 

    // 
    stringToNextion = String("xpic ");
    stringToNextion = stringToNextion + String(drawX); // String(axisX[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(drawY); // String(axisY[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(symbolW[page][0]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(symbolH[page]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String("0"); //     0, 0
    stringToNextion = stringToNextion + String(","); //     0, 0
    stringToNextion = stringToNextion + String("0"); //     0, 0
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(numberPic[page]);
   // // Serial2.println("Temp leading zero");
   // // Serial2.println(stringToNextion);
    Serial.print(stringToNextion);
    sendToNextion();
    drawX = drawX + symbolW[page][0]; //     0
      
   } // count = 1

   for (byte ii = count; ii > 0; ii--) { //   ,    

    if ((ii == 1) && ((type == 0) || (type == 1) || (type == 6))) { //  ,     
      stringToNextion = String("xpic ");
      stringToNextion = stringToNextion + String(drawX); // String(axisX[page, type]);
      stringToNextion = stringToNextion + String(",");
      stringToNextion = stringToNextion + String(drawY); // String(axisY[page, type]);
      stringToNextion = stringToNextion + String(",");
      stringToNextion = stringToNextion + String(symbolW[page][10]);
      stringToNextion = stringToNextion + String(",");
      stringToNextion = stringToNextion + String(symbolH[page]);
      stringToNextion = stringToNextion + String(",");
      if (page == 0) {
        stringToNextion = stringToNextion + String("265"); //        265
      } else {
        stringToNextion = stringToNextion + String("118"); //       135  Comfortaa Light 25
      }
      stringToNextion = stringToNextion + String(","); // 
      stringToNextion = stringToNextion + String("0"); //    Y    0
      stringToNextion = stringToNextion + String(",");
      stringToNextion = stringToNextion + String(numberPic[page]); 
     // // Serial2.println("Temp decimal dot");
     // // Serial2.println(stringToNextion);      
      Serial.print(stringToNextion);
      sendToNextion();
      drawX = drawX + symbolW[page][10]; //     
    } // ii == 1 && type == 0 || type == 1

    //       
    symbolX0 = 0; //       
    for (symbolCount = 0; symbolCount < (splitData[ii-1]);symbolCount++) { //     X    (   )
      symbolX0 = symbolX0 + symbolW[page][symbolCount];
    }

    stringToNextion = String("xpic ");
    stringToNextion = stringToNextion + String(drawX); // String(axisX[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(drawY); // String(axisY[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(symbolW[page][splitData[ii-1]]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(symbolH[page]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(symbolX0); //     0, 0
    stringToNextion = stringToNextion + String(","); //     0, 0
    stringToNextion = stringToNextion + String("0"); //     0, 0
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(numberPic[page]);
   // // Serial2.print("Symbol: "); // Serial2.println(splitData[ii-1]);
  //  // Serial2.println(stringToNextion);    
    Serial.print(stringToNextion);
    sendToNextion();
    drawX = drawX + symbolW[page][splitData[ii-1]];
  }

  if (minusSign == true) {

    /*
    symbolX0 = 0; //    
    for (byte ii = count; ii > 0; ii--) { 
      symbolX0 = symbolX0 + symbolW[page][splitData[ii-1]];
    }

    */
    
    stringToNextion = String("xpic ");
    stringToNextion = stringToNextion + String(posX); // String(axisX[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(drawY-8); // String(axisY[page, type]);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(drawX - posX);
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(minusH); //  
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(0); //     0, 0
    stringToNextion = stringToNextion + String(","); //     0, 0
    stringToNextion = stringToNextion + String("0"); //     0, 0
    stringToNextion = stringToNextion + String(",");
    stringToNextion = stringToNextion + String(minusPicID);
//    // Serial2.print("Symbol: "); // Serial2.println(splitData[ii-1]);
 //   // Serial2.println(stringToNextion);    
    Serial.print(stringToNextion);
    sendToNextion();
    
  }
  
 } // if count < 5    9999
  mySwitch.enableReceive(0);
}         

//     ( )
void getMinMax(byte arrayToMax, byte maxCount) {
  
byte getMaxCount = 0;

arrayMax = historyArray[arrayToMax][getMaxCount]; //      
arrayMin = historyArray[arrayToMax][getMaxCount]; //      

for (byte getMaxCount = 0; getMaxCount < maxCount; getMaxCount++) { // maxCount 47   , 6  
  
  if (historyArray[arrayToMax][getMaxCount+1] > arrayMax){ 
    arrayMax = historyArray[arrayToMax][getMaxCount+1];
  }

  if (arrayMin > historyArray[arrayToMax][getMaxCount+1]){ 
    arrayMin = historyArray[arrayToMax][getMaxCount+1];
  }
  
}
 
}      

void getTrend(byte arrayToTrend) {
mySwitch.disableReceive();
getMinMax(0, 6); //        


for (trendCount = 0; trendCount < 6; trendCount++) {
  if (arrayMin < 0) {
    trendArray[0][trendCount] = historyArray[arrayToTrend][5-trendCount] + abs(arrayMin); //    
  } else {
    trendArray[0][trendCount] = historyArray[arrayToTrend][5-trendCount];
  }
}

sumY = 0;
sumXY = 0;

//   ,   XY
for (trendCount = 0; trendCount < 7; trendCount++) {
  sumY = sumY + trendArray[0][trendCount];
  sumXY = sumXY + trendArray[0][trendCount]*trendArray[1][trendCount];
}

trend = (int) (sumY/10 + (sumXY/x2)*trendArray[1][5]) - (sumY/10 + (sumXY/x2)*trendArray[1][0])+0.5;

// Serial2.print("Trend: "); // Serial2.println(trend);

drawTrend(arrayToTrend);
mySwitch.enableReceive(0);
}

void reDraw() {
 mySwitch.disableReceive();

// Serial2.println("Redraw main page");
/*    
 for (i = 0; i < 7; i++) {
  parameterS[i] = random(255);
  statusS[i] = 1;
 }
    */ 

 Serial.print("page 0");
 sendToNextion();
 // Serial.print("pic 0,0,6");
 // sendToNextion();
 
 
 
  for (i = 0; i < 7; i++) {
   // Serial2.print("StatusBoolean on reDraw for item "); // Serial2.print(i); // Serial2.print(" is "); // Serial2.println(statusBoolean[i]);
   if (statusBoolean[i] == true) { //     " "
    drawRoutine(currentPage, parameterS[i], i, axisX[currentPage][i], axisY[currentPage][i]);
    // Serial2.print("Redraw, ");// Serial2.print(i); // Serial2.print(": "); // Serial2.println(parameterS[i]);
    if (historyCount > 5) {
      getTrend(i);
    }

   }
    
  }

 mySwitch.enableReceive(0);
}




void getNorm() {

arrayNorm = 1.00; //  1:1

  arrayNorm = abs(arrayMax - arrayMin);
  
    arrayNorm = waveLimit/arrayNorm; //   
  
}



void drawHistory(byte arrayCounter, byte waveCount){
mySwitch.disableReceive();
byte tC01 = 0;
byte tC02 = 0; 
int interPoint, lineMulti;
int justPoint;

  byte channelCount = 0; //   ,   (ID = 0),           

      getMinMax(arrayCounter, 47); //  47   ,  39,        ,   
 //     // Serial2.print("arrayMax: "); // Serial2.println(arrayMax);
 //     // Serial2.print("arrayMin: "); // Serial2.println(arrayMin);
      getNorm();
      
      if (currentPage == 2) {
         arrayNorm = arrayNorm*0.5;      
      }

      if (currentPage == 3) {
         arrayNorm = arrayNorm*0.3;      
      }

      if (currentPage == 4) {
         arrayNorm = arrayNorm*0.2;
      }

 //     // Serial2.print("arrayNorm: "); // Serial2.println(arrayNorm);   

     
     

//  
      stringToNextion = String("add "); //   
      stringToNextion = stringToNextion + String(waveCount); //    ID
      stringToNextion = stringToNextion + String(",");
      stringToNextion = stringToNextion + String(channelCount); //   0, 1, 2  3
      stringToNextion = stringToNextion + String(",");
      if (arrayMin < 0) {
        justPoint = (int) (historyArray[arrayCounter][tC01] + abs(arrayMin))*arrayNorm + 0.5;
        stringToNextion = stringToNextion + String(justPoint); //    
      } else {
        justPoint = (int) historyArray[arrayCounter][tC01]*arrayNorm + 0.5;
        stringToNextion = stringToNextion + String(justPoint); //    
      }
      Serial.print(stringToNextion);
      // // Serial2.print("First point, original");// Serial2.println(historyArray[arrayCounter][tC01]);
      // // Serial2.print("First point: "); // Serial2.println(stringToNextion);          
      sendToNextion(); 
                
        for (tC01 = 0; tC01 < 46; tC01++) { //   37  46
          
          lineMulti = (historyArray[arrayCounter][tC01+1] - historyArray[arrayCounter][tC01])/9; //         
          
          if (arrayMin < 0) {
            justPoint = (int) historyArray[arrayCounter][tC01] + abs(arrayMin) + lineMulti+0.5;
            interPoint = justPoint;
          } else {
            justPoint = (int) historyArray[arrayCounter][tC01] + lineMulti + 0.5;
            interPoint = justPoint;
          }
          
          for (tC02 = 0; tC02 < 7; tC02++) { //   ,  ,    9
            stringToNextion = String("add "); //   
            stringToNextion = stringToNextion + String(waveCount); //     (1, 2, 3  4 )
            stringToNextion = stringToNextion + String(",");
            stringToNextion = stringToNextion + String(channelCount); //   0, 1, 2  3
            stringToNextion = stringToNextion + String(",");
            justPoint = (int) interPoint*arrayNorm;
            stringToNextion = stringToNextion + String(justPoint);
            interPoint = (int) interPoint + lineMulti;
            Serial.print(stringToNextion);   
           // // Serial2.print("Connecting point: "); // Serial2.println(stringToNextion);                               
            sendToNextion();                      
          }
          stringToNextion = String("add "); //   
          stringToNextion = stringToNextion + String(waveCount); //     (1, 2, 3  4 )
          stringToNextion = stringToNextion + String(",");
          stringToNextion = stringToNextion + String(channelCount); //   0, 1, 2  3
          stringToNextion = stringToNextion + String(",");
          if (arrayMin < 0) {
            justPoint = (int) (historyArray[arrayCounter][tC01+1] + abs(arrayMin))*arrayNorm + 0.5;
            stringToNextion = stringToNextion + String(justPoint); //    
          } else {
            justPoint = (int) historyArray[arrayCounter][tC01+1]*arrayNorm + 0.5;
            stringToNextion = stringToNextion + String(justPoint); //    
          }
          
          Serial.print(stringToNextion);
         // // Serial2.print("Next/Last point, original: ");// Serial2.println(historyArray[arrayCounter][tC01+1]);               
          // // Serial2.print("Next/Last point: "); // Serial2.println(stringToNextion);               
          sendToNextion();                                  
        }
    
 mySwitch.enableReceive(0);   
  }
  






void drawIcon(int where, byte what) {

//// Serial2.print("Where: "); // Serial2.println(where);
//// Serial2.print("What: "); // Serial2.println(what);

stringToNextion = String("xpic ");
stringToNextion = stringToNextion + String("0"); // String(axisX[page, type]);
stringToNextion = stringToNextion + String(",");
stringToNextion = stringToNextion + String(where-3); // String(axisY[page, type]);
stringToNextion = stringToNextion + String(",");
stringToNextion = stringToNextion + String(80); //   
stringToNextion = stringToNextion + String(",");
stringToNextion = stringToNextion + String(30);
stringToNextion = stringToNextion + String(",");
stringToNextion = stringToNextion + String(what*80); //     X = 80*  
stringToNextion = stringToNextion + String(","); // 
stringToNextion = stringToNextion + String("0"); //   Y  0
stringToNextion = stringToNextion + String(",");
stringToNextion = stringToNextion + String(4);
//// Serial2.println(stringToNextion);
Serial.print(stringToNextion);
sendToNextion();
  
}



void toPage(byte pageNum) {
mySwitch.disableReceive();
currentPage = pageNum;

/*
//    
stringToNextion = String("ref page");
stringToNextion = stringToNextion + String(pageNum);
Serial.print(stringToNextion);
sendToNextion();
*/

//    
  String stringToNextion = String("page ");
  stringToNextion = stringToNextion + String(pageNum);
 // // Serial2.print("Switch to: "); // Serial2.println(stringToNextion);
  Serial.print(stringToNextion);
  sendToNextion();



if (pageNum == 0) {
  clearSelection();
  reDraw();
}

//        
  if (pageNum > 0) {

    
    if (pageNum == 1 && waveCounter > 1) { //           
 //     // Serial2.print("Draw single, searchCounter-1: "); // Serial2.println(searchCounter-1);
      getMinMax(searchCounter-1, 47); //      
  //    // Serial2.print("arrayMax: "); // Serial2.println(arrayMax);
  //    // Serial2.print("arrayMin: "); // Serial2.println(arrayMin);
      drawRoutine(pageNum, arrayMax, searchCounter-1, 0, 117); // 115
      drawIcon(145, searchCounter-1);
      drawRoutine(pageNum, arrayMin, searchCounter-1, 0, 185); // 175
      drawHistory(searchCounter-1, 1); //  :     
     } else {

              //  
              iconCounter = 0;
              for (drawCounter = 0; drawCounter < 7; drawCounter++) {
                if (drawArray[drawCounter] == true) {
        //          // Serial2.print("pageNum: "); // Serial2.println(pageNum);
       //           // Serial2.print("iconCounter: "); // Serial2.println(iconCounter);
      //            // Serial2.print("drawCounter: "); // Serial2.println(drawCounter);
                  getMinMax(drawCounter, 39); //   39  47
      //            // Serial2.print("arrayMax: "); // Serial2.println(arrayMax);
     //             // Serial2.print("arrayMin: "); // Serial2.println(arrayMin);
                  drawRoutine(pageNum, arrayMax, drawCounter, 0, axisY[pageNum][iconCounter]-22);   // -30               
                  drawIcon(axisY[pageNum][iconCounter], drawCounter);
                  drawRoutine(pageNum, arrayMin, drawCounter, 0, axisY[pageNum][iconCounter]+35); // +30
                  iconCounter++;
                }
            }      
              channelToDraw = 1; //      ,    ,   - 
              for (drawCounter = 0; drawCounter < 7; drawCounter++) { //   " "
                if (drawArray[drawCounter] == true) {
                  drawHistory(drawCounter, channelToDraw);
           //       // Serial2.print("drawCounter / channelToDraw "); // Serial2.print(drawCounter); // Serial2.print(" | "); // Serial2.println(channelToDraw);
                  channelToDraw++;
                 }
              }
      }
    }
    
  mySwitch.enableReceive(0);
}



void setup() {

  pinMode(ledPower,OUTPUT);
 // pinMode(measurePin, INPUT);

 pinMode(4, OUTPUT);
 digitalWrite(4, HIGH);



 
  currentPage = 0;
  allClear = true;
  historyCount = 0; //       
  backLight = true; //          ,   false
  
//     
//  . : tempIn, tempOut, humidityIn, humidityOut, pressure, ppm, pm
 for (i = 0; i < 7; i++) {
  parameterS[i] = 0;
  statusS[i] = 1;
 }

//   
for (arrayCounter = 0; arrayCounter < 7; arrayCounter++) {
 for (i = 0; i<48; i++) {
  historyArray[arrayCounter][i]=0;
 }
}
 
 statusTime = millis();
 updateTime = millis();
 historyTime = millis();
 backLightTime = millis();

 Serial.begin(9600);
  Serial.print("baud=57600");
  sendToNextion();
 Serial.end();

 Serial.begin(57600);
 Serial.print("baud=57600");
 sendToNextion();
 
 // Serial2.begin(115200);
 dht.begin();
 mySwitch.enableReceive(0);
 delay(2000);
 Serial.print("page 0");
 sendToNextion();
 // Serial2.println("Ready");
 
 reDraw();
}



void loop() {


//    

   if (mySwitch.available()) { //  
    int value = mySwitch.getReceivedValue();
    if (value != 0) {
    // Serial2.print("RC-Switch: "); // Serial2.println(mySwitch.getReceivedValue());
//    
      if (mySwitch.getReceivedValue() / 100000 == 161) {

        weatherData = mySwitch.getReceivedValue() - 16100000;
        if (weatherData > 10000) { //  
          parameterS[3] = (weatherData - 10000)/10;
          statusS[3] = statusS[3]+1;   
          statusBoolean[3] = true;  
        }
        else { //  
          if (weatherData > 1000) { //  
            parameterS[1] = -(weatherData - 1000);
            minusOut = true;
          }
          else { //  
            parameterS[1] = weatherData;
            minusOut = false;
          }
        }
          statusS[1] = statusS[1]+1;
          statusBoolean[1] = true;
      }

//    
      if (mySwitch.getReceivedValue() / 10000 == 1210) {
        parameterS[4] = (mySwitch.getReceivedValue() - 12100000) / 1.33; //  
        statusS[4] = statusS[4]+1;   
        statusBoolean[4] = true;   
        // Serial2.print("Pressure: "); // Serial2.println(parameterS[4]);     
      }

      if (mySwitch.getReceivedValue() / 100000 == 131) {
        weatherData = mySwitch.getReceivedValue() - 13100000;
        if (weatherData > 1000) { //  
          parameterS[0] = -(weatherData - 1000);
          minusIn = true;
        }
        else { //  
          parameterS[0] = weatherData;
          minusIn = false;
        }
          statusS[0] = statusS[0]+1;
          statusBoolean[0] = true;
      }

//        

      if (mySwitch.getReceivedValue() / 10000 == 1212) {
        parameterS[2] = (mySwitch.getReceivedValue() - 12120000); // 
        statusS[2] = statusS[2]+1;   
        statusBoolean[2] = true;   
        // Serial2.print("HumidityIn: "); // Serial2.println(parameterS[2]);     
      }
// CO2 PPM
      if (mySwitch.getReceivedValue() / 10000 == 1213) {
        parameterS[5] = (mySwitch.getReceivedValue() - 12130000); // CO2
        statusS[5] = statusS[5]+1;   
        statusBoolean[5] = true;   
        // Serial2.print("CO2 PPM: "); // Serial2.println(parameterS[5]);     
      }      
// PM2.5
      if (mySwitch.getReceivedValue() / 10000 == 1214) {
        parameterS[6] = (mySwitch.getReceivedValue() - 12140000); // PM2.5
        statusS[6] = statusS[6]+1;   
        statusBoolean[6] = true;   
        // Serial2.print("PM2.5: "); // Serial2.println(parameterS[6]);     
      } 

    }
    mySwitch.resetAvailable();
    //    mySwitch.enableReceive(0); //  RC Switch
  }   

  
//    
if (currentPage == 0) {
  if ((millis() - selectionTime) > selectionTimeOut) { 
    if (allClear == false) {
      clearSelection();
    }
  }
 }

  if (Serial.available())
  {
    bool moretocome = true;
    int endcount = 0;
    int bytesread = 0;
    byte inbyte;
    //bool isascii = false;

    while (moretocome)
    {
      inbyte = Serial.read();

        delay(2);
        
      if (inbyte == 0xFF)
      {
        endcount++;
        if (endcount == 3)
        {
          moretocome = false;
          // Serial2.println("");
        }
      }
      else
      {
        endcount = 0;
      }
      buffer[bytesread] = inbyte;
      bytesread++;

    }

    for (int x = 0; x < bytesread; x++)
    {
      // Serial2.print(buffer[x], HEX);
      // Serial2.print(" ");
    }

    //// Serial2.println(bytesread, DEC);
    // Serial2.println("");

  }

  if (buffer[0] == 101) { //   
   backLightTime = millis(); //        
   if (backLight == false) { //    ,   
    // Serial2.println("Backlight 50%");
    Serial.print("dim=100"); //  
    sendToNextion();
    backLight = true; //    
   } else { //     
    
    if (buffer[1] == 0) { //    
      selectionTime = millis();
      if (buffer[2] < 8) { //    
      if (waveCounter < 4) { //    4 
        if (drawArray[buffer[2]-1] == false) { //    
          drawArray[buffer[2]-1] = true; //    ,   
          drawMark(1, buffer[2]-1);
          waveCounter = waveCounter + 1; //       
     //     // Serial2.print("Set button: "); // Serial2.println(buffer[2]);          
     //     // Serial2.print("Total buttons: "); // Serial2.println(waveCounter);
        } else {
          drawArray[buffer[2]-1] = false; //     
          drawMark(0, buffer[2]-1);
          if (waveCounter > 0) {
            waveCounter = waveCounter - 1;
          }
     //     // Serial2.print("Clear button: "); // Serial2.println(buffer[2]);          
     //     // Serial2.print("Total buttons: "); // Serial2.println(waveCounter);          
        }
      } else { //     
        if (drawArray[buffer[2]-1] == true) { //    ,  
          drawArray[buffer[2]-1] = false; //     
          drawMark(0, buffer[2]-1);
          waveCounter = waveCounter - 1; //   
     //     // Serial2.print("Clear button: "); // Serial2.println(buffer[2]);          
     //     // Serial2.print("Total buttons: "); // Serial2.println(waveCounter);          
        }
      }
    } else { //      
        currentPage = waveCounter;
        toPage(waveCounter);    
      }
    }
    else { 
      if (currentPage > 1) { //      ,    ID = 5    0
        if (buffer[2] == 5) {
          toPage(0);
        }
      }

      if (currentPage == 1) { //   1   ,    ID = 5    0
        if (buffer[2] == 5) {
          if (waveCounter == 1) {
            toPage(0);
          } else {
            toPage(waveCounter); //       
          }
        }
      }

      if (currentPage == 1) { //    1     ID = 6 -          
        if (buffer[2] == 6) {
          toPage(0);
        }
      }      
      
      //   

    if (currentPage > 1) { //    1, .   1
      if (buffer[2] > 5) { //     ID > 2, ..  
   //     // Serial2.print("Buffer[2]: ");
   //     // Serial2.println(buffer[2]);
   //     // Serial2.print("Normalized button: ");
        searchTarget = buffer[2] - 5; // ""  ,     ,   :  1 -   -  true   drawarray   1
        searchNumber = 0;
        searchCounter = 0;
   //     // Serial2.println(searchTarget);

        while ((searchCounter < 7) && (searchNumber < searchTarget)) {
          if (drawArray[searchCounter] == true) {
            searchNumber++;
          }
          searchCounter++;
        }
        
   //     // Serial2.print("searchCounter: "); // Serial2.println(searchCounter);
        toPage(1); //      
      }
    }


      
     }
    }
  } 

buffer[0] = 0;

//    *Status   1   
//    

//  :       ,    9
if ((millis() - statusTime) > statusTimeOut) {

 
 for (i = 0; i < 7; i++) { //   
  // Serial2.print("Status of "); // Serial2.print(i); // Serial2.print(" is: "); // Serial2.println(statusS[i]);
    if (statusS[i] == 0) {statusBoolean[i] = false;
    // Serial2.print("As StatusS "); // Serial2.print(i); // Serial2.print(" is "); // Serial2.print(statusS[i]); // Serial2.println(" StatusBoolean set to false");
    }
    statusS[i] = 0; //    
 }
  statusTime = millis();
  
}

if (currentPage == 0) { //       

 
//    
if ((millis() - updateTime) > updateTimeOut) {

  reDraw();
  updateTime = millis();
 }

 
 
}

//         
if ((millis() - backLightTime) > backLightTimeOut) {
 if (backLight == true) {
  backLight = false;
  // Serial2.println("Backlight 15%");
  //Serial.print("page 0");
  // sendToNextion();
  currentPage = 0;
  clearSelection();
  reDraw();
  Serial.print("dim=15");
  sendToNextion();
 }
  
 }

//   
if ((millis() - historyTime) > historyTimeOut) {
  updateHistory();

    historyCount++;
    // Serial2.print("History Q: "); // Serial2.println(historyCount);
 
  historyTime = millis();
  }

}  



Modelo de caja (con cuidado, puede romper la pantalla)

Source: https://habr.com/ru/post/es399409/


All Articles