text:
I2C LCD TFT with UART serial communication for MLX90615 IR thermometer freezing IR output
I have one Ir temperature mlx90615 sensor based of this connection only used for mega2560 RX1&TX1) :

Which is connected to one Arduino 2560 mega with one LCD TFT 2.4 like this (Arduino mega2560 RX1 TX2 instead of Uno for mlx90615 connection and UNO 3.5V and Ground used to power supply the MLX90615):

So my problem is when i insert some new object in the seen area of Ir sensor the output halt for some second delay and don't show new value  via serial point or LCD output.
it characteristic table via datasheet of mlx90615 sensor is :

I have use this source code on library for mlx90615 into my codes by this function:

or(i=0;i<8;i++){
  i=1;
 serialEvent();
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
//           Serial.print("TO:");
//           Serial.println(TO);
//           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
//           Serial.print("TA:");
//           Serial.println(TA);

             tft.fillScreen(BLACK);
             tft.setTextColor(WHITE);
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);

            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);
            tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
   }
  }

 }

void serialEvent(){
  char i;
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
  for (i=0;i<30;i++)
  {
    while (Serial1.available()) {

    Re_buf[counter]=(unsigned char)Serial1.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;i=600;
       sign=1;
    }
  }
  }
}

The total codes are here:
#include "LiquidCrystal.h"

 #include <Adafruit_GFX.h>    // Adafruit's core graphics library
#include <Adafruit_TFTLCD.h> // Adafruit's hardware-specific library
#include <TouchScreen.h>     //Touchscreen library
///#include <Fonts/Org_01.h>    //Include a different font
#include <EEPROM.h>         //Include the EEPROM library to score the highscore
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;

#include <TimeLib.h>

bool backsensed = false;
bool resetsensed = false;

// most mcufriend shields use these pins and Portrait mode:
uint8_t YP = A1;  // must be an analog pin, use "An" notation!
uint8_t XM = A2;  // must be an analog pin, use "An" notation!
uint8_t YM = 7;   // can be a digital pin
uint8_t XP = 6;   // can be a digital pin

#define TS_MINX 100
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940
//Create the touchscreen object
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);  //(data,data,data,data,sensitivity);

//Some of the tft pins
#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
// Optional, used to reset the display
#define LCD_RESET A4

#define REDBAR_MINX 80
#define GREENBAR_MINX 130
#define BLUEBAR_MINX 180
#define BAR_MINY 30
#define BAR_HEIGHT 250
#define BAR_WIDTH 30

//Create the tft object
//Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

// Define some TFT readable colour codes to human readable names
#define BLACK   0x0000
int BLUE = tft.color565(50, 50, 255);
#define DARKBLUE 0x0010
#define VIOLET 0x8888
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF
int GREY =  tft.color565(64, 64, 64);
#define GOLD 0xFEA0
#define BROWN 0xA145
#define SILVER 0xC618
#define LIME 0x07E0

int currentpcolour;

//Minimum and maximum pressure to sense the touch
#define MINPRESSURE 10
#define MAXPRESSURE 1000

#define DRAW_LOOP_INTERVAL 50  //The interval used instead of delay();

//Define the address used in the eeprom memory to store highscores
#define addr 0
int currentpage;

int currentWing;        //Used to flap the wings
int flX, flY, fallRate; //Used to calculete and store the bird's position
int pillarPos, gapPosition;  //Used tho draw the pillars
int score;              //Store the score
int highScore = 0;      //Store the highscore
bool running = false;   //Store weather flying or not
bool crashed = false;   //Store weather crashed or not
bool scrPress = false;  //Store weather sensed some touch and store
long nextDrawLoopRunTime;
int redval;
int greenval;
int blueval;

int redpos = BAR_MINY + 12;
int greenpos = BAR_MINY + 12;
int bluepos = BAR_MINY + 12;

int oldrpos = redpos;
int oldgpos = greenpos;
int oldbpos = bluepos;
int x, y;

int lastDay = 0;
int lastMonth = 0;
int lastYear = 0;
int lastHour = 0;
int lastMinute = 0;
int lastSecond=0;
int movementTimer = 0;
int menuOptions = 4;
int menuOption = 0;
int alarmHours = 0;
//int Heater_alarmMinutes = 0;
//int Heater_alarmSecond=10;
//int Motor_alarmSecond=10;
//int Motor_alarmMinutes=0;

byte Heater_alarmMinutes_end ;
byte Heater_alarmSecond_end;
byte Motor_alarmSecond_end;
byte Motor_alarmMinutes_end;

bool heater_key = 0;
bool backLightOn = 1;
int fadeValue = 255;

byte address=0;
byte value;

bool state=1;

//#$############# MLX9615 ##################

 unsigned char Re_buf[11],counter=0;
 char sign=0;
float TO=0,TA=0;
void serialEvent();

//########################################
void DrawTriangle() {
 int n, i, cx = tft.width() / 2 - 1, cy = tft.height() / 2 - 1;

 tft.fillScreen(BLACK);
 n = min(cx, cy);

 for (i = 0; i < n; i += 15) {
 tft.drawTriangle(
 cx , cy - i, // peak
 cx - i, cy + i, // bottom left
 cx + i, cy + i, // bottom right
 tft.color565(0, 0, i));
 }
}
void drawHome()
{

  tft.fillScreen(BLACK);
  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game

  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);

  tft.fillRoundRect(60, 80, 200, 40, 8, RED);
  tft.drawRoundRect(60, 80, 200, 40, 8, WHITE); //Oscilloscope

  tft.setCursor(60, 20);
  tft.setTextSize(2);
///  tft.setFont();
  tft.setTextColor(WHITE);
  tft.print("Select on Option");
  tft.setCursor(70, 50);
  tft.setTextSize(2);
  tft.setTextColor(LIME);
  tft.print("GSH.ir");
  tft.setTextColor(BLACK);

  tft.setCursor(80, 95);
  tft.print("Heater Setting");

  tft.setCursor(80, 145);
  tft.print("Motor  Setting");

  tft.setCursor(70, 195);
  tft.print("     Start");

  //tft.drawCircle(30, 30, 20, RED);
  //tft.fillCircle(111, 111, 30, WHITE);
  //  delay(500);
  //tft.drawRoundRect(120, 192, 60, 64, 15, YELLOW);
  // tft.fillRoundRect(0, 192, 60, 64, 15, CYAN);

   // tft.drawRect(0, 0, 60, 64, CYAN);

   //  tft.fillRect(180, 192, 60, 64, GREY);
     //DrawTriangle();

}

void drawstart(bool k)
{

  tft.fillScreen(BLACK);
  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

//  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
//  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game
//
//  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
//  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);
//
  tft.fillRoundRect(90, 60, 160, 60, 18, RED);
  tft.drawRoundRect(90, 60, 160, 60, 18, WHITE); //Oscilloscope

  tft.setCursor(40, 180);
  tft.setTextSize(3);
///  tft.setFont();
  tft.setTextColor(WHITE);

  if (k) {
    tft.print("Motor on time");
  }else{
    tft.print("Heater on time");
  }

}
void drawMenu(bool k)
{
   tft.fillScreen(BLACK);

  tft.drawRoundRect(0, 0, 319, 240, 8, WHITE);     //Page border

//  tft.fillRoundRect(60, 180, 200, 40, 8, RED);
//  tft.drawRoundRect(60, 180, 200, 40, 8, WHITE);  //Game
//
//  tft.fillRoundRect(60, 130, 200, 40, 8, RED);   //RGB led
//  tft.drawRoundRect(60, 130, 200, 40, 8, WHITE);
//
//  tft.fillRoundRect(75, 80, 160, 60, 18, BLUE);
 // tft.drawRoundRect(700, 60, 160, 80, 18, WHITE); //Oscilloscope

  //tft.fillTriangle(60,60,20,120,180,180,RED);
  tft.fillRoundRect(70, 75, 180, 70, 18, GREEN);
   //tft.fillTriangle(42, 20, 42, 60, 90, 40, RED);
   tft.fillTriangle(260,90, 260, 130, 300, 110, RED);
   tft.fillTriangle(60,90, 60, 130, 20, 110, RED);

  tft.setCursor(45, 180);
  tft.setTextSize(2.95);
///  tft.setFont();
  tft.setTextColor(WHITE);
  if (k) {
    tft.print("Motor Timer Setting");
  }else{
    tft.print("Heater Timer Setting");
  }
//  tft.fillRoundRect(5, 5, 80, 60, 8, WHITE);
//  delay(70);

  tft.setTextSize(4);
  tft.fillRoundRect(5, 5, 80, 60, 8, RED);
  tft.drawRoundRect(5, 5, 80, 60, 8, WHITE);
  tft.setCursor(20,20);
  tft.print("<-");

   tft.fillRoundRect(230, 5, 85, 60, 8, BLUE);
  tft.drawRoundRect(230, 5, 85, 60, 8, WHITE);
  tft.setCursor(250, 20);
  tft.print("OK");

}

void start(){
  tft.fillScreen(BLACK);
   drawstart(0);
   setTime(0, 0, 1, 20, 1, 2013); // hour, min, sec, day, month, year
  lastHour = hour();

          //check for heater key pressed

   heater_key=1;state =1;
 while (state ){

   if ( lastSecond!=second())
   {
       lastMinute = minute();
       lastSecond=second();
       tft.setTextSize(6);
       tft.fillRoundRect(60, 60, 200, 100, 18, RED);
       //tft.fillScreen(BLACK);
       tft.setTextColor(WHITE);
       tft.setCursor(110, 85);
       tft.print(lastMinute);
       tft.setCursor(140,85);
       tft.print(":");
       tft.setCursor(170, 85);
       tft.print(lastSecond);
       //delay(1000);
   }
   if (heater_key)
    {
      // alarm set
      if ((Heater_alarmSecond_end <= lastSecond) && (Heater_alarmMinutes_end == lastMinute))
      {
         state=0;
         digitalWrite(A5, LOW);

      }
       if ((Heater_alarmSecond_end >= lastSecond) || (Heater_alarmMinutes_end >= lastMinute))
         {
          //sound alarm
          digitalWrite(A5, HIGH);
          //setOffAlarm();
         }
     }
   }

    drawstart(1);
    state =1;
   setTime(0, 0, 0, 20, 1, 2013); // hour, min, sec, day, month, year
   while (state){
   if ( lastSecond!=second())
   {
       lastMinute = minute();
       lastSecond=second();
       tft.setTextSize(6);
       tft.fillRoundRect(60, 60, 200, 100, 18, RED);
       //tft.fillScreen(BLACK);
       tft.setTextColor(WHITE);
       tft.setCursor(110, 85);
       tft.print(lastMinute);
       tft.setCursor(140,85);
       tft.print(":");
       tft.setCursor(170, 85);
       tft.print(lastSecond);
       //delay(1000);
   }
   if (1)
    {
      // alarm set
      if ((Motor_alarmSecond_end <= lastSecond) && (Motor_alarmMinutes_end == lastMinute))
      {
         state=0;
         digitalWrite(A6, LOW);

      }
       if ((Motor_alarmSecond_end >= lastSecond) || (Motor_alarmMinutes_end >= lastMinute))
         {
          //sound alarm
          digitalWrite(A6, HIGH);
          //setOffAlarm();
         }
     }
   }

//########### MLX90615 @#############
   char i=0,sum=0;

//  for (i=0;i<100;i++){
   score=1;
    while(score==1){
    serialEvent();
    if(sign)
    {
       sign=0;
       for(i=0;i<8;i++)
        sum+=Re_buf[i];
       if(sum==Re_buf[i] )
       {
             TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
             if ((int)TO>=30){
              score=0;
             }
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);
            tft.fillScreen(BLACK);
            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
     }
    }
  }
//####################
   delay(100);
   drawHome();
   return;

}

void menu(){

// drawMenu();

 TSPoint p = ts.getPoint();     // Read touchscreen
 state =1;
// while(state){
// if (p.z > MINPRESSURE && p.z < MAXPRESSURE)
if (p.z > 10 && p.z < 1000)
    {
     tft.setTextSize(3);
            tft.setTextColor(RED);
            tft.setCursor(10, 10);
            tft.print(p.x);
            delay(500);
      /* if (p.y > 743 && p.x < 247 && p.x > 150 && p.y < 875)
        {
          tft.fillRoundRect(5, 5, 50, 30, 8, WHITE);
          delay(70);
          tft.fillRoundRect(5, 5, 50, 30, 8, BLUE);
          tft.drawRoundRect(5, 5, 50, 30, 8, WHITE);
          tft.setCursor(15, 15);
          tft.print("<-");
          delay(70);
          tft.fillRoundRect(5, 5, 50, 30, 8, BLACK);
          currentpage = 0;
          drawHome();
          p.x = 160;
          p.y = 760;
          return;
        }
      if (p.x > 736 && p.x < 855 && p.y > 255 && p.y < 725  )
      {
        tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(10, 10);
            tft.print("UP2");
            delay(500);

      }
      x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
      y = map(p.y, TS_MINY, TS_MAXY,  tft.height(), 0) + 30;
//tft.fillTriangle(250,90, 250, 130, 290, 110, RED);
//   tft.fillTriangle(60,90, 60, 130, 20, 110, RED);
    if (y > 70 && y < 130)
      {
        if (x > 20 && x < 120)
        {
            tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(50, 140);
            tft.print("DOWN");
        }
        if (x > 220 && x < 320)
        {
            tft.setTextSize(3);
            tft.setTextColor(WHITE);
            tft.setCursor(50, 140);
            tft.print("UP");
        }

      }
      */
  }
// }
}
////########## MLX90615    #############
//void serialEvent(){
//  while (Serial1.available()) {
//    Re_buf[counter]=(unsigned char)Serial1.read();
//    if(counter==0&&Re_buf[0]!=0x5A) return;
//    counter++;
//    if(counter==9)
//    {
//       counter=0;
//       sign=1;
//    }
//  }
//}
////########################

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);

void setup()
{

  time_t t = now(); // store the current time in time variable t
  pinMode(A5, OUTPUT);pinMode(A6, OUTPUT);

  tft.reset();
  tft.begin(tft.readID());
//  Serial.begin(9600);
//  Serial.println();
//  Serial.print("reading id...");
//  delay(500);
//  Serial.println(tft.readID(), HEX);

  tft.fillScreen(BLACK);
  tft.setRotation(1);

  currentpage = 0;

  tft.setTextSize(3);
  tft.setTextColor(WHITE);
  tft.setCursor(50, 140);
  tft.print("Loading...");

  tft.setTextColor(tft.color565(255, 255, 0));
  tft.setCursor(30, 70);
  tft.print("By:");

  tft.setCursor(30, 100);
  tft.print("NotesPoint.com GSH.IR");

  for (int i; i < 250; i++)
  {
    tft.fillRect(BAR_MINY - 10, BLUEBAR_MINX, i, 10, RED);
    delay(0.000000000000000000000000000000000000000000000000001);
  }

  tft.fillScreen(BLACK);
  score=14;
  if (EEPROM.read(1)==score){
  address=2;
  tft.setCursor(300, 100);
  tft.print("eeprom writed beffor");
  Heater_alarmSecond_end = EEPROM.read(address);
  Heater_alarmMinutes_end= EEPROM.read(address+1);
  Motor_alarmSecond_end = EEPROM.read(address+2);
  Motor_alarmMinutes_end = EEPROM.read(address+3);
  }
  else{
    tft.setCursor(300, 100);
  tft.print("new eeprom");
    address=1;
  EEPROM.write(address,14);
  EEPROM.write(address+1,10);
  EEPROM.write(address+2,4);
  EEPROM.write(address+3,10);
  EEPROM.write(address+4,0);
  address=1;

  Heater_alarmSecond_end = EEPROM.read(address);
  Heater_alarmMinutes_end= EEPROM.read(address+1);
  Motor_alarmSecond_end = EEPROM.read(address+2);
  Motor_alarmMinutes_end = EEPROM.read(address+3);
  }
  delay(100);
  drawHome();
  setTime(0, 0, 0, 20, 1, 2013); // hour, min, sec, day, month, year
  //########### MLX90615 ############

Serial1.begin(115200);Serial.begin(115200);
  delay(1);
//  Serial1.write(0XA5);
//  Serial1.write(0X45);
//  Serial1.write(0XEA);
  Serial.write(0XA5);
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
//buadrate 115200
  Serial1.write(0XA5);
  Serial1.write(0XAF);
  Serial1.write(0X54);

//#############################

}
//void setup() {
//
//lcd.begin(16,2);
//
//// set cursor position to start of first line on the LCD
//lcd.setCursor(0,0);
////text to print
//lcd.print("   16x2 LCD");
//// set cusor position to start of next line
//lcd.setCursor(0,1);
//lcd.print("   DISPLAY");
//   Serial1.begin(115200);
//   Serial.begin(115200);
//  delay(1);
//  Serial1.write(0XA5);
//  Serial1.write(0X45);
//  Serial1.write(0XEA);
//}

void loop() {

//
//
//
   char cc,i=0,sum=0;

   //  digitalWrite(13, HIGH);
  TSPoint p = ts.getPoint();     // Read touchscreen
//  digitalWrite(13, LOW);

  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);

//   score=1;
//   while(score==1){
for(i=0;i<8;i++){
  i=1;
 serialEvent();
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
//           Serial.print("TO:");
//           Serial.println(TO);
//           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
//           Serial.print("TA:");
//           Serial.println(TA);

             tft.fillScreen(BLACK);
             tft.setTextColor(WHITE);
             tft.setTextSize(3);
             Serial.print("TO:");
             Serial.println(TO);

            tft.setCursor(10, 15);
            tft.print("Temprature :");
            tft.setCursor(10, 50);
            tft.print(TO);
            tft.setCursor(100, 30);tft.print("C");
             TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
             Serial.print("TA:");
             Serial.println(TA);
             delay(100);
   }
  }

 }

}
void serialEvent(){
  char i;
  Serial1.write(0XA5);
  Serial1.write(0X15);
  Serial1.write(0XBA);
  for (i=0;i<30;i++)
  {
    while (Serial1.available()) {

    Re_buf[counter]=(unsigned char)Serial1.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;i=600;
       sign=1;
    }
  }
  }
}

So has anybody this problem with this kind of sensors or other sensors?and why this happened?
Update:
Based of this site i have combined the blinky and mlx90615 uart sample code, and it's working without freeze, the code is shown below:

unsigned char Re_buf[11],counter=0;
unsigned char sign=0;
float TO=0,TA=0;
void setup() {
   pinMode(LED_BUILTIN, OUTPUT);
   Serial.begin(115200);
  delay(1);
  Serial.write(0XA5);
  Serial.write(0X45);
  Serial.write(0XEA);
}

void loop() {
  unsigned char i=0,sum=0;
 digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(50);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(50);
  if(sign)
  {
     sign=0;
     for(i=0;i<8;i++)
      sum+=Re_buf[i];
     if(sum==Re_buf[i] )
     {
           TO=(float)(Re_buf[4]<<8|Re_buf[5])/100;
           Serial.print("TO:");
           Serial.println(TO);
           TA=(float)(Re_buf[6]<<8|Re_buf[7])/100;
           Serial.print("TA:");
           Serial.println(TA);
   }
  }

}
void serialEvent() {
  while (Serial.available()) {
    Re_buf[counter]=(unsigned char)Serial.read();
    if(counter==0&&Re_buf[0]!=0x5A) return;
    counter++;
    if(counter==9)
    {
       counter=0;
       sign=1;
    }
  }
}

I have read this queston: Hardware Serial causes hang-up and i think its related to I2C comunication with TFT LCD by this:

I think I found the solution. As you can see on the photo above, I
used unscreened wires in comparison with the Breadboard. I2C is
definitely very sensitive against EMP, which causes the bus freezes. I
now use screened wires and don´t use the Breadboard anymore. The issue
now occurs very rarely. Unfortunately I still don´t understand the
interdependency to the UART interface. I will now improve the
screening of my wireing. Hopefully, the breakdowns will totaly
diappear.
Re: Hardware Serial causes hang-up
Summary: My final solution, after weeks of detective work is, to use another sensor board.  :smiley-fat:
Obviously the ADXL 345 together with connected UART, provoked by EMP
is the problem. I still don´t know why, but now, using the 10DOF GY-86
board with the MCU5060 IMU, it runs stable in a longtime test, for
over 60 hours! No more freeze!!! I hope this will help someone having
similar problems!

Now it the end of week and i will go to holiday so i wil try newx two days by 16X2 Crystal LCD and printed board to check will it happen again?
Until next two days i will appriciate any sugestion or help.
Thanks a lot.

If you have noise problems with the I2C interface, you should add stronger pullup resistors to the lines (SDA and SCL). For example 4.7kOhm or a bit less.

TBH, I've read your question many times but I still do not understand, what your problem is. What I can see is:

You provided picture with wiring for Arduino Uno, not Arduino Mega. If you are using LCD TFT shield intended for I2C and Arduino Uno, it will not work on Mega – this board has I2C on pin 20 (SDA) and 21 (SCL), not like Uno on pin A4 (SDA) and A5 (SCL). But I guess the LCD TFT shield uses SPI, not I2C. Even if it is SPI, it will not work either (again, different pinout).
You are using HW Serial #1 for debug and also for communication with the sensor. This may be the source of your problems. Use different HW Serial for debug (#1 is recommended) and different for communication with the sensor (e.g. Serial #2). Arduino Mega has 3 HW Serial interfaces. If you are using Uno and not Mega, use SoftwareSerial (but I recommend using smaller baud rate, if possible).


text:
Issue with Arduino car bot, the servo motor moves randomly also it turns hot pretty quickly
I trying to create an Arduino avoiding obstacle car. Using Arduino Uno +shield (sensor sheild v5.0). The problem is that when I upload the code, the servo moves randomly (it doesn't rotate to the right) and becomes hot quickly, it is an SG90 with 5v. I have already checked several times and the hardware seems all right.
I have tried to change the angle of the servo, checked the pins several times - uploaded the code many times I have also used serial.prints. researched on the internet.

#include <NewPing.h>        //Ultrasonic sensor function library. You must install this library

//our L298N control pins
const int LeftMotorForward = 5;
const int LeftMotorBackward = 4;
const int RightMotorForward = 1;
const int RightMotorBackward = 0;

//sensor pins
#define trig_pin A1 //analog input 1
#define echo_pin A2 //analog input 2

#define maximum_distance 200
boolean goesForward = false;
int distance = 100;

NewPing sonar(trig_pin, echo_pin, maximum_distance); //sensor function
Servo servo_motor; //our servo name

void setup(){

  pinMode(RightMotorForward, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);

  servo_motor.attach(11); //our servo pin

  servo_motor.write(90);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop(){

  int distanceRight = 0;
  int distanceLeft = 0;
  delay(50);

  if (distance <= 20){
    moveStop();
    delay(300);
    moveBackward();
    delay(400);
    moveStop();
    delay(300);
    distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);

    if (distance >= distanceLeft){
      turnRight();
      moveStop();
    }
    else{
      turnLeft();
      moveStop();
    }
  }
  else{
    moveForward();
  }
    distance = readPing();
}

int lookRight(){
  servo_motor.write(10);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
}

int lookLeft(){
  servo_motor.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(90);
  return distance;
  delay(100);
}

int readPing(){
  delay(70);
  int cm = sonar.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

void moveStop(){

  digitalWrite(RightMotorForward, LOW);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(LeftMotorBackward, LOW);
}

void moveForward(){

  if(!goesForward){

    goesForward=true;

    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(RightMotorForward, HIGH);

    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(RightMotorBackward, LOW);
  }
}

void moveBackward(){

  goesForward=false;

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorForward, LOW);

}

void turnRight(){

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorBackward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorForward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);

}

void turnLeft(){

  digitalWrite(LeftMotorBackward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);

  delay(500);

  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(RightMotorForward, HIGH);

  digitalWrite(LeftMotorBackward, LOW);
  digitalWrite(RightMotorBackward, LOW);
}

Expected to the servo to rotate 90 degrees, but right now the servo is moving randomly.

If the motor gets hot quickly, there is something broken or it is connected wrong. Please show us your circuit. Are you sure about the polarity of the servos supply voltage?

I think you need to do some rigorous testing of the individual functions of your bot.
Step 1: rename your loop function to "loop_temp" which means it won't run, but it will be retained for later.
Step 2: write a new "loop" function, which sets the LeftMotorForward for 1 second, then stop for 1 second.  And observe the results.
Step 3: repeat Step 2 with LeftMotorBackward, RightMotorForward, etc
Step 4: using serial print, experiment with the output from the sonar to make sure it's delivering the expected results.
Step 5: one at a time introduce your functions and ensure they are each working properly.
Step 6: hopefully you've discovered a bug/fault somewhere, and you can re-introduce your original "loop" function.  Otherwise that function may be the issue.
I've had a look at your code, but don't see anything obviously amiss.  So I'm afraid it may be a process of elimination.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
What hardware do I use to detect an electric current going to a lightbulb and tell if it is turning on and off
I’m doing a project where you have to detect a lightbulb coming on through the electrical current and was wondering what Hardware and what the program is? Can y’all help? Very much appreciated if y’all do.

What kind of Arduino will you be using?

What about a current sensor? The code depends on the sensor. Choose a fitting one and try to interface it with an Arduino. You can always come back with a specific question

I am using an Arduino uno

I never thought about a current sensor. Thank you very much

this part of the title is redundant and it turning on and off

A suitable piece of hardware would be a ACS712 Current Sensor which can be used with any Arduino which runs on 5 volts -for instance an Arduino Uno.
You may find this guide useful in writing the program.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Flow meter using Wemos Mini - ISR not in IRAM!
I'm trying to use a flow meter with Wemos Mini.
Most tutorials are using Arduino boards ( which code and HW work OK ), but since I want this device to send alerts over the internet when abnormal usage/leakage is detected, I want to use Wemos Mini using How to Use Water Flow Sensor - Arduino Tutorial. On top of if will add my code for notifications using Telegram.
BUT - after uploading the original code (before adding Telegram changes ), an error occurs during code run : ISR not in IRAM!
I tried to change Pin - but still getting this error,

Hve you seen this issue on github? They state, that you can avoid this error by prepending ICACHE_RAM_ATTR to ISR functions. Maybe you can try this.

this is an error in the original code and new versions of core check if the ISR handler is in IRAM, because without ICACHE_RAM_ATTR  the handler sometimes worked and sometimes not

This happens because of conflicts between Serial and external interrupts
Put ICACHE_RAM_ATTR before your interrupt function, like this  ICACHE_RAM_ATTR void ISR()

For WEMOS or NODEMCU you must predefine  interupt routine for example
void ICACHE_RAM_ATTR ServiceLimitSwitchUpperShield_12_D6();
//it is solve problem for ATTACHINTERRUPT - you must predefine this method before use setup (very important )
Then this message error ISR not IRAM will be not displayed .
In a setup you can for example define
attachInterrupt(digitalPinToInterrupt(12), ServiceLimitSwitchUpperShield_12_D6 , FALLING );
Look for page
https://community.blynk.cc/t/error-isr-not-in-iram/37426/23

this is not true


text:
How to wake up Arduino with an rtc?
I am doing a data logger with an Arduino Mega2560 and I want to use a code to make it sleep when no measure is needed and wake it up with an RTC when time comes. The reason I want this is because I intend to run the code on a Pro Mini later so I need to save as much energy as I can. I am able to put the arduino to sleep using the alarm interrupt when a minute is passed but it doesn't wake up from sleep afterwards.
Here is the code I am using:

#include <Wire.h>
#include <RtcDS3231.h>
#include <avr/sleep.h>

const byte interruptPin = 2;
volatile bool alarm = 0;
volatile byte counter = 0;

RtcDS3231<TwoWire> rtcObject(Wire);

void setup() {

  Serial.begin(9600);
  Serial.println("Initialisation");
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);

  rtcObject.Begin();

  RtcDateTime timestamp = RtcDateTime(__DATE__, __TIME__);
  rtcObject.SetDateTime(timestamp);

  rtcObject.Enable32kHzPin(false);
  rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeAlarmOne);

  DS3231AlarmTwo alarm2(
    0,
    0,
    0,
    DS3231AlarmTwoControl_OncePerMinute);

  rtcObject.SetAlarmTwo(alarm2);
  rtcObject.LatchAlarmsTriggeredFlags();

}

void loop() {
  if (alarm == true){
    handleAlarm();
    if (counter == 1){
      mesure();
      counter = 0;
      delay(100);
      sleepNow();
    }
  }
}

void handleInterrupt() {
  alarm = true;
  counter ++;
  Serial.println(counter);
}

void handleAlarm() {
  alarm = false;
  rtcObject.LatchAlarmsTriggeredFlags();
}

void mesure(){
  RtcDateTime timestamp = rtcObject.GetDateTime();

  Serial.print("time interrupt at: ");
  char time[10];

  sprintf(time, "%d:%d:%d",
          timestamp.Hour(),
          timestamp.Minute(),
          timestamp.Second()
         );
Serial.println(time);
}

void sleepNow() {
  Serial.println("Entering sleeping");
  delay(100);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // sleep mode is set here
  sleep_enable();                         // enables the sleep bit in the mcucr register
  attachInterrupt(digitalPinToInterrupt(interruptPin),wakeUpNow, FALLING);  // use interrupt 0 (pin 2) and run function
  sleep_mode();                           // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

  sleep_disable();         // first thing after waking from sleep: disable sleep...
  detachInterrupt(digitalPinToInterrupt(interruptPin));      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
Serial.println("Woke up");
delay(100);
}

I want to understand how to wake it up properly so I can later make it sleep first in the loop and wake it up only if an interrupt is detected from the rtc.
Thank you for your help !

Try to sleep in IDLE mode, or to attach the interrupt in LOW mode.

I tried both of your advice but none of them worked for me...

You may not need to use an RTC to wake up. Jeelabs has done extensive work on low-power consumption maybe you just need to use the jeelib library from Github. They even sold (not anymore) ultra low power optimized UNO compatible devices (https://jeelabs.org/202x/jnc/). You find jeelib on github on the linked page.
Look at the Sleepy class. It does some low level power saving magic directly with the hardware. It would be interesting to extract that class from Ports.h and Ports.cpp and try if it works standalone.
You simply use it with: Sleepy::loseSomeTime(32); and it will power down the whole MCU for some time. https://github.com/jeelabs/jeelib/blob/635113edea74b1290713360649679c3a13016304/Ports.h#L346
It uses the watchdog timer of the MCUs:
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

If you use the DS3232RTC library then you can setup an alarm which is like an alarm. I have put a good tutorial on how to do that below.
https://thekurks.net/blog/2018/2/5/wakeup-rtc-datalogger
There is also other threads on arduino.cc you should check out. They might have additional work-arounds.
https://forum.arduino.cc/index.php?topic=333654.0
https://forum.arduino.cc/index.php?topic=99588.0


text:
Sending Integer > 1 Byte from Android to Arduino over Serial
I´m using
public abstract void write(int b) throws IOException;

from class OutputStream on Android Studio to sent Integer (degrees from 0 to 360) to the Serial Port of my Arduino over HC06 Bluetooth module.
Degrees from 0 to 256 are read well by using
 int angle = Serial.read();

Values over 256 (1 Byte) are received as 0 are something weird.
I tried using
 Serial.parseInt();

as it should return an long int but all I get is one digit mostly 0.
I also tried using
Serial.readBytes(threeDigitsInt, 3);
angle = (threeDigitsInt[0] * 100) + (threeDigitsInt[1] * 10) + threeDigitsInt[2];

but I cannot tell what ends up in the array. Definitly not the correct single digit. I tried char[] and byte[] but I´m not able to reconstruct my send Integer value.
Summary: I want to send 360 as Integer from Android and have it as Integer on Arduino.
Appreciate your help!

You are only sending one byte from 0 to 255. Read the manual. https://developer.android.com/reference/java/io/OutputStream.html#write(int)

Ok. I see you´re right!
Can you help me parse that int angle into an byte b [ ] so I can use the
   public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

You can't just throw data randomly at a serial connection. You need to have some kind of format so the receiver knows what byte is what.

Hm. I mean the format is recognized well on Serial.read()

First off, you are only sending one byte from Android:

public abstract void write (int b)
Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

OutputStream.write(byte) can never write more than one byte.
Also it's clear you have no clue about what format the data is sent in if you are trying to then read 3 bytes and use Binary Coded Decimal to reconstruct it.
Instead I suggest you work in a purely ASCII format. Forget bytes. Bytes are not what you want, unless you feel like spending some extra time defining, and then implementing, your own protocol.
Start by formatting your data into an ASCII printable string.  If Android Java is anything like normal Java I'd start by turning your integer into a string with proper line endings.  Something like:
String val = String.format("%d\n", angle);

Then get the bytes that represent that formatted string:
byte[] valBytes = val.getBytes();

Now you have a valid byte array containing your textual representation of the data that you can send with OutputStream.write(byte[]).
Now your task is to read that data on the Arduino.  That means reading each byte that arrives in turn storing it away in some form until you receive the \n line ending.  At that point you can take each byte as a string and convert them into an integer again.
It's possible to do that on the fly:
static int angle = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == '\n') {
        Serial.print("I got: ");
        Serial.println(angle);
        angle = 0;
    } else if ((c >= '0') && (c <= '9')) {
        angle *= 10;
        angle += (c - '0');
    }
}

Basically, have a variable that stores the incoming angle. For each character that arrives on the serial port - if it's a line ending \n then do whatever with the angle value. If it's a character between 0 and 9 then multiply your angle by 10 (decimal shift left), convert your character to the equivalent integer by subtracting character '0', and add it to your angle.

Angle does not receive any value?

Maybe Android is sending things differently. You should first confirm exactly what is being sent by Android.

Also test the Arduino separate from Android. If it works using the serial monitor by typing in numbers then the Arduino code is fine.

Alright thanks a lot. I´ll take my time and try it today!


text:
How to include Vref in thermistor temperature calculation?

simulate this circuit – Schematic created using CircuitLab
This is the code that I'm using to get the temperature:
#define COEFF_A 0.8662984364E-03
#define COEFF_B 2.780704551E-04
#define COEFF_C -0.9395108479E-07

float VRT, Temp;
float Vref = 2.52;

void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
}

void loop() {
  long Resistance;
  VRT = analogRead(A3);
  Resistance = 10000 / ((1023.0 / VRT) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
  Temp += -273.15;
  Serial.println(Temp);
  delay(500);
}

I know that the calculation should be: V = Vref × VRT ÷ 1023 but i don't know how to implant it in this code, any help appreciated.

Update
After Edgar Bonet answer, the edited code is:
#define COEFF_A 0.8662984364E-03
#define COEFF_B 2.780704551E-04
#define COEFF_C -0.9395108479E-07

float VRT, Temp, VR;

void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
}

void loop() {
  long Resistance;
  VRT = analogRead(A3);
  VR = 2.52 * VRT / 1024;
  Resistance = 10000 * VR / (2.52 - VR);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
  Temp += -273.15;
  Serial.println(Temp);
  delay(500);
}

But the temperature reading is 2 centigrade less than what it should be, when i remove the analogReference(EXTERNAL); it shows the normal/correct temperature readings.

The formula to get the analog voltage from the ADC reading is:
    V = Vref × reading ÷ 1024
(yes, it's 1024, not 1023). The formula to get the thermistor resistance
from the measured voltage is:
    R = Rref × V ÷ (Vref − V)
where Rref is your 10 kΩ pull-up. You can combine these
two formulas in order to get the resistance directly from the ADC
reading:
    R = Rref × reading ÷ (1024 − reading)
You may notice that, while doing this simplification, Vref
cancels out. It's not an error. The readings you get with this setup are
indeed independent of your reference voltage.

Update 1: After the OP's edit, we now have a completely different
question. The question is now: how come the readings do depend on the
reference voltage that is used, whereas in theory they should not.
The answer lies most likely in the ADC calibration. If high accuracy is
a requirement, the correct formula for the measured voltage is
    V = Vref ×
(reading + Eoff) ÷ (1024 + Egain)
where Eoff and Egain are the offset error and the
gain error respectively. These errors are not knows a priori, and they
are usually neglected when the accuracy requirement is low. The
datasheet only gives constraints on how big these errors can be. The
actual values depend on the specific microcontroller and can somewhat
depend on the reference voltage. The only solution to get rid of these
errors is to calibrate your own ADC. See Response of the Arduino
ADC for an example on how this could be done.

Update 2: If I had to program this in an Arduino, I would rather
simplify the calculations as much as possible before coding:

do not compute the measured analog voltage, nor the resistance, as
they are not needed
compute instead the ratio R/Rref directly from the analog
reading
rewrite the calibration polynomial as a function of
log(R/Rref) instead of log(R) (which actually means
log(R/(1 Ω)))
optimize the evaluation of the polynomial by using
Horner's method.

With these optimizations, we get:
// Coefficients of polynomial fit of log(R/Rref) -> 1/T.
const float c0 = 3.3540165e-3;
const float c1 = 2.5416075e-4;
const float c2 = -2.5959644e-6;
const float c3 = -9.3951087e-8;

// Convert ADC reading to temperature in deg. C.
static float temperature(int reading)
{
    float R_ratio = reading / (1024.0 - reading);  // = R / Rref
    float x = log(R_ratio);
    float inverse_T = c0 + x*(c1 + x*(c2 + x*c3));
    return 1/inverse_T - 273.15;
}

void loop()
{
    int reading = analogRead(A3);
    Serial.println(temperature(reading));
    deay(500);
}

so in this example it should be this: Resistance = 2.52 * VRT / (1024 - VRT);, correct?

No. Your reference resistance is 10 kΩ, not 2.52 Ω.

but the readings is wrong, Resistance = 10000 * VRT / (1024 - VRT); did i missed something? it's like 2C less...

I don't understand your last comment. Please, edit your original question if there is something missing.

when i use your suggested formula Resistance = 10000 * VRT / (1024 - VRT); the temperature is 2 centigrade less than what it should be.

unless i remove the analogReference(EXTERNAL);, that means it don't ignore "cancel" the Vref!

Update your question.

Edited the question.

The article you linked is a piece of gold, thank you.

Note: I formulated this answer on your previous, deleted question.
Whether the voltage increases or decreases with rising temperature depends on your circuit: if you use the ntc with R1 as a pull-down, the voltage will increase on rising temperature. If R1 is a pullup the voltage will fall respectively.
Concerning your calculation: I highly recommend using a look-up table instead. Those are some hard calculations, and at the arduinos resolution you'll be fine with a LUT with about 64 entries. There're tools out there which generate LUTs for a given NTC setup (I personally like this tool).

uh i feel so bad now that i deleted that question while you was answering it! sorry...

the code that i posted in my question does all the calculations, i don't need to re-do it, i just need to add the Vref into the calculation and don't know how... it's a pull-down btw.


text:
Which Arduino-compatible microcontroller for 2 continuous analog audio recording and 2 digital pin snapshots every second?
Apologies if the title is not very well worded. I'm new to electronics and trying to learn more about embedded systems too. I have a small project that requires recording an analog audio input at 8-bit at 40kHz and saving it every second in a SD card.
Although I know that I can do that with an ATmega328P chipset, I'm not sure if the processing power of ATmega328P will be good enough for further extension of the project.
Ideally I would like to be able to record two sound sources at the same time at around 40kHz -- 16 or 24-bit would be perfect, and capture two sensory data also every second.
This device should be able to run on a reasonably sized battery for at least two hours, but ideally up to eight hours.
I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project and the current draw of a Cortext-M3 series might be too much for this project too.
My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements -- in terms of processing power, or do I have to upgrade to something like the AT91SAM3X8E?

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements

No. Not in the slightest.
Your primary requirement of sampling audio at, basically, CD quality (or better) requires the use of a proper CODEC chip - and to drive that you require a microcontroller that has I2S. None of the 8-bit AVR chips have that.
On top of that you will need a LOT of memory. Far far more than an 8 bit Arduino has.  Two channels of 16 bit audio at 44100Hz (CD quality) requires 176400 bytes per second.
You will need double that.
To both continuously record and save the data you will require DMA to do the recording.  The DMA reads the incoming data from I2S and stores it in one buffer. When that buffer is full you generate an interrupt and switch to a second buffer. You can then save the first buffer to SD - assuming that it can be done in under a second.  Note that SD cards, when controlled by SPI as they generally are on microcontrollers, are generally quite slow.
So with all that in mind:

I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project

Overkill? No. Not suitable since it is not up to the task. Yes, it has I2S. Yes, it has DMA. But it doesn't have anywhere near enough memory.  You need for the audio alone 350 kilobytes (the SAM3X8E has up to 100 kilobytes) - not to mention memory required by the SD card's buffers.
So you're looking for a microcontroller that has full I2S support, DMA, and around half a megabyte of memory.  And those aren't small and cheap like the Arduino's 8-bit AVRs.

Great, thanks a lot! Do you think there is a way to write down the samples at the time of interrupt -- say every 20us, in a temporary fast but small RAM and then write that down to the SD card every second. This way the microcontroller itself wouldn't need to have the extra memory embedded inside.

Also the whole idea of buffering the data is to not have the SD card on all the time, just to lower the power consumption. If we ignore that for now, do you think a mega328 can write real-time data to a (high quality, fast) SD card without any delays?

As for the temporary cache, maybe some fast EEPROM would work?

No, and no. You need a more powerful MCU.

"write real-time data to a (high quality, fast) SD card without any delays?" The possible speed of the SD card is not important as long as you use SPI. To reach the high data speeds, you need to use the parallel data interface. And even with that most like the microcontroller (assuming you have one, that is up to the task in general) will be the bottleneck. So the possible speed of the SD card doesn't really matter


text:
Can't print out a field with ArduinoJSON
I'm trying to create a command interpreter. Allowed commands are stored in a JSON document inside SPIFFS. If I send an allowed command, it doesn't print the field associated with that value (end of receiveMsg function), can someone help me to figure out what the problem is? Here's the full code.
EDIT: added minimal code
EDIT 2: solved, but not entirely. I fixed readFile function, but I cannot print out the first field, it appears to be empty. Json is { "ssid"="aaa", "password":"bbb"}, password is printed out, but not ssid. Changing position, password is empty, ssid is printed out. I can resolve by adding a first empty field, but why it happens?

#include<ESP8266WiFi.h>
#include<ArduinoJson.h>
#include<stdio.h>
#include<string.h>
#include "FS.h"

DynamicJsonDocument* functions;

DynamicJsonDocument* readFile(String filename) {
  File file = SPIFFS.open(filename, "r");
  if (!file) {
    Serial.println("Failed to open the file");
  }
  size_t size = file.size();
  if (size > 1024) {
    Serial.println("File size is too large");
  }
  std::unique_ptr<char[]> buf(new char[size]);
  file.readBytes(buf.get(), size);
  DynamicJsonDocument* jsonBuffer = new DynamicJsonDocument(200);
  DeserializationError error = deserializeJson(*jsonBuffer, buf.get());
  if (error) {
    Serial.println("Failed to parse file");
  }
  return jsonBuffer;
}

int connection() {
  DynamicJsonDocument *settings = readFile("/wifiSettings.json");
  const char* ssid = (*settings)["ssid"];
  Serial.println("Printing ssid");
  Serial.println(ssid);
  const char* psw = (*settings)["password"];
  Serial.println("Printing password");
  Serial.println(psw);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, psw); //Connect to wifi
  Serial.println("Connecting to Wifi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
  return WiFi.status();
}

void setup() {
  Serial.begin(115200);
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }
  if (connection() != WL_CONNECTED)
    Serial.println("Not connected");
  else
    Serial.println("Connected");
}

Could it be that you're losing all your data as you pass objects around copying them like that? A better strategy would be to have a single document as a global object, and load the data into that once at start up (after all, it's not going to change, is it?)

add the output from Serial Monitor to the question? do you sent the command from Serial Monitor? contains the  command a space? Is the command from Serial Monitor terminated with new line characters?

I tried modifying readFile function by returning a DynamicJsonDocument pointer, but the problem still remains. The output from serial monitor is empty, even If I put a fixed key like "test" (where "test":"test")

so this is not a minimal sketch to reproduce the problem?

Not properly, I changed it to minimal

Solved. I was using static allocation instead of dynamic. I'll upload the fix soon


text:
How can I stop a loop when using a servo with a Key input?
How can I stop my following code using a key?
Basically the code should run the servo in a loop if "t" is pressed and stop the loop if "s" is pressed.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position
int servodata;

void setup() {
  myservo.attach(8);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

}

void loop() {
  if (Serial.available()>0){
    servodata = Serial.read();
    while (servodata == 't'){
           for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
  }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(3);                       // waits 15ms for the servo to reach the position
    }
    }
  }
  while (servodata == 's'){
    break;
  }
}

thank you for help.

Basically: Don't use blocking for loops and delays. Delays are just busy waiting. Look into a non-blocking coding style like demontrated in the BlinkWithoutDelay example, that comes with the Arduino IDE. It has been explained throughout the internet.

separate the value of servodata and the servo motion ... use a flag variable ... for example, name the flag go ... if go is true then run the motor ( if (go) { ) ... read the value from serial and set go accordingly ... that way the servo code is not inside the if serial loop

could you post and example? thanks

why do you need a for loop to position the servo?

Here is a quick and dirty solution, where each loop() iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:

wait for the “start” command
then sweep back and forth in an infinite loop
stop at any point if you receive the “stop” command

void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}

Note that this approach has a couple of drawbacks:

As this is blocking code, you cannot easily extend the program to do
other things.
The sweeping runs always start at position 0, instead of resuming
from the position that was current on the last “stop” command.

If you need anything more sophisticated, you should go to a non-blocking
approach based on a Finite State Machine (c.f. jsotola's
comment). Note that you can get away with delay(3);, as it is a quite
short delay, but you would have to break the sweeps into one step per
loop() iteration.
I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.


text:
Parent class callback from child class
I want the Parent class to pass a pointer to a callback function to the child class when the child class is created. I got this working when the parent was the sketch thanks to this post:
In this example, the parent was the .ino file, i.e. not a class but a collection of functions. This code worked fine.
However, I need to be able to make the call to the child constructor from a within a class as shown in the code below. I get I get an "invalid use of non-static member function on the line child = new Child ( handlerDispatcher );
Here is the complete code:
class Child {
public:
    typedef void ( *callback_t ) ( uint8_t, uint8_t );

    callback_t callback;

    //  Constructor
    Child ( callback_t _callback ): callback ( _callback ) {}

    void doCallback ( uint8_t id, uint8_t index ) {
        callback ( id, index );
    }

    void makeCallbacks () {
        doCallback ( 1, 0 );
        doCallback ( 2, 1 );
        doCallback ( 3, 2 );
    }
};

class Parent {
public:
    Child *child;

    Parent () {}

    void handlerDispatcher ( uint8_t id, uint8_t index ) {
        ( this->*callbackHandlers [ index ] ) ( id );
    }

    typedef void ( Parent:: *handlerPointer ) ( uint8_t );
    handlerPointer callbackHandlers [ 3 ] = {
        &Parent::handler1,
        &Parent::handler2,
        &Parent::handler3,
    };

    void handler1 ( uint8_t index ) { echo ( index ); }
    void handler2 ( uint8_t index ) { echo ( index ); }
    void handler3 ( uint8_t index ) { echo ( index ); }
    void echo ( uint8_t value ) {
        Serial.print ( "Got: " );
        Serial.println ( value );
    }

    void configure () {
        child = new Child ( handlerDispatcher );

    }
    void test () {
        child->makeCallbacks ();
    }
};

Parent parent;
void setup () {
    Serial.begin ( 115200 );
    parent.configure ();
    parent.test ();
}

void loop() {}

Use virtual functions. On object of type Child, fnc2 defined in Parent will call fnc1 of class Child:
class Parent {
public:

  virtual void fnc1() {
  }

  void fnc2 {
    ...
    fnc1();
    ...
  }
}

class Child : public Parent {
public:
  virtual void fnc1() {
    ...
  }
}

For the child drop the virtual and append a final - unless you want to have grandchildren.  Also you could make the parent's fnc1() pure virtual.

@Majenko, and then I would have to explain it :-)

I have expanded my answer to do just that.

It is because
void Parent::handlerDispatcher ( uint8_t id, uint8_t index )

is not
void ( *callback_t ) ( uint8_t, uint8_t )

The closest equivalent would be:
void ( *callback_t ) (Parent *, uint8_t, uint8_t )

Though I am not sure off hand if that is even possible.
But it seems you are trying to do something insanely convoluted and complex which would be made far simpler if you just used object inheritance and forget about callbacks.
With object inheritance a child object can implement the functions that a parent object defines. That way you end up with a single object instance which is a combination of the parent functions and the child functions, one overlaid on the other.
To build on Juraj's excellent answer and add a bit of explanation, if you take the following parent object:
class Parent {
public:

  virtual void fnc1() = 0;

  void fnc2 {
    fnc1();
  }
};

What we have here are two functions in the parent.  fnc2() simply calls fnc1() as an example.  However fnc1() isn't a normal function - it's a pure virtual function. That is akin to an interface in Java. It's a placeholder in the parent that says "This function will exist, but the child will implement it, not me".  If you try and instantiate a Parent object the compiler will complain that certain functions are pure virtual and the object can't be created.
So then you create a child class which takes the parent class and extends it with the body of any pure virtual functions that are needed, and can also add more.  For example:
class Child : public Parent {
public:
  void fnc1() final {
    ...
  }
};

Here we only have one function - fnc1(), which is marked as final.  The final keyword is kind of the opposite of the virtual keyword.  virtual means "This function will be overridden by the child". final means "I have overridden this, and nothing else can now override it". It's not essential, but it does help with the compiler's optimiser somewhat, since it no longer needs to worry about further inheritance of that function.
So now you can create a Child instance, and you will have access to all the parent functions and data, as well as all the child functions and data.  Simply calling fnc2() on this child instance will call that function on the parent, which then itself calls fnc1() which is implemented by the child.
And thanks to something called polymorphism, the child can be seen as a parent for all intents and purposes (though if you look at it as a parent you won't see any of the child's own functions).
To wrap it all up, here's a full example that uses two different child classes and stores pointers to them in an array of parents (so the children are seen as if they are objects of class Parent), iterates through them, and calls the parent's fnc2() function:
class Parent {
    public:
        virtual void fnc1() = 0;
        void fnc2() {
            fnc1();
        }
};

class Child1 : public Parent {
    public:
        void fnc1() final {
            Serial.println("I am child 1");
        }
};

class Child2 : public Parent {
    public:
        void fnc1() final {
            Serial.println("I am child 2");
        }
};

Child1 c1;
Child2 c2;

Parent *objects[2] = {
    &c1, &c2
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 2; i++) {
        objects[i]->fnc2();
    }
}

void loop() { }

The serial output from that program is:
I am child 1
I am child 2

Which I think is the end effect that you are looking for.


text:
Not getting any output from ECG sensor AD8232
I am trying for the beginning to run a simple Arduino code in order to test the functionality of the ECG sensor. What I am getting on the output are some random values around 600 or around 200.
I connected everything the same as in any tutorial about AD8232:
GND -> GND, 3.3V -> 3.3V, L0+ -> digital pin 10, L0- -> digital pin 11, output -> analog pin A0.
I placed the sensor pads on my body like in pictures (forming a triangle), but regardless of putting the electrodes or not, I always get the same floating signal.
Here is Arduino code:
int ecg;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(10,INPUT);
  pinMode(11,INPUT);

}

void loop() {
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
    Serial.println('!');
  }
    else{
    // send the value of analog input 0:
    Serial.println(analogRead(A0));
    }
    //Wait for a bit to keep serial data from saturating
    delay(1);
}

When I run this code I get only "!" on the output, no matter where I put the electrodes on my body. When I comment "if" and "else" parts of the code and print directly only reading from the pin A0, I get those random floating values, like on the image.

I also tried another custom built ECG sensor, but the results are the same. I haven't found the solution anywhere. It is not about the noise, because when I touch the metal box of my PC, I only reduce the values but there is still nothing on the output.

I only reduce the values but there is still nothing on the output.
Have you tried measuring using a laptop that isn't connected to AC? Not to mention, have you added large electrolytic capacitors to the 3.3V bus and made sure it can supply enough current for the sensor?

It is OK to accept your own answer as a solution to the problem. I think you get 15 rep for it.

The problem was that I connected GND on the other half of the protoboard and there was no connection. I thought that the whole length of the protoboard is on the same potential for + and -, so GND wasn't connected. After connecting GND pin correctly, all worked perfectly.


text:
OLED not updating display
I'm trying to connect a GPS unit (GY-GPS6MV2) and an OLED screen as in the diagram below (green connector is GPS; VCC, RX, TX, GND left to right):

Here's the code I've come up with:
#include <Wire.h>
#include <Adafruit_SH1106.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define OLED_RESET 4
Adafruit_SH1106 display(OLED_RESET);
static const int RXPin = 5, TXPin = 3;
static const uint32_t GPSBaud = 9600;
float vkph;
float vmps;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

void setup(){
  Serial.begin(9600);
  ss.begin(GPSBaud);
  display.begin(SH1106_SWITCHCAPVCC, 0x3C);
  display.display();
  delay(2000);
  display.clearDisplay();
}

void loop(){
  while (ss.available() > 0){
    gps.encode(ss.read());
    vkph = gps.speed.kmph();
    vmps = gps.speed.mps();
    if (gps.location.isUpdated()){
      Serial.print("Position: ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" : ");
      Serial.println(gps.location.lng(), 6);
      Serial.print("Speed: ");
      Serial.print(vmps);
      Serial.print(" m/s");
      Serial.print(", ");
      Serial.print(vkph);
      Serial.println( " km/hr");

      display.clearDisplay();
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println("Hello"); // Changing this to display.println(vmps);
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.println("World"); // Changing this to display.println(vkph);
      display.display();
      delay(1000);

    }
  }
}

The GPS outputs to the serial monitor fine, and the screen displays "Hello \n World" as expected. But when I make the changes indicated in the comments to the display part of the code, the display just shows its splash screen, flashing when the GPS updates.
How can I get the display to show the speeds in m/s and km/hr?

Maybe you need to add delay() in your code,I am not sure.

display.clearDisplay();
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println("Hello"); // Changing this to display.println(vmps);
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.println("World"); // Changing this to display.println(vkph);
      display.display();
      delay(1000);

Why, and where?

Because OLED doesn't have a time to keep showing.

Is this an answer or a question? Also please elaborate more, so that the answer is really helpful

I tried this, even before you posted the edit. Same problem, only now it takes 1000 milliseconds to flash the splash screen.

Have you also added the delay after the GPS display code?


text:
arduino mega multi integer values reading on other arduino mega
I need two Arduino communications.
The master arduino from the slave arduino needs to read 16 signals.
The sample serial port output from the slave is as follows.
@ 125 @ 13 @ 874 @ 1023 & 950 @ 547 @ 965 @ 852 @ 654 @ 478 @ 0 @ 456 @ 996 @ 789 @ 556 @ 847 @

I need to throw this output into an integer array.

So the problem is only to split up the received string? Then maybe this article from Majenkos Blog can help you

Is the & a typo? Should that have been @? Also, are there line endings added after each block of 16 values?

You can use the following C functions:

strtok: to split a string (see strtok).
atoi: to convert a string to an integer (see atoi).


text:
Arduino Every 25k PWM signal
I have written a class for generating a 25khz pwm signal for the Arduino Nano. This works great (pin 9 and 10 only) on the Nano. I want to switch to Arduino Every; this code does no longer work (the registers are unknown ‘not declared in this scope’ is the compiler error). The Every is suppose to be a drop in replacement for the Nano; how to generate a 25KHz PWM on the Arduino Every?

#include <Arduino.h>
#include "HixPinPWM25KHz.h"

HixPinPWM25KHz::HixPinPWM25KHz(int nPinNumber): HixPin(nPinNumber) {
}

void HixPinPWM25KHz::begin() {
  //25KHz PWM only supported on ping 9 and 10
  if ( (m_nPinNumber != 9) && (m_nPinNumber != 10) ) {
    return;
  }
  // Configure Timer 1 for PWM @ 25 kHz.
  TCCR1A = 0;           // undo the configuration done by...
  TCCR1B = 0;           // ...the Arduino core library
  TCNT1  = 0;           // reset timer
  TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
  TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
  ICR1   = 320;         // TOP = 320
  pinMode(m_nPinNumber, OUTPUT);
  analogWrite(50);
}

void HixPinPWM25KHz::analogWrite(float percent) {
  int value = (int) ( (percent * (float)320) / (float)100 );
  switch (m_nPinNumber) {
    case 9:
      OCR1A = value;
      break;
    case 10:
      OCR1B = value;
      break;
    default:
      // no other pin will work
      break;
  }
}

did you try the "Registers emulation" "ATMEGA328" in Tools menu of Arduino IDE? EDIT: I did. It doesn't work for Timer1 registers

A "drop-in replacement" does not mean "exactly the same". It means you get the same footprint and IO pins. It does not mean that you get the exact same internal architecture. Step one must always be read the datasheet for the chip and learn about the internal workings of it.

The Every uses a ATMega4809, which has a very different timers than the nano's ATmega328. The advantage is that it has a mux, so almost every pin can be selected as a output for one of the four timers.

@Juraj also tried emulation "ATMEGA328" (just to confirm), this does not solve the issue. Still getting the same compiler error.


text:
Serial Communication with a Serial device
I have a blood glucose meter which supports downloading data to computer using a serial cable and its own software. I made a serial cable for this with a usb to ttl pl2303 and its working. I can download the data from the device to my pc using that software but now I want get the data to my arduino using serial communication. I have a serial monitor software which detects the communication between the device and the software usin com port.
Can any one please tell me how to get the data to my arduino?
I have attached the dump file from that serial monitor.
[31/08/2019 21:32:16] - Open port COM12 (C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe)

[31/08/2019 21:35:10] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

[31/08/2019 21:35:10] Written data (COM12)
    55                                                U
[31/08/2019 21:35:11] - Close port COM12

[31/08/2019 21:35:11] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

[31/08/2019 21:35:11] Written data (COM12)
    05                                                .
[31/08/2019 21:35:12] - Close port COM12

[31/08/2019 21:35:12] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

[31/08/2019 21:35:13] Written data (COM12)
    05                                                .
[31/08/2019 21:35:13] Read data (COM12)
    01 47 6c 75 63 6f 73 65 0d 0a 02 31 2c 32 30 31   .Glucose...1,201
    38 2c 30 37 2c 32 30 2c 30 31 2c 30 30 2c 31 2e   8,07,20,01,00,1.
    31 2c 6d 6d 6f 6c 5f 4c 0d 0a 32 2c 32 30 31 38   1,mmol_L..2,2018
    2c 30 37 2c 32 30 2c 30 31 2c 30 30 2c 31 2e 31   ,07,20,01,00,1.1
    2c 6d 6d 6f 6c 5f 4c 0d 0a 33 2c 32 30 31 38 2c   ,mmol_L..3,2018,
    30 37 2c 32 30 2c 30 31 2c 33 37 2c 32 2e 34 2c   07,20,01,37,2.4,
    6d 6d 6f 6c 5f 4c 0d 0a 34 2c 32 30 31 38 2c 30   mmol_L..4,2018,0
    37 2c 32 30 2c 30 31 2c 33 36 2c 31 2e 31 2c 6d   7,20,01,36,1.1,m
    6d 6f 6c 5f 4c 0d 0a 35 2c 32 30 31 38 2c 30 37   mol_L..5,2018,07
    2c 32 30 2c 30 31 2c 33 35 2c 33 32 2e 37 2c 6d   ,20,01,35,32.7,m
    6d 6f 6c 5f 4c 0d 0a 03 04                        mol_L....
[31/08/2019 21:35:14] - Close port COM12

.
--------------------------------------
#   Time                Function                                                Dir   Status           Data                                                        Data (chars)       Data length   Req. length  Port        Comments
0   31/08/2019 21:32:16 IRP_MJ_CREATE                                           DOWN                   C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe                                 COM12
1   31/08/2019 21:32:16 IRP_MJ_CREATE                                           UP    STATUS_SUCCESS   C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe                                 COM12
2   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      DOWN                   19 01 00 00                                                 ....                  4                       COM12
3   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      UP    STATUS_SUCCESS                                                                                COM12
4   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
5   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   80 25 00 00                                                 €%..                  4                       COM12
6   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   DOWN                                                                                COM12
7   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   UP    STATUS_SUCCESS   00 00 08                                                    ...                   3                       COM12
8   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          DOWN                                                                                COM12
9   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          UP    STATUS_SUCCESS   1a 00 00 1a 11 13                                           ......                6                       COM12
10  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       DOWN                                                                                COM12
11  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       UP    STATUS_SUCCESS   00 00 00 00 00 00 00 00 00 08 00 00 00 02 00 00             ................      16                      COM12
12  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK)       DOWN                                                                                COM12
13  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
14  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   80 25 00 00                                                 €%..                  4                       COM12
15  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   DOWN                                                                                COM12
16  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   UP    STATUS_SUCCESS   00 00 08                                                                          3                       COM12
17  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          DOWN                                                                                COM12
18  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          UP    STATUS_SUCCESS   1a 00 00 1a 11 13                                           ......                6                       COM12
19  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       DOWN                                                                                COM12
20  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       UP    STATUS_SUCCESS   00 00 00 00 00 00 00 00 00 08 00 00 00 02 00 00             ................      16                      COM12
21  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      DOWN                   00 4b 00 00                                                 .K..                  4                       COM12
22  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      UP    STATUS_SUCCESS                                                                                COM12
23  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS)            DOWN                                                                                COM12
24  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS)            UP    STATUS_SUCCESS                                                                                COM12
25  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR)            DOWN                                                                                COM12
26  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR)            UP    STATUS_SUCCESS                                                                                COM12
27  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL)   DOWN                   00 00 08                                                    ...                   3                       COM12
28  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL)   UP    STATUS_SUCCESS                                                                                COM12
29  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_CHARS)          DOWN                   1a 00 00 1a 11 13                                           ......                6                       COM12
30  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_CHARS)          UP    STATUS_SUCCESS                                                                                COM12
31  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW)       DOWN                   01 00 00 00 40 00 00 00 00 08 00 00 00 02 00 00             ....@...........      16                      COM12
32  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW)       UP    STATUS_SUCCESS                                                                                COM12
33  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS)    DOWN                                                                                COM12
34  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS)    UP    STATUS_SUCCESS   f0 00 00 00                                                 ð...                  4                       COM12
35  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS)       DOWN                   00 00 00 00 00 00 00 00 2c 01 00 00 00 00 00 00 2c 01 00 00 ........,.......,...  20                      COM12
36  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS)       UP    STATUS_SUCCESS                                                                                COM12
37  31/08/2019 21:32:26 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
38  31/08/2019 21:32:26 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
39  31/08/2019 21:32:31 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
40  31/08/2019 21:32:31 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
41  31/08/2019 21:32:35 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
42  31/08/2019 21:32:35 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
43  31/08/2019 21:32:38 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
44  31/08/2019 21:32:38 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
45  31/08/2019 21:32:44 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
46  31/08/2019 21:32:44 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
47  31/08/2019 21:33:42 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
48  31/08/2019 21:33:42 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
49  31/08/2019 21:33:45 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
50  31/08/2019 21:33:45 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
51  31/08/2019 21:33:47 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
52  31/08/2019 21:33:47 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
53  31/08/2019 21:33:48 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
54  31/08/2019 21:33:48 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
55  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      DOWN                   6e 00 00 00                                                 n...                  4                       COM12
56  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      UP    STATUS_SUCCESS                                                                                COM12
57  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
58  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   4b 00 00 00                                                 K...                  4                       COM12
59  31/08/2019 21:34:01 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
60  31/08/2019 21:34:01 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   4b 00 00 00                                                 K...                  4                       COM12
61  31/08/2019 21:34:04 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
62  31/08/2019 21:34:04 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
63  31/08/2019 21:34:09 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
64  31/08/2019 21:34:09 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
65  31/08/2019 21:34:11 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
66  31/08/2019 21:34:11 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
67  31/08/2019 21:34:15 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
68  31/08/2019 21:34:15 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
69  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      DOWN                   00 00 00 00                                                 ....                  4                       COM12
70  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK)       UP    STATUS_SUCCESS   00 00 00 00                                                 ....                  4                       COM12
71  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      UP    STATUS_SUCCESS                                                                                COM12

Dump file 1
New Dump file

I tried to do this...... check after the read response..... but no response

Its tooo long that i couldnt upload here

i added some dump data

the dump file contains more text i couldnt post it here... how can i post the text file?

yes this is the communication between the device and the software..... its a long file but i posted a part of it..... i never worked like this devices.... thats why i have no idea how it works.... i know basic serial communication arduino to arduino... blutooth module... displays....

https://meta.stackexchange.com/questions/47689/how-can-i-attach-a-file-to-a-post .... use TAB delimited data if you have an option when exporting the data dump

Sir i attached two file..... two from two different serial sniffer software

This depends on what data you need. The device seem to output a lot of information. You need to parse the string for the needed data. For example I found a line in the second dump file like <SOH>Glucose [len=8] followed by lines with glucose reading

yes.... iIn first file there is a tab called function... i can see that..... it uses some function to control it loke "IOCTL_SERIAL_GET_HANDFLOW" and many more.... this is probably programing the serial device......

download Processing and use it to diagnose the communication protocol ( https://processing.org/download/ ) ... see the example serial port sketches ... the new data.txt file that you attached has promising information ... edit the file so that the timestamp is in left column ... <20190901033932.479 SYS>   COM is open
<20190901033932.530 SYS>   Baud rate 1200 .... that will make it easier to follow

looks like you have to initiate the data exchange at 1200 baud and then switch to 9600 baud .... open port at 1200 baud, send U (0x55), close port ... open port at 1200 baud, send <ENQ> (0x05), close port .... open port at 9600 baud, send <ENQ> (0x05), data should start to be sent ..... if that works then try sending U<ENQ> together


text:
WebSocketsServer.h: No such file or directory
I'm trying use the NodeMCU WebSocket.
I downloaded the required libraries from:
https://github.com/Links2004/arduinoWebSockets
and pasted them in my Arduino libraries folder. I uploaded my code but got this error:
WebSocketsServer.h: No such file or directory.
Can you please tell me why my Arduino IDE won't find the WebSocketsServer.h header file when it is physically present in my Arduino libraries folder?   Or if there's an alternative way to use the NodeMCU WebSocket?
Here's the code:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <Hash.h>

// Replace with your network credentials
const char* ssid = "<WiFi-SSID>";
const char* password = "WiFi-PASSWORD";

WebSocketsServer webSocket = WebSocketsServer(81);
ESP8266WebServer server(80);   //instantiate server at port 80 (http port)

String page = "";
int LEDPin = D5;

void setup(void){
 //the HTML of the web page
 page = "
Simple NodeMCU Web Server

<button>ON</button> <button>OFF</button>
";
 //make the LED pin output and initially turned off
 pinMode(LEDPin, OUTPUT);
 digitalWrite(LEDPin, LOW);

 delay(1000);

 Serial.begin(115200);
 WiFi.begin(ssid, password); //begin WiFi connection
 Serial.println("");

 // Wait for connection
 while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
 }

 Serial.println("");
 Serial.print("Connected to ");
 Serial.println(ssid);
 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.on("/", [](){
    server.send(200, "text/html", page);
 });

 server.on("/LEDOn", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, HIGH);
    delay(1000);
 });

 server.on("/LEDOff", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, LOW);
    delay(1000);
 });

 server.begin();
 webSocket.begin();
 webSocket.onEvent(webSocketEvent);

 Serial.println("Web server started!");
}

void loop(void){
  webSocket.loop();
  server.handleClient();
  if (Serial.available() > 0){
    char c[] = {(char)Serial.read()};
    webSocket.broadcastTXT(c, sizeof(c));
  }
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length){
  if (type == WStype_TEXT){
   for(int i = 0; i < length; i++) Serial.print((char) payload[i]);
   Serial.println();
  }
}
~~~

What is the exact structure, where you have the file in your libraries folder? Directly in there, or in a subfolder? What name for the subfolder?

I try to change that with #include "WebSocketsServer.h" and WebSocketsServer.h is on actual dir.

the library has formal issues to be detected by Arduino IDE. in library.properties the headers key is missing

after you included the zip file to library you must rename directory like this 'WebSocketsServer'. And then you copy all file in 'src' directory and then paste them to its parent directory (WebSocketsServer)

didn't work with me .. do you mean like this: ..\OneDrive\Documents\Arduino\libraries\WebSocketServer\src ?

The proper way is to add library into your Arduino IDE, it will just work.

Open the Arduino IDE
Go to Sketch > Include Library > Manage Libraries
Search for "WebSockets Sattler' and install the library named "WebSockets by Markus Sattler"
Restart the Arduino IDE.

PS

you will see two results for WebSockets library from the same author
the second "WebSockets_Generic" is a more lightweight library and it only provides support for WebSockets in the client mode (it is designed to be more memory efficient)

proper way would be to add WebSocketsServer.h to list of locations that gcc looks for. see: https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC6
another way would be to download WebSocketsServer.zip from  https://www.arduinolibraries.info/libraries/web-sockets
to your workdir and unzip it
replace
#include <WebSocketsServer.h>

with explicit location
#include "./WebSockets-2.3.5/src/WebSocketsServer.h"

(note unziped version in this case is WebSockets-2.3.5)

relative paths don't work with Arduino builder. the build is executed in a temporary folder where the path is not valid. with Arduino we don't setup gcc.


text:
How can I measure if a battery is there?
With my arduino I want to measure if one / two AAA batteries are in their single / double battery holder.
When the Arduino is running, connected to some other power supply and the batteries are in place everything is fine: I get my measurements of around 1.5V / 3V on the analog pin the battery is connected to (- of battery and Arduino GND are connected as well of course).
Problems arise when I either
a) pull the batteries out: The analog pin is left floating. Not good. Can I put the pin into INPUT_PULLUP mode? Is the internal resistor big enough? Or will the then connected 5V damage my batteries when they are back in the battery holder?
b) dissconect the Arduino from its external power supply: Because the Arduino is then "powered" by the 3V through the analog pin my blinking LED keeps blinking (at less brightness, but still...). I neither want the batteries to get drained nor damage my Arduino with it. So I would like to avoid this.
Actually I don't care about the actual battery voltage - I just want to know if the batteries are in their holder or not. And I want to leave the batteries there even though the Arduino is not powered. I would even consider something like "a button is held down when a battery is in its holder" or any other (simple) creative ideas.
Is this possible? How?

do you want to use batteries as a [backup] power source or not ? if not (and you didn't connect the + of batteries to arduino supply line), why the arduino is powered by them when you disconnect the main power source in section b of your question?

@Tirdad Sadri Nejad That is a parasitic current through the input pin. Not good for the microcontroller.

I see 1 main problem: Keeping the batteries isolated, so that no current flows between them and the Arduino (especially no parasitic current into the input pin of a turned off Arduino), while still reading a voltage level (HIGH or LOW).
I would suggest using a fitting N-Channel MOSFET. Connect the minus pin of the batteries to ground and the plus pin to the gate of the MOSFET. Then source and drain of MOSFET to ground and a digital arduino pin respectively. Enable the internal pullup resistor. Add a pulldown resistor between gate and ground.
Now, without the batteries, the gate is at ground level, so the MOSFET is not conducting. The level at the input pin will be high. If the batteries are in, their voltage will activate the MOSFET, which pulls the Arduinos input pin to ground, thus LOW level. Since the MOSFET is somewhat like a capacitor between gate and the rest, almost no current will flow here (only enough to load the small capacitance). Though I'm not sure, I think that no current will flow either in the case of the Arduino being unpowered.
The task now would be to find a fitting MOSFET, which goes in saturation for 1.5V.
Of course you can also use a microswitch, that gets pushed down by the batteries. That is electronically easier, but maybe mechanically challenging.

Sounds reasonable, thanks! I tried to draw a schematic off your instructions: https://i.ibb.co/pW7n4D6/sch.png Is that what you thought of?
Now I go find a MOSFET and try it :-)

Almost. I intended to connect to a digital pin instead of an analog one, since you only need information, if there are batteries or not. Doing this electrically also means, that empty batteries are like no batteries.

I built this circuit with a "ZVN3310A", a 560k Pulldown and internal pullup. Seems to work :-)
For the one-battery-version I had to measure the analog value though, because the transistor I got has a VGS(th) of 0.8 to 2.4V and the 1.5V of a single battery were just not enough to make the transistor fully conductive (I had no other transistor available). But it conducted enough to get the analog value from about 1000 (no battery) to about 700 (1.5V battery).
All LEDs stay off even with a 3V battery when no power is connected, so I guess there is no (significant) parasitic current.

Yes, I assumed a transistor, that would be already fully conductive for 1.5V, but if you don't have a better transistor, using analog input is also fine.

You could add a pulldown to the analog pin. If the ADC reads a value below e.f. 10, you could consider this the state when there are no batteries.
From the signal perspective a pullup would be better, because without batteries you would read 5V which is unambigous as it can not be provided by the batteries themselves. But in general I don't think that applying higher voltage to the batteries is good practice, even though you could limit the current with a reasonably high resistor.


text:
Error while reburning bootloader to atmega328p by usbasp in Arduino IDE
I have got the Bootloaded ATMega328P-PU from China and I want to reburn new bootloader into it. For this I use UsbAsp programmer. I want to do it in Arduino IDE. But when I try to flash, for example, an empty flash it says that error:
 Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 0
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

But when I work in Avrdudeprog, it works without any problems.
How can I fix it?

what's the circuit ? the error is mainly about a bad connection to the chip.

Nop. When I work whith programs as Khazarma, AVRDUDESS andAvrdudeprog v3.3 it works without broblems

use Zadig 2.4 to change the driver for USBasp. USBasp works with 3 drivers but it seems the type of installed driver causes some problems in various software. khazama, progisp on one hand and Arduino on the other hand. despite all of them using avrdude.
libusb-win32 : khazama works, Arduino does not
WinUSB       : khazama doesn't work, Arduino works
libusbK      : both work

I must select libusbK. OK. I test

Can I ask one question? This chip is fron china and it worked very slow and in internal clock 8 MHZ. I watched video and here said that I must set fuse bits as:

L: 0xFF H: 0xDE E: 0x05 Lock:0x3F as in bootloader. But my chip broke. WHY? I don't know! How can I fix it without fuse doctor?

@E.M. the arduino has to operate from 16MHz. and when you use the 328 for the first time, it has a clock of internal 8MHz divided by 8 = 1MHz.
the fuses seem right except for Efuse. the value 0x05 means 256 words for bootloader which is not sufficient. use 0xFD for 2K words

@E.M.http://www.engbedded.com/fusecalc

But Bro this chip wont to work

Chip won't working. How can I write fuses here?