text:
to measure the time between the ON signal and OFF signal
int pin_state = LOW;
struct Channel {
    byte pin;
    byte state;
    byte count;
    unsigned long fell, rose;
};

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

void setup()
{
    for (int i = 2; i <= CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    //Serial.println("pin,fell,rose,low time");
    Serial.println("Minutes, Seconds, Count");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i)
    {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == LOW && new_state == HIGH)
        {
            c.rose = millis();
            c.count = c.count + 1;
        }
        else if (c.state == HIGH && new_state == LOW)
        {
            c.fell = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

void display_channel(const Channel &c)
{
  int minutes, seconds;
  unsigned long difference;
  difference = c.fell - c.rose;
  seconds = int(difference/1000);
  if (seconds >= 60)
  {
       minutes = seconds / 60;
       seconds = seconds % 60;
  }
    //Serial.print(difference/1000);
    //Serial.print(",");
    Serial.print(minutes);
    Serial.print(",");
    Serial.print(seconds/1000);
    Serial.print(",");
    Serial.println(c.count-1);
    //Serial.print(",");
  }

When I try to run the program, I don't get any output.
Is there anything wrong with the code, that must be solved before any output can get displayed?

Hint: Might want to check how you handle channel vector index, pin initialization, etc. There are many trivial mistakes in the sketch.

Could you provide a better solution code for the mistakes as i cant find any.

Check the answer provided below by Majenko. He understood the hints :).

Here's the catalog of errors I see at first glance:
const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

You set up space for 3 entries but only fill 2.  Also, the Channel structure has 5 entries, not 4. You don't initialize the 5th (rose) entry (although it will be initialized to 0 for you - best to be explicit though).

for (int i = 2; i <= CHANNEL_COUNT; ++i) {
    pinMode(channels[i].pin, INPUT);
}

You start from entry number 2 (the third entry) and iterate to the 4th (non-existent) entry to set the pin mode of either undefined or invalid pins.

for (int i = 0; i < CHANNEL_COUNT; ++i)

You have only filled in 2 of the three entries. Yet you use the third as if it were filled in.

Serial.print(minutes);

If seconds is less than 60 then minutes is undefined here.

I would suggest changing your code so that Channel is a class and embed the code to manage that class within it.

Bonus Time

Here's your program re-written using a class. As an added bonus I have added automatic allocation of a channel number to each object as it's created.  To add more channels just add the pin number into the initialization list.
class Channel {
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display() {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0) {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process() {
            int s = digitalRead(_pin);
            if (s != _state) {
                _state = s;
                if (s == LOW) { // Fell
                    _fall = millis();
                    _count++;
                    display();
                } else {
                    _rise = millis();
                }
            }
        }
        void begin() {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 2, 3 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

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

    Serial.println("Channel,Minutes,Seconds,Count");

    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].begin();
    }
}

void loop() {
    for (unsigned int i = 0; i < NUM_CHANNELS; i++) {
        channels[i].process();
    }
}

Is class in arduino same as it is in python, as im just starting with arduino. Modified code would be helpful in that case :)

The concept of a class is the same, yes (it's a standard Object Oriented Programming term), but the way of working with them and the syntax is different. You should check some of the many many libraries around - they almost all use classes.

@RajeshAnand10 I have rewritten your program using a class.  There's no comments. It's up to you to pull it apart and work out what it's doing and how it's doing it.

But this doesn't seem like two pins can process the same "void process()" when two inputs come in simultaneously right?

Each pin has its own void process(), and there is no such thing as simultaneously.

Here the count keeps incrementing when the pin is low, but I need the count only when the pin gets low. I mean the count is effectively the number of times when the pin gets low and not how long the pin is low. How do I change to that condition accordingly as I can't even use break command since it's not in the loop structure?


text:
Management issues through Blynk
I wrote a sketch for controlling the stepper motor under the controls of the Blynk application, the sketch was compiled but there was a problem in that no control was taking place. Receipts and controls occur on virtual pins V1, V2, V3. (The problem is that nothing is controlled), please help solve the problem.

//#include <Stepper.h>
//#define BLYNK_WRITE
//#include <ESP8266WiFi.h>
//#include <BlynkSimpleEsp8266.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 1, 2, 3, 4);

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "[private]";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "S30mini";
char pass[] = "12345678";

int pinData;
int pinData1;
int pinData2;
BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  int pinData = param.asInt();
 }
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  int pinData1 = param.asInt();
 }
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  int pinData2 = param.asInt();
 }

void setup()
{
  // Debug console
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
}

void loop()
{
    Blynk.run();

  // map it to a range from 0 to 100:
  int motorSpeed = map(pinData, 0, 1023, 0, 100);
  // set the motor speed:
  if (motorSpeed > 0) {
    myStepper.setSpeed(motorSpeed);
    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 100);
  }

   if (pinData1 == 1){
      myStepper.step(stepsPerRevolution);
   }

   if (pinData2 == 1){
     myStepper.step(-stepsPerRevolution);
    }

}

By prefixing your pinData variables with int, you are declaring local variables in your BLYNK_WRITE() functions, whose scope is only in that function. The local version is written to, instead of the global.
To fix this, do not declare a new variable in BLYNK_WRITE():
BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  pinData = param.asInt();
}
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  pinData1 = param.asInt();
}
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  pinData2 = param.asInt();
}

source: Stack Exchange

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

sort: votes


text:
Help to delimit and read specific contents of incoming HTTP string
I am sending strings to an Esp8266 via web browser.
The below code returns the following in serial monitor if I send in browser:
Send from browser to esp8266 - http://192.168.1.220/s1s2s3s4s5d1
Receive in Arduino Serial monitor - GET /s1s2s3s4s5d2 HTTP/1.1
How do i read only the contents s1s2s3s4s5d1  ? This content can vary in length, numbers could be double digits but alphabets will remain in between.
Please note I am still a novice.

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

google arduino parsing strings

Thanks, i have tried to implement some methods unsuccessfully. i simply do not have the experience especially since the content required varies in length. i was hoping to get an example if possible.

do you have any control over the URL format ....maybe you need to use something like http://192.168.1.220?s=1&s2=4&s3=8&d=1&abcd=1234

will this method retain the letters or does it strip to numbers?

I have this
if (client.connected()) {
  if (client.available() && client.find(' ')) { // GET /fn HTTP/1.1
    char fn[20];
    int l = client.readBytesUntil(' ', fn, sizeof(fn));
    fn[l] = 0;
    while (client.read() != -1);
    Serial.println(fn);
    client.stop();
  }
}

Thank you, will apply solution and revert.

@s-b, did it help?

you can try something like this
int first_space = request.indexOf(' '); // location of the first space
int second_space = request.indexOf(' ', first_space); // the next space after first

String query_arg = request.substring(first_space,second_space);

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


text:
ESP8266 SoftwareSerial not receiving any character
I want to use a ESP8266 (ESP12) to receive data from a counter at 9600 baud via SotwareSerial. But my program does not receive any data. I broke it down to the code i attach here. I tried it using different libraries (Arduino SoftwareSerial and also espsoftwareserial) i found. I connected and tested RX and TX in different combinations of the available pins 4/5/12/13/14. But no combination is receiving data at all. I only can send data - checked by oscilloscope. Running my test program attached i connected the RX and TX pin together so i should loop back the data from tx.
I hopefully find somebody in the community who can give me a helpful hint. Thank you in advance!
#include <SoftwareSerial.h>
SoftwareSerial mySerial1(14, 12, false, 256);  // RX, TX

void setup() {
mySerial1.begin(9600);   //  Kommunikation mit Zähler
mySerial1.setTimeout(5000);
mySerial1.listen();
//delay(100);
//mySerial1.listen();

Serial.begin(9600);
delay(1000);
Serial.print(__DATE__);Serial.print(" ");Serial.println(__TIME__);

char ch;
while(1){
  wdt_reset();
  Serial.println("\nSoftware serial test started");
  Serial.print("Data sent: ");
  for (byte i = 32; i < 128; i++) { mySerial1.write(i);
  Serial.print(char(i)); }
  Serial.println();
  mySerial1.println();
  ESP.wdtFeed();
  delay(100);
  Serial.print("Data recv: ");
  if(mySerial1.available()) {
    while(mySerial1.available()){
      ch = mySerial1.read();
      Serial.print(ch);
    }
    Serial.println("_");
  }
  delay(400);
}
}

void loop() {}

Dear @fhpa, before answering, I suggest you to remove while(1) from setup() function and move content of while(1) inside loop() function. Loop() function, as suggested by its name, loops consecutively. https://www.arduino.cc/en/Reference/Loop?setlang=en

Please, be more precise, provide the schematic. Are you sure that connection are correct?

Thank you commenting. Yes, the connections have been correct. In the meantime my question was answered and the problem is solved: SoftwareSerial cannot send and receive at the same time.

If the ESP8266's software serial is anything like the Arduino's software serial, it cannot receive data while it's transmitting. It's strictly half-duplex.
To test your system you will need to test the transmission and reception completely separately, and that means having some external device sending data for you to attempt to receive.

Thank you Majenko for your answer solving the problem. You are right saying the SoftwareSerial is working strictly half duplex. I tested it with a second esp only sending data and receiving with the second ESP. BTW i only need to receive data. I think you saved me a lot of my time!


text:
Nan values in Egg Incubator
I've recently built my Arduino Incubator, which consists of a DHT22 sensor, an LCD Keypad Shield, some fans, resistors, e.t.c.
I uploaded the sketch, and everything seemed fine. However, when I try to select the temperature and humidity I want, it won't let me change anything, and it says "Temperature: NanC, Humidity: Nan%".
What am I doing wrong? I didn't write the code myself. I copied it from a guy who made his incubator and wrote his code himself. He has the incubator project on github.
As you can see in the pictures he posted, everything appears to be working fine. What would be the problem? I don't have a lot of Arduino knowledge, although I am OK with reading and tinkering with code.
The display below, shows NaN when I try to select my own temperature/humidity. When I see the current temperature/humidity, it works fine. The sensor works with no problems at all, though I didn't connect a pullup resistor. I am going to try adding one. However, to me it seems like the problem isn't that. I get NaN errors when trying to select my own value. The buzzer beeps, the servo turns and the fan works fine. As said above, DHT sensor works and sends the values.

Useful Links:
The code (Github)
The schematic (Github)
The whole incubator project (Github)
Update - 7/1/2019
Thanks to Jot, everything works fine now! He corrected my code, and he adviced me to reset the values in the EEPROM. I would have given up the project, unless he had helped me. I have now fully finished the build, even though I plan to add some features in the future.
I want to add:

A backup power source (lead acid battery)
Bigger ventilation holes
Design improvements
The ability to control everything using the serial monitor, so I can connect to the Arduino via Internet (Using an MFP Storage Server which I have)
A larger box for more eggs
A system which turns the eggs automatically
A pump which pumps water to the sponge automatically as well

However, nothing could be done without Jot's help. Again, thanks a lot to Jot for his help, and the efforts he put in order to help me. I really appreciate that, since I have not any kind of Arduino knowledge (I'm 14 years old), and I found his advices and comments very very useful.
I have now put 5 eggs inside the incubator, and it is right now working. I am counting backwards from today, and in about 21 days I am going to have chickens!
Here are some pictures of the machine for those who are interested (or just curious!):
The incubator working, with the screen turned on:

The "egg hatching" room:
(Inside, there is a wet sponge, all the devices and of course, 5 eggs!)

i think that nan means not a number ..... comment out this line H = dht.readHumidity();  and add H = 0.5; ..... what do you get on the display then?

Please, Post all the code that you are using to.

The code, is given in the link above. However, here is the link: https://github.com/quantenschaum/egg-incubator/blob/master/incubator.ino. I only made a few changes at the beginning, so the lcd screen shows both date and time. Actually, I dodn't think this affects the error, as it has nothing to do with that. In addition to the above, I imported the code to the Arduino (before changing anything), and it seemed like the problem existed.

@jsotola thanks for the reply! However, it seems like the H = dht.readHumidity(); is already included. Take a look at that:     if (!key) {
//    beep(2000, 50);
T = dht.readTemperature() + T_OFFSET;
H = dht.readHumidity();
  if ((isnan(T) || T < 10 || T > 60) || (Hcontrol && (isnan(H) || H < 5 || H > 95))) {
    heater(0);
    lcd.clear();
    lcd.print("SENSOR ERROR!"); It seems like it includes those, and also sets off an alarm if a nan value is displayed. When I add H = 0.5;, it beeps and reboots as the code says. My problem is when I select t/h.

@jsotola Also, the screen says "SENSOR ERROR", and that is something that the code says. As you can see in the previous code, if a nan value is displayed, then it sets off the alarm. For more information you can also see the whole code at the link included. Something to mention, is that I only have trouble selecting values e.g. temperature or humidity. I see the current temperature and humidity displayed with not problems. However, when I go to the selection menu, all the setpoints are NaN values.

Did you lay these eggs yourself?

Hi Lefteris the builder,
StackExchange is about questions and answers.
Arduino is about learning and fast prototyping.
For guidance with your project, the forum at http://forum.arduino.cc/ is more appropriate.
I suppose that a number of us have read the code that you use. We really do read code.
That code is not bad, but there are a few weak spots in that code:

Not enough comments to explain what is going on.
Many conditions with flags. That is okay,
but the flags are sometimes a boolean and
sometimes a byte, and there is no explanation what the flag is
used for.
Many checks for isnan(). Does that indicate that
a floating point "nan" problem might pop up
at any time in the sketch?
Most of the code is in the loop(). I don't mind that, but
others prefer to put large blocks of code in functions.

It seems that your hardware is working okay.
It is hard to confirm that the code for the Holt-Winters algoritme is working.
All this together is too confusing for us at the moment.

I have changed my answer, the hardware seems to be working.

Below is the changed sketch to test it without extra hardware.
I use the serial monitor. The sadw keys (followed by enter) are the cursor keys and the space bar (followed by enter) is select.
#include <avr/wdt.h>
// #include <Servo.h>
// #include <LiquidCrystal.h>
// #include <DHT.h>
#include <EEPROM.h>

// stty -F /dev/ttyACM0 115200 cs8 cread clocal -hupcl time 30 && tee incubator.log </dev/ttyACM0

#define WDT_TIMEOUT WDTO_8S // if defined, enable hardware watchdog
#define DHTPIN 3 // data pin of the DHT T/H sensor
#define T_OFFSET 0.9 // temperature sensor offset
#define FAN_PIN 2 // fan tacho signal pin
#define FAN_THRES 500 // fan alarm threshold
#define BEEPER A2 // pin where beeper is attached
#define BRIGHTNESS 10 // display brightness pin
#define HEATER A1 // heater MOSFET pin
#define DELAY 2000 // loop delay in ms
#define TS_ADDR 0 // temperature set point EEPROM address
#define HS_ADDR 4 // humidity set point EEPROM address
#define HC_ADDR 8 // humiditiy control mode EEPROM address
#define TI_RESET 1 // integral reset threshold, set integral to 0 when T error greater than this
#define HI_RESET 5 // integral reset threshold, set integral to 0 when H error greater than this
#define ALARM_T 2 // temperature alarm threshold, alert if T error greater than this
#define ALARM_H 8 // humidity alarm threshold, alert if H error greater than this
#define H_AUTO_THRES 3 // disable vent control in auto mode if H error < this
#define H_AUTO_COUNT 200 // disable for n cycles
#define HWAT 0.25 // holt winters parameters for temperature smoothing
#define HWBT 0.2
#define HWAH 0.7 // holt winters parameters for humidity smoothing
#define HWBH 0.5
#define A 0.005 // long average parameter
#define VENTCLOSED 80 // consider vent closed if under this angle
#define VENTOPENMS  480000L // open vent if closed longer
#define VENTRESETMS 600000L // reset vent after this time (>VENTOPENMS!)

// Servo vent;
// DHT dht(DHTPIN, DHT22);
// LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define RIGHT 16
#define UP 8
#define DOWN 4
#define LEFT 2
#define SELECT 1
#define NO_KEY 0

// added define to show messages on serial monitor.
#define lcd Serial

byte getKey() {
//  int key = analogRead(0);
//  if (key < 50) {
//    return RIGHT;
//  } else if (key < 150) {
//    return UP;
//  } else if (key < 300) {
//    return DOWN;
//  } else if (key < 500) {
//    return LEFT;
//  } else if (key < 800) {
//    return SELECT;
//  } else {
//    return NO_KEY;
//  }
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    switch (inChar)
    {
      case 'w': return UP;
      case 'a': return LEFT;
      case 's': return DOWN;
      case 'd': return RIGHT;
      case ' ': return SELECT;
    }
  } else {
    return NO_KEY;
  }
}

void eeread(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    *b++ = EEPROM.read(address + i);
  }
}

void eewrite(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    EEPROM.write(address + i, *b++);
  }
}

void write_byte(int address, byte &value) {
  eewrite(address, sizeof(value), &value);
}

byte read_byte(int address) {
  byte value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_int(int address, int &value) {
  eewrite(address, sizeof(value), &value);
}

int read_int(int address) {
  int value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_float(int address, float &value) {
  eewrite(address, sizeof(value), &value);
}

float read_float(int address) {
  float value;
  eeread(address, sizeof(value), &value);
  return value;
}

void heater(boolean on) {
//  digitalWrite(HEATER, !on ? LOW : HIGH);
}

boolean heater() {
//  return digitalRead(HEATER) == HIGH;
  return true;
}

volatile int fancount;

void count() {
  ++fancount;
}

void beep(unsigned long f, unsigned long l) {
//  pinMode(BEEPER, OUTPUT);
  byte v = 0;
  f = 500000 / f;
  l = (1000 * l) / f;
  for (int i = 0; i < l; ++i) {
//    digitalWrite(BEEPER, v = !v);
//    delayMicroseconds(f);
  }
//  pinMode(BEEPER, INPUT);
}

float Ts, Hs; // set points
byte Hcontrol; // H control mode
byte Ts_changed, Hs_changed; // setpoint changed flags
float ET, dETdt, IETdt; // prop/diff/integ terms for T
float EH, dEHdt, IEHdt; // prop/diff/integ terms for H
float T, Tavg = NAN, Tvar, Tstd;
float H, Havg = NAN, Hvar, Hstd;
float Hpower, Hduty; // heater current power, average duty cycle
unsigned long t0, Hon, talarm, tventclosed;
byte displayMode;
byte key, bri = 255, alarm;
boolean ventclosed;
int fanrpm;

void setup() {
#if defined(WDT_TIMEOUT)
//  wdt_enable(WDT_TIMEOUT);
#endif
  Serial.begin(9600);
  Serial.println("Egg Incubator");
  Serial.println("Use wsad and space is select");

//  pinMode(HEATER, OUTPUT);
//  heater(0);
//  pinMode(BRIGHTNESS, OUTPUT);
//  analogWrite(BRIGHTNESS, bri = 255);
//  lcd.begin(16, 2);
//  lcd.noCursor();
  lcd.print("Incubator 0.7");
//  lcd.setCursor(0, 1);
  Serial.println();
  lcd.print(__DATE__);
//  dht.begin();
//  vent.setMinimumPulse(800);
//  vent.setMaximumPulse(2600);
//  vent.attach(11);
  //  write_float(TS_ADDR, Ts=37.8);  write_float(HS_ADDR, Hs=55);
  Ts = read_float(TS_ADDR);
  Hs = read_float(HS_ADDR);
  Hcontrol = read_byte(HC_ADDR);
//  pinMode(FAN_PIN, INPUT_PULLUP);
//  attachInterrupt(0, count, FALLING);
//  sei();
//  beep(800, 100);
//  beep(1000, 100);
//  beep(1200, 100);
//  beep(1600, 100);
}

void loop() {
  unsigned long t1 = millis();
  int dt = t1 - t0;

  if (!key) {
    key = getKey();
  }

  if (key) {
//    analogWrite(BRIGHTNESS, bri = 255);
  }

  if (t1 - Hon > Hpower * DELAY) {
//    heater(0);
  }

  if (Hcontrol && Hcontrol < H_AUTO_COUNT) {
//    vent.refresh();
  }

  if (alarm && !(alarm & 8)) {
//    beep(1000, 50);
//    beep(1414, 50);
  }

  if (dt > DELAY || key) {

    if (!key) {
      //    beep(2000, 50);
//      T = dht.readTemperature() + T_OFFSET;
      T = 30.0 + T_OFFSET;             // set to fixed value !
//      H = dht.readHumidity();
      H = 60.0;                        // set to fixed value !

      if ((isnan(T) || T < 10 || T > 60) || (Hcontrol && (isnan(H) || H < 5 || H > 95))) {
//        heater(0);
//        lcd.clear();
        lcd.print("SENSOR ERROR!");
//        lcd.setCursor(0, 1);
        Serial.println();
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        beep(2000, 1000);
        return;
      }

      float dts = dt * 1e-3;

      if (dt > DELAY) {
        fanrpm = fancount * 60 / dts;
        fancount = 0;
      }

      if (fanrpm < FAN_THRES) {
        alarm |= 4;
      } else {
        alarm &= ~4;
      }

      // temperature Holt-Winters smoothing
      float E0 = ET;
      ET = HWAT * (T - Ts) + (1 - HWAT) * (ET + dETdt * dts); // smoothed T error (deviation from set point)
      dETdt = HWBT * (ET - E0) / dts + (1 - HWBT) * dETdt; // smoothed derivative
      IETdt += ET * dts; // integral of error
      if (abs(ET) > TI_RESET) // reset integral on big deviation
        IETdt = 0;
      float pidT = 1.1765 * (ET + 0.010526 * IETdt + 23.75 * dETdt); // PID value, adjust coefficients to tune
      Hpower = fanrpm > FAN_THRES ? max(0, min(1, -pidT)) : 0;
      heater(Hpower > 0.1);
      Hon = millis();

      if (abs(ET) > ALARM_T) {
        alarm |= 1;
//        vent.write(ET < 0 ? 0 : 180);
        if (Hcontrol > 1) {
          Hcontrol = 2;
        }
      } else {
        alarm &= ~1;
      }

      // humidity Holt-Winters smoothing
      E0 = EH;
      EH = HWAH * (H - Hs) + (1 - HWAH) * (EH + dEHdt * dts); // smoothed H error (deviation from set point)
      dEHdt = HWBH * (EH - E0) / dts + (1 - HWBH) * dEHdt; // smoothed derivative
      IEHdt += EH * dts; // integral of error
      if (abs(EH) > HI_RESET) // reset integral on big deviation
        IEHdt = 0;
      float pidH = 0.1176 * (EH + 0.09091 * IEHdt + 2.75 * dEHdt); // PID value, adjust coefficients to tune
//      vent.write(pidH * 180);

      if (Hcontrol && abs(EH) > ALARM_H) {
        alarm |= 2;
      } else {
        alarm &= ~2;
      }

      boolean ventclosed0 = ventclosed;
//      ventclosed = vent.read() < VENTCLOSED;
      ventclosed = VENTCLOSED;

      if (ventclosed && ventclosed != ventclosed0) {
        tventclosed = millis();
      }

      boolean openvent = ventclosed && millis() - tventclosed > VENTOPENMS;
      if (openvent) {
//        vent.write(180);
        if (millis() - tventclosed > VENTRESETMS) {
          tventclosed = millis();
        }
      }

      if (Hcontrol > 1) {
        if (abs(EH) > H_AUTO_THRES || openvent) {
          Hcontrol = 2;
        } else {
          if (Hcontrol < H_AUTO_COUNT) {
            ++Hcontrol;
          } else {
            IEHdt = 0;
          }
        }
      }

      // long term averages
      Tavg = A * T + (1 - A) * (isnan(Tavg) ? T : Tavg);
      Tvar = A * pow(T - Tavg, 2) + (1 - A) * (isnan(Tvar) ? 0 : Tvar);
      Tstd = sqrt(Tvar);

      Havg = A * H + (1 - A) * (isnan(Havg) ? H : Havg);
      Hvar = A * pow(H - Havg, 2) + (1 - A) * (isnan(Hvar) ? 0 : Hvar);
      Hstd = sqrt(Hvar);

      Hduty = A * Hpower + (1 - A) * Hduty;

      if (Ts_changed) {
        if (Ts_changed-- == 1)
          write_float(TS_ADDR, Ts);
      }

      if (Hs_changed) {
        if (Hs_changed-- == 1)
          write_float(HS_ADDR, Hs);
      }
    }

    if (key & SELECT) {
      displayMode = ++displayMode % 8;
    }

//    lcd.clear();
    Serial.println();
    lcd.print("T=");
    lcd.print(Ts + ET);
    lcd.print("C H=");
    lcd.print(Hs + EH, 1);
    lcd.print("%");

//    lcd.setCursor(0, 1);
    Serial.println();

    float uptime;
    char unit;
    switch (displayMode) {
      case 0: // raw values
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        break;
      case 1: // temperature setpoint
        if (key & (UP | DOWN | LEFT | RIGHT)) {
          Ts = max(20, min(50, Ts + (key & (UP | RIGHT) ? +1 : -1) * (key & (UP | DOWN) ? 0.1 : 1)));
          Ts_changed = 10;
        }
        lcd.print("Ts=");
        lcd.print(Ts);
        lcd.print("C");
        break;
      case 2: // humidity setpoint
        if (key & (UP | DOWN)) {
          Hs = max(10, min(90, Hs + (key & UP ? +1 : -1)));
          Hs_changed = 10;
        }
        if (key & RIGHT) {
          if (Hcontrol < 2) {
            Hcontrol = ++Hcontrol;
          } else {
            Hcontrol = 0;
          }
          IEHdt = 0;
          write_byte(HC_ADDR, Hcontrol);
        }
        lcd.print("Hs=");
        lcd.print(Hs);
        lcd.print("% ");
        lcd.print(Hcontrol == 1 ? "on" : (Hcontrol > 1 ? "auto" : "off"));
        break;
      case 3: // average temperatur
        lcd.print("Ta=");
        lcd.print(Tavg);
        lcd.print("C (");
        lcd.print(Tstd);
        lcd.print(")");
        break;
      case 4: // average humidity
        lcd.print("Ha=");
        lcd.print(Havg);
        lcd.print("% (");
        lcd.print(Hstd);
        lcd.print(")");
        break;
      case 5: // heater duty cycle
        lcd.print("Hd=");
        lcd.print(Hduty);
        lcd.print(" Hp=");
        lcd.print(Hpower);
        break;
      case 6: // air vent
        lcd.print("V=");
//        lcd.print(vent.read() / 180.0);
        lcd.print(" F=");
        lcd.print(fanrpm);
        break;
      case 7: // average humidity
        uptime = t1 * 1e-3;
        unit = 's';
        if (uptime > 60) {
          uptime /= 60;
          unit = 'm';
          if (uptime > 60) {
            uptime /= 60;
            unit = 'h';
            if (uptime > 24) {
              uptime /= 24;
              unit = 'd';
            }
          }
        }
        lcd.print("Up=");
        lcd.print(uptime, 1);
        lcd.print(unit);
        break;
      default:;
    }

    Serial.println();

    if (alarm & 7) {
      if (!talarm) {
        talarm = millis();
      }
      // sound on persistent alarm and fan failure
      if (millis() - talarm > 300000L || alarm & 4) {
        alarm &= ~8;
      }
//      analogWrite(BRIGHTNESS, bri = 255);
//      lcd.setCursor(0, 0);
      if (alarm & 1)
        lcd.print("T ");
      if (alarm & 2)
        lcd.print("H ");
      if (alarm & 4)
        lcd.print("F ");
      lcd.print("ALARM!          ");
      if (!(alarm & 8) && key) {
        alarm |= 8; // alarm acknowledged
        talarm = millis();
      }
      if (!(alarm & 8)) {
//        lcd.setCursor(0, 1);
        Serial.println();

        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
      }
    } else {
      alarm = 0;
      talarm = 0;
    }

    if (key) {
      delay((key & SELECT) ? 500 : 200);
    }

    if (bri) {
//      analogWrite(BRIGHTNESS, --bri);
    }
    key = 0;
    t0 = t1;
  }

#if defined(WDT_TIMEOUT)
  wdt_reset();
#endif
}

@Lefteristhebuilder, you have selected that sketch, but the sketch might not handle problems very well.
Anyone can write code for Arduino and put it online.
At least at Github it is possible that others can write an issue (as you did). The project at Github has 9 stars and the creator showed the project at the Arduino "Project Hub". That is all good, but I'm not very happy with the code itself.

Hi! First of all... I didn't write the code myself! I copied from a guy who did the same thing and it worked for him. The display above, shows NaN when I try to select my own temperature/humidity. When I see the current temperature/humidity, it works fine. The sensor works no problems at all, though I didn't connect a pullup resistor. I am going to try adding one. However, to me it seems like the problem isn't that. I get NaN errors when trying to select my own value. Buzzer, servo and fan work fine. Buzzer, fan and servo work fine. As said above, DHT sensor works and sends the values.

@Lefteristhebuilder please update your question with this extra information. Also add a link to your issue at github to your question. Add to question which DHT library you use. Did you really use a SoftwareServo library?

@Lefteristhebuilder I'm running a simulation of the code. I don't get the "nan" numbers when adjusting the values with up and down. The way the menu works in the sketch is hard to understand. If I had to solve this for myself, I would print a lot of variables to the serial monitor and probably end up rewriting the whole sketch.

thanks for your reply! What kind of simulation did you do? Can I do that as well? I don't know whether the code is hard to understand or not, since as mentioned above, I have not any kind of experience with coding. Unfortunately I can't write the sketch, I haven't done any similar thing before and if you asked me to create just a blink sketch, I would struggle a lot, or I would just copy something posted online. What are the available options? I spent a lot of money for this project and I don't want to throw it away.... Hope you kindly understand. I used DHT.h and SoftwareServo.h.

@Lefteristhebuilder I have added the changed sketch to my answer. There are many libraries with "DHT.h" and no one uses the SoftwareServo anymore because that became the normal Arduino Servo library.

Thank you a lot for your time and the efforts you put! I followed your steps, uploaded the code, but unfortunately I still get the same error.... I don't know what causes it to do so, and since you told me that it worked at the simulation, I think that we are not going to make it work..... sorry for wasting your time, very sorry....

Also, is there any way to make it displayed both in the serial monitor and the screen??

That is good information. I have removed all the hardware from the sketch except the EEPROM. Did you reset the values in EEPROM? Can you uncomment the line with two "write_float" in it (remove the two slashes // in front). This line: https://github.com/quantenschaum/egg-incubator/blob/master/incubator.ino#L164 Run the sketch once, and then put the two slashes // back. You can add code to send data also to the serial monitor.

@Lefteristhebuilder You gave up?

Not only I didn't gave up, but I also finished the build. Right now it is working fine, without problems and that's all thanks to you! Thanks to you, I've got rid of the NaN values, and I finished something that I was about to give up. I'm only 14 years old and I don't have any idea of programming, so your advise was very very helpful. You can also check at the very bottom of that thread, as I've put an update and mentioned the fact that you helped me. I don't even know how to thank you! That was unbelievable!

@Lefteristhebuilder Well done. I'm glad I could help.


text:
How to connect multiple I2C devices?
I am trying connecting I2C OLED SSD1306 and I2C INA219 on ESP32 but without success.
First try:
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA1 21  //OLED SSD1306
#define SCL1 22  //OLED SSD1306
#define SDA2 5  //INA219
#define SCL2 4  //INA219

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char* ssid     = "SSID";
const char* password = "PASSWORD";

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  Wire.begin(SDA1, SCL1);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

   startWiFi();

  Wire.begin(SDA2, SCL2);
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{
      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

const char* wl_status_to_string(wl_status_t status) {
  switch (status) {
    case WL_NO_SHIELD: return "WL_NO_SHIELD";
    case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
    case WL_NO_SSID_AVAIL: return "WL_NO_SSID_AVAIL";
    case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
    case WL_CONNECTED: return "WL_CONNECTED";
    case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
    case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
    case WL_DISCONNECTED: return "WL_DISCONNECTED";
  }
}

void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");

  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  Serial.println("Connected to wifi");
}

void startWiFi() { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection

typedef enum {
    WL_NO_SHIELD        = 255,   // for compatibility with WiFi Shield library
    WL_IDLE_STATUS      = 0,
    WL_NO_SSID_AVAIL    = 1,
    WL_SCAN_COMPLETED   = 2,
    WL_CONNECTED        = 3,
    WL_CONNECT_FAILED   = 4,
    WL_CONNECTION_LOST  = 5,
    WL_DISCONNECTED     = 6
} wl_status_t;

  WiFi.begin(ssid, password);
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting Wifi...");
  delay(5000);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("NOT Connected to wifi");
    Serial.print("Status: ");
    Serial.println(wl_status_to_string(WiFi.status()));
    WiFi.begin(ssid, password);
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
    WiFi.mode(WIFI_STA);
    delay(5000);
    ESP.restart();
  }

  //If connection successful show IP address in serial monitor
  Serial.println("Connected to wifi");
  printWifiStatus();

}

void testscrolltext(char * text) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(WHITE);
  display.setCursor(10, 0);
  display.println(F(text));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

OLED doesn't work. But INA219 works perfectly.
Second try:
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA1 21  //OLED SSD1306
#define SCL1 22  //OLED SSD1306
#define SDA2 5  //INA219
#define SCL2 4  //INA219

TwoWire I2Cone = TwoWire(0);
TwoWire I2Ctwo = TwoWire(1);

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char* ssid     = "SSID";
const char* password = "PASSWORD";

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  I2Cone.begin(SDA1,SCL1,400000);
  I2Ctwo.begin(SDA2,SCL2,400000);

  I2Cone.beginTransmission(0x3C);
  I2Ctwo.beginTransmission(0x40);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

  startWiFi();
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{

      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

OLED works perfectly. But INA219 doesn't work.
How to make both OLED SSD1306 and INA219 works simultaneously?
Please help...

why does your code contain WiFi functions? .... reduce your code to minimum ..... display fixed text on the OLED and read a single value from the INA219

why do you use two instances of TwoWire? I2C is a bus. connect both devices to the same pair of pins

I have used a 128*64 oled display with a ina219. Both of them were working fine. Check the below code. Hope it helps.
#include <Adafruit_INA219.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>

#define I2C_OLED_ADDRESS    0x3C
#define I2C_INA219_ADDRESS  0x40

#define OLED_RESET  4

 Adafruit_SSD1306 oled(OLED_RESET);
 Adafruit_INA219 ina219;

 void initialize_device () {

  oled.begin (SSD1306_SWITCHCAPVCC, I2C_OLED_ADDRESS);
  oled.setTextColor (WHITE);
  oled.clearDisplay ();

  ina219.begin ();
}

 void refresh_oled (float current_ma, float load_voltage) {
  oled.clearDisplay ();

  oled.setTextSize (2);
  oled.setCursor (0, 0);
  oled.print ("V:"); oled.print (load_voltage); oled.print ('V');
  oled.setCursor(0, 20);
  oled.print ("I:"); oled.print (current_ma); oled.print ("mA");

  oled.display();
}

 void setup () {
  initialize_device ();
}

 void loop () {

  float current_ma = ina219.getCurrent_mA ();
  float load_voltage = ina219.getBusVoltage_V () + (ina219.getShuntVoltage_mV() / 1000);

  refresh_oled (current_ma, load_voltage);

  delay(100);
}

Please note that both of the modules were connected to the same I2C bus lines.

Thanks a lot for the note thilinaur. Because of your note, I realized my mistake. I2C doesn't need separate SDA SCL pins. As long as each device has separate addresses then using same SDA SCL pins will works.

I think that the issue is during INA219 initialization.
According with the begin function of class Adafruit_INA219.
Use:

ina219.begin(&I2CTwo);

instead of

ina219.begin();

According with the constructor of class Adafruit_INA219, default INA219 address is 0x40. As long as INA219 address on 0x40, no need ina219.begin(&I2CTwo). ina219.begin() will find 0x40 automatically.

@wieb the problem is NOT the address but the instance of i2c class to be used. I meant ‘’begin’’ function and not constructor.

Here is the code for connecting I2C OLED SSD1306 and I2C INA219 on ESP32 which will works simultaneously
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA 21  //OLED SSD1306 & INA219 pin
#define SCL 22  //OLED SSD1306 & INA219 pin

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char* ssid     = "SSID";
const char* password = "PASSWORD";

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  Wire.begin(SDA, SCL);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

  startWiFi();
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{

      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

const char* wl_status_to_string(wl_status_t status) {
  switch (status) {
    case WL_NO_SHIELD: return "WL_NO_SHIELD";
    case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
    case WL_NO_SSID_AVAIL: return "WL_NO_SSID_AVAIL";
    case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
    case WL_CONNECTED: return "WL_CONNECTED";
    case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
    case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
    case WL_DISCONNECTED: return "WL_DISCONNECTED";
  }
}

void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");

  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  Serial.println("Connected to wifi");
}

void startWiFi() { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection

typedef enum {
    WL_NO_SHIELD        = 255,   // for compatibility with WiFi Shield library
    WL_IDLE_STATUS      = 0,
    WL_NO_SSID_AVAIL    = 1,
    WL_SCAN_COMPLETED   = 2,
    WL_CONNECTED        = 3,
    WL_CONNECT_FAILED   = 4,
    WL_CONNECTION_LOST  = 5,
    WL_DISCONNECTED     = 6
} wl_status_t;

  WiFi.begin(ssid, password);
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting Wifi...");
  delay(5000);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("NOT Connected to wifi");
    Serial.print("Status: ");
    Serial.println(wl_status_to_string(WiFi.status()));
    WiFi.begin(ssid, password);
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
    WiFi.mode(WIFI_STA);
    delay(5000);
    ESP.restart();
  }

  //If connection successful show IP address in serial monitor
  Serial.println("Connected to wifi");
  printWifiStatus();

}

void testscrolltext(char * text) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(WHITE);
  display.setCursor(10, 0);
  display.println(F(text));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

NOTE: Both OLED SSD1306 and INA219 must be using the same SDA & SCL pins (pin 21 & pin 22 on ESP32).
Hope this will help anyone who has same issue like me.


text:
Why my LCD does not work with this if statement?
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int greenLedPin = 12;
int blueLedPin = 11;
int redLedPin = 8;
int yellowLEdPin = 9;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  pinMode(greenLedPin, OUTPUT);
  pinMode(blueLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLEdPin, OUTPUT);
  Serial.begin(9600);
  while (! Serial);

}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(lightSensorPin));
  analogValue = analogRead(lightSensorPin);
  if (analogValue < 50) {

digitalWrite(redLedPin, HIGH);

  }
  else if (analogValue >= 50 && analogValue <= 99) {
    digitalWrite(yellowLEdPin, HIGH);
  }
  else if (analogValue >= 100 && analogValue <= 300) {

    digitalWrite(blueLedPin, HIGH);
    lcd.print("its bright");
 }
  else {
      digitalWrite(greenLedPin, HIGH);
      lcd.print("its bright");
      }

  delay(3000);
  digitalWrite(greenLedPin, LOW);
  digitalWrite(blueLedPin, LOW);
  digitalWrite(redLedPin, LOW);
  digitalWrite(yellowLEdPin, LOW);
  lcd.clear();

}

I'm very new to this so sorry if its a dumb mistake and I know my LCD is working right, since I have tested it so all the pins are good.

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. What happens if you change the wiring to use a different pin and update the code accordingly?

thanks so much this seems to have worked for me

You're welcome. I'm very glad to hear that! I have written a formal answer so that this question can be considered answered by the Stack Exchange system. If you consider it the correct answer, you can "accept" it.

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. In general, it's best to avoid using pins 0 and 1.
You need to change the LCD wiring to use a different pin and update the code accordingly. For example, if you moved the LCD's RS pin connection from pin 1 on your Arduino to pin 13, you would update this line from:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

to:
LiquidCrystal lcd(13, 2, 4, 5, 6, 7);

After that, your LCD should work correctly.


text:
Arduino based fully controlled aquaculture
I am doing a project on aquaculture,so I am using temperature sensor, water level sensor, dissolved oxygen sensor, pH sensor and also 4 motor's and water heater is it possible for a single Arduino to run all these at the same time??

yes, it is possible, if you use the right components and are a good programmer

Yes. Arduino has that much capability. But you have to plan properly how to operate your module and provide proper functionality.

I would suggest finding sensors that work on an I2C bus. This way all the sensors are only using two pins for data. That will free up other outputs for motors, heaters that will probably be on relays or other drivers that need a single or multiple pins for each devices.  As you start to plan it out, if you do run out of pins on a arduino uno, look at the Mega, as it has many more GPIO pins as well as multiple dedicated UART ports.
Bottom line, find your sensors, drivers, see what type of communication they require, and start to make a list of how many separate io pins you need. Then that will tell you which board is suitable for your project.


text:
How to check whether my arduino-mega ADC is sampling correctly?
I have a code which samples the given input signals with sampling rate 256hz. I plotted the graph of FFT and was able to see the peaks at the expected frequencies.But I would like to know whether my ADC is sampling correctly or not?Is there a way to do it?`
    void setup()
{ Serial.begin(38400);
}

const unsigned long READ_PERIOD = 3906;  // 3906 us: 256 Hz
void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A3);
        int val_a2 = analogRead(A5);
        int val_a3 = analogRead(A7);
       Serial.print(val_a0);
       Serial.print("  ");
       Serial.print(val_a1);
       Serial.print("  ");
      Serial.print(val_a2);
      Serial.print("  ");
        Serial.println(val_a3);
    }
}

In this case the baud rate will be real bottleneck. You have to send from 110 to 230 bits per reading (1 start bit, 8bits data, 1 stop bit)*(3*2 spaces + 4-16 number characters + 1 line feed).
That means best case (all numbers are less than 10) 349 readings per second. And worst case is 166 readings per second (all readings are more than 999).
So it's about 10% probability to be sampled correctly.
You can check if the next time (with misleading name lastReading) is less than current time. That means you are already too slow.


text:
USB Communication between Arduino Nano and UHF Reader module
I am working on a project that requires a UHF reader development kit that can communicate using either RS232 or by USB.  Via USB and a Serial terminal, I have been able to send commands to the reader as well as analyze its response.
My goal is to send these same commands to the reader, but through an Arduino Nano.  My first instinct was to use the RS232, converting the signal via a MAX232.  However, this is for a school project, and my advisor preferred I try to work with USB.  I am familiar with UART communication, and I've been under the assumption that USB operates using UART.
I had purchased a USB converter that gives me access to the pins, but it had two additional pins than I was not expecting: CTS and DTR.  I attempted to communicate despite these pins (just leaving them open, and connecting Rx, Tx, Vcc and GND as I normally would).  When plugged into the UHF reader, the device did power on (as it draws power from the USB connection), however, it did not receive the output signal from the Arduino Nano.
I know that my baud rate and other settings are correct, because, as I have said, communicating via USB and a Serial terminal gives me no problems.  My initial thought is that I need to properly connect the CTS and DTR pins, but immediately I could not find a good reference on how to do this, and I am not entirely convinced this is the issue.  My other thought was that perhaps I am writing out my HEX values wrong from the Arduino, using a line similar to the following, where "UHF_Reader" is defined by SoftwareSerial:
UHF_Reader.write(0xAA);

However, it appears to me from research that this is indeed the correct way to output HEX values via serial.
My final attempt to resolve this was to connect the micro-USB from the Nano to the USB of the reader, and then use Software Serial in conjunction with the USB converter to analyze the output on a Serial terminal, while powering the Nano via a 5V power supply.  However, since the reader draws power from the USB port, it did not even turn on when I attempted this (I am assuming that the Vcc can only be supplied from the USB end?).  Regardless, this attempt proved useless as well.
If anyone can offer any advice, or point me towards any references for something similar, I would much appreciate it!  I have spent a while on this, and I just can't figure out what the problem is.
For reference, the reader I am using is found here: UHF Reader
And the USB converter I am using is here: USB Converter

I've been under the assumption that USB operates using UART.

No. You have it backwards.  Devices can emulate a UART (known as CDC/ACM) over a USB connection as one of the many possible device profiles, but it is about as far from being a UART as an F1 car is from a Penny Farthing.
USB operates on a strict Master / Slave principle. That is, it has a single master device, called the Host, which coordinates all the devices on the bus and makes requests to them.  Everything you plug into a USB system is a Device and requires a Host to tell it what to do.
Neither the Nano, nor this adaptor you bought, are Hosts. They are just Devices. And Devices cannot talk to Devices. Only Hosts can talk to Devices.
Which means you need a Host in there somewhere. If you want it controlled by Arduino then you need a USB Host Shield (or something similar) which normally communicates over SPI.
If the device you are trying to talk to uses the CDC/ACM profile then you can use the USB Host Shield with it. If it uses a proprietary profile, like the CH340G or FT232, then getting it to work with the USB Host Shield will be much harder (maybe even impossible) unless you are intimate with the underlying protocol used.


text:
Digispark Attiny85 ultrasonic sensor input problem
I was trying to use ultrasonic with digispark Attiny85 board and used separate pins for trigger and echo, and used MM5451 led controller as a display, I uploaded the code successfully the problem is if the echo pin is connected to it at startup board stops/freezes I don't know but code doesn't work, and if I connect the echo pin few seconds after the board starts everything works fine.
Below is the code I wrote
#define clock 0
#define data 1
#define trig 2
#define echo 3
byte c[5]={10,11,11,0,12};
long dist=0;
const uint8_t digits[15]={
    B1110111,
    B1000100,
    B1101011,
    B1101110,
    B1011100,
    B0111110,
    B0111111,
    B1100100,
    B1111111,
    B1111110,
    B0111011,
    B0010011,
    B1011101,
    B0111001,
    B0000000
};
void setup()
{
    pinMode(clock,OUTPUT);
    pinMode(data,OUTPUT);
    pinMode(trig,OUTPUT);
    pinMode(echo,INPUT);
    digitalWrite(clock,LOW);
    digitalWrite(data,LOW);
    digitalWrite(trig,LOW);
}
void pulse()
{
    delayMicroseconds(5);
    digitalWrite(clock,HIGH);
    delayMicroseconds(10);
    digitalWrite(clock,LOW);
    delayMicroseconds(5);
}
long ultrasonic(boolean ci)
{
    long distance;
    unsigned long pulsetime;
    digitalWrite(trig,LOW);
    delayMicroseconds(5);
    digitalWrite(trig,HIGH);
    delayMicroseconds(10);
    digitalWrite(trig,LOW);
    pulsetime=pulseIn(echo,HIGH);
    if(ci)
    {
        distance=pulsetime/58;
    }
    else
    {
        distance=pulsetime/148;
    }
    delay(50);
    if((distance<450)&&ci)
    {
        return distance;
    }
    else if((distance<180)&&(!ci))
    {
        return distance;
    }
    else
    {
        return 0;
    }
}
void show(byte a[5])
{
    delayMicroseconds(5);
    digitalWrite(data,HIGH);
    pulse();
    for(byte x=0;x<5;++x)
    {
        byte data1=digits[a[x]];
        for(byte y=0;y<7;++y)
        {
            if(data1&(1<<y))
            {
              digitalWrite(data,HIGH);
                pulse();
            }
            else
            {
                digitalWrite(data,LOW);
                pulse();
            }
        }
    }
    digitalWrite(data,LOW);
    pulse();
}
void loop()
{
    show(c);
    delay(2000);
    while(1)
    {
        dist=ultrasonic(true);
        if(dist>0)
        {
            byte i=3;
            c[4]=14;
            c[0]=14;
            c[1]=14;
            c[2]=14;
            c[3]=14;
            while(dist>0)
            {
                c[i]=(dist%10);
                if(i==0)
                {
                    i=4;
                }
                dist/=10;
                --i;
            }
            show(c);
        }
        delay(200);
    }
}

Pins 3 and 4 are used for USB (during programming). Try using pin 5 instead.
Or swap it with one of the clock, data, or trig outputs (i.e. 0,1,2)

Gerben thanks for your replay, one thing I want to mention is I used same code and powered digispark with my phone otg and it's working and it doesn't work when I connect it to phone charger's USB output, weird right.

That  is weird indeed. Did my suggestion of swapping/changing pin(s) help?

That echo pin was sending pulse at startup without trigger. and it was messing with USB signals of bootloader at startup which making bootloader to stuck. I did what you said, swapped pin and it's working. But one problem is that USB singals on startup messing with my display by sending invalid data, I have to use pin 3,4 because 5th pin doesn't work  it is set as reset pin my board is digispark clone

Try some other combinations. Like for example using pins 3 and 4 for trig and data. Having the bootloader pulsing those won't have many side effects, as far as I can tell.


text:
ESP8266 Supply Voltage dropping below 3.3V
I am trying to power an ESP8266 with a 3.3V regulator (this one, can supply ~ 1A). I've been struggling for days to get the ESP to work – it will occasionally boot, occasionally connect, but then not work again for hours. What I mean by "not working" is that it will often have trouble communicating over UART; or, upload my code, but not run it; or, run my code and crash on an Exception 0.
Now I have noticed that my voltage rail is dipping severely, sometimes below 3V. If I press my reset button, the level returns to 3.3V, but then when the ESP "boots" (but often not running any code, or crashing), it dips back to 2.9V. It is also fine while programming.
Does this suggest my ESP is simply fried? It's possible I briefly misconnected a wire when I first got the unit.

power an ESP8266 - is this a bare esp8266 (which one, 01, 7, 12 etc) with nothing else connected to it?

Yeah, ESP-01, I think. Just have a 5/3.3V logic level converter and some decoupling caps.

Are you just using a bare regulator, or do you have an actual module?

Just have a 5/3.3V logic level converter with something connected to that? if not, remove that, see if that "helps"

Just the bare regulator, with the recommended caps. Main power supply is Arduino 5V via USB.

@JaromandaX the logic level converter is for USB to Serial.

what's the capabilities of the power supply? I mean if the input to the regulator is 5V 100mA I dont' think you can get 3v3 @ 1A output ... can you?

It's my computer's USB, via Arduino. Arduino has a 500 mA fuse and a FET switch on USBVCC. Not sure how much my computer is actually providing. Maybe I'll try with a powered USB hub.

How hot is the regulator getting? To draw anywhere near the rated 1A you need lots and lots of heatsinking.

I think it was my computer. Powered USB hub seems to be working..."Current Available (mA): 500
Current Required (mA): 100
Extra Operating Current (mA): 0"

how much is the arduino itself using?

None. I don't have a FTDI cable :/ so the arduino is held reset (Reset tied to GND) and I'm just using it for the USB to Serial.

The ESP8266 will do an analog calibration when it is running the user code. This will typically be the worst case power requirement. The peak current requirement can be as much as 1/2 an amp. While your regulator probably can supply that I would bet your interconnecting wiring, and maybe the power source, are causing too much voltage drop.
The fact that you can see the voltage go down to 2.9 volts makes me thin that you have serious problems.
Early on when I started with the ESP8266 I was getting flaky operation. I put it down to bad code. But eventually I ruled that out. I took my setup to work (where I design electronic products) and looked at the power connections with a digital scope at the module. Right at the last point before the traces run under the shield. (I use the ESP-12 modules) It dipped just under 3.0 volts for two microseconds, and that was enough to cause a reset.
These things are not tolerant to any power dips. And this is why I recommend anyone starting with the ESP8266 to buy a Nodemcu or a Wemos type module. Something that has the regulator right at the processor.

Yeah, I definitely played myself here. The $5 savings were not worth the hassle.

You probably have not damage the module. It will probably work fine if all the rest of the circuitry is done well.

It's working now with a powered USB hub. See answer below.

It was a power issue. Everyone tells you the ESP8266 needs a lot of current, and I didn't believe them.
In case anyone else runs in to this issue, I was powering the ESP via a 3.3V regulator (fine), being fed from and Arduino's 5V (fine). However: I was plugging my Arduino directly into my MacBook. It seems that my Mac was limiting USB power. Using a powered USB hub (max current ~2A) worked fine, but you could probably also get away with directly powering VIN on the Arduino (or a standalone 3.3V supply).


text:
MQTT - Can lastwill be sent to multiple topics?
I'm using an ESP8266 as an IOT device, with MQTT to send status messages.
Each device have its own availability topic, to state its online or offline state ( needed for Home Assistant indication on web GUI )
Since multiple devices are present- I was wondering if a lastwill status can be sent for a joint topic to be monitored ( for example :"device_id:offline" )
my relevant part of the code defining a lastwill for devices topic is : mqttClient.connect(deviceName, user, passw, availTopic, 0, true, "offline")
EDIT1:
using PubSubClient.h

no, last will is set up when connecting to the broker (as you  know), and you can only set one topic with one value - what you can do in home assistant is use that LWT topic for however many "devices" you need - I'm guessing by "devices" you mean multiple devices connected to a single ESP8266 ... actually, reading your question fully, I see you more or less know what to do ... use a "joint" topic

@JaromandaX by multiple devices I meant 10X ESP8266 devices sending different sensor readings. If I was misunderstood - I meant that I want I single topic to recieve all offline notification from all 10 devices ( a topic that will be saved as a log file ).

oh, so 10 devices sending to the one topic? that makes no sense ... if one is down, then all are considered down?

No. Sorry for my bad English. Each device will identify in its last will message as ‘offline_dev1’

so each device will use exactly the same MQTT topic?

Yes. A common topic for offline notifications only for all devices

I guess I'm having trouble with that because my LWT's are all with the retain flag - but if you are not using retained messages then it's up to the subscriber to deal with getting messages from different devices on the same topic - not sure if that would make the setup for home assistant more complex than it would be if you had one topic per device

Technically, as far as MQTT is concerned, there is no problem with multiple devices publishing to the same topic. MQTT is fine with that. It's just a broker - it doesn't care where things come from or what they contain. It's dumb.

@Majenko - that i know well, but can I config last will to be sent to more that one topic ?

That depends on the MQTT library (and maybe the MQTT server) you're using.

@Majenko see in edit 1

The "Last Will & Testament" facility of MQTT is controlled by the server, not the client.
The topic and payload are specified when the client connects as part of the connection handshaking. When the client disconnects this stored information is published automatically by the server.
The specification only allows for one topic and payload to be set.
Of course, you can specify the same topic for many clients and give each one its own distinct payload, but you can't also have a unique topic for each client at the same time.
This is according to the specification - however that doesn't stop a broker implementing its own extensions to the specification to allow such things - but I know of no such extensions being implemented. But, given the open-source nature of many MQTT implementations (PubSubClient.h and Mosquitto, for example), there is no reason you couldn't extend the protocol to implement your own requirements (at the cost of compatibility with other systems of course).


text:
SG90 not responding with Arduino Uno
I bought an SG90 servo motor, seller demonstrated by direct supply check, it works there but with Arduino servo sweep check it does not respond: no error during compiling and uploading, but it does not respond.
While other Arduino examples are working correctly like blink example.
I have changed another one but result is the same.
Neither it moves by Arduino nor after installing a grbl shield, where is the problem?

Please, post your arduino sketch and schematic connections.

Even a small servo motor requires a lot of current. You could add a power supply. Do you use a good quality usb cable? The component on the right of the arduino board, with the golden stripes is a polyfuse of 500mA. That servo motor can draw 500mA or more.

Leoc 7, I have already attached a picture.

@AdnanTahir please post your code. As Leoc7 said, usually powering servos from the Arduino directly isn't the best idea, but in my personal projects I've powered several servos from my arduino, as long as they weren't under any load :)

Arduino can readily power an SG90 servo under no load in my own experience. Also see this question on Electrical Engineering SE. If you're seeing no response, there is a fault in the wiring, the code, or the servo itself.
I think I'm seeing the servo's signal wire (orange) connected to the yellow wire to pin 9. Is your sketch attaching pin 9? What is the brown wire connected to the Arduino near the servo's power & ground (red & black)?

@JRobert those servos use Orange for Sig, Brown for GND and Red for Vcc. I use them all the time in my RC projects, and haven't had any issues using Arduinos either. My guess is coding, we'll see if he posts it or not

OP has issue when using Arduino servo sweep - it's an example in the Servo library - it uses pin 9 for Signal ... so I dare say it should work unless OP modified the example (highly doubt it)

Friends, I did not modify code even a litte bit, I uninstalled arduino and reinstalled but whenever I tried the code servo did not rotate, however no error occurred in compile and upload. The code is same in the arduino IDE Examples >Servo >Sweep. I wanted to ask if there is a possibility of any fault in my arduino board 5v, gnd or signal pin. Because servo with direct 5v battery power supply is rotating that means servo is fine. I watched several videos regarding sg90 test with arduino uno and same I have been trying to do but the outcome is NO ROTATION as I have mentioned in my query.

I always tried arduino IDE menu option i.e. Examples > Servo > Sweep, I did not try any thing manually or a self written code. Wiring is accurate as shown in my attached picture. I wanted to know that is there any action missing or it is a confirmed board fault.

Then your next step should be to measure the 5v with a DVM: at the 3-pin connector with- and without the servo connected to it, and at the Arduino pin the connector is plugged-in to. Maybe all of the Arduino 5v pins (without the servo connected) if everything else wasn't what it should be (5v +/- a few millivolts).

@HavocRC: I may be confused by a shadow, but it looks rather like there are 3 conductors connected to the top row of the board and a 4-th one to the bottom (pin 9).

@AdnanTahir we know these servos work fine with Arduinos, and since the wiring is correct, here's all that could be wrong: Broken 5v rail from Arduino, broken PWM pin on 9, or a faulty servo. You can even measure with your DMM if the P9 is putting out the proper PWM frequency/duty cycle.


text:
What would cause one Arduino to be recognized but not another?
I have two Arduinos, A cheap china-knockoff and an original one. I have had no problem with either of them before. But when I moved from connecting the original with a USB A-hub to running it over USB-C my computer can't find it any more.
I run OSX and tried to install a new USB serial driver. Didn't work either. Then I tried the cheap clone, same computer, same wire, same computer and it works fine.
The faulty Arduino powers up and I can reset it. So it seems to be working. What might cause this?

Do the two boards use different USB chips? I.e., the clone use CH340G?

How can I tell?

By looking. Black thing. Near the USB connector on the board.

Yeah, the clone is CH340G... what's the original one?

ATMega16U2. There's the probable difference that means one is detected and the other not. As to why the genuine one isn't detected, I have no idea.  The clone uses the custom CH340G driver. The original uses the default CDC/ACM driver. I have an itch at the back of my head about something to do with CDC/ACM in later versions of OS X, but I don't know what.

This might help: https://discussions.apple.com/thread/8297132

Are you 100% sure the USB cable is a data cable, not just a power cable? A power cable will only provide power to the USB device, but no data communications.

Thx, the problems started when I went from a usb hub to usb3. @tom, yeah, it works with the chineese knockoff...


text:
NodeMCU with digital sound sensor - Can't find examples or good documentation
I'm very new to this world, and trying to hack one of my first projects have proven hard without solid documentation or examples to copy like I usually do.
I've got a https://www.gearbest.com/transmitters-receivers-module/pp_366523.html NodeMCU ESP8266 board that I'm trying to pair with a Sound Sensor. I wanted digital and simple solution, but I'm thinking I might need a library to make it work?
The closes examples I've found are DHT11/22-sensors using the DHTlib library.
The Waveshare-Wiki contains the following expample that I've tried to modify without any luck.
int sound_din=2;
int sound_ain=A0;
int ad_value;
void setup()
{
  pinMode(sound_din,INPUT);
  pinMode(sound_ain,INPUT);
  Serial.begin(9600);
}
void loop()
{
  ad_value=analogRead(sound_ain);
  if(digitalRead(sound_din)==LOW)
  {
    Serial.println("Noise!");
    Serial.println(ad_value);
  }
  else
  {
    Serial.println("Quiet!");
  }
  delay(500);
}

I've also tried to modify/simplify this code to just print the digital output:
#include <ESP8266WiFi.h>

int dig_in=4; //Using D2-pin on my NodeMCU-board
int dig_value;

void setup()
{
  pinMode(dig_in,INPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println(digitalRead(dig_in));

  delay(1000);
}

This results in varius gibborish and junk. I've seen plenty of various errors, and the board seems to crash quite a lot. I've tried swapping out the NodeMCU and the Sound level sensor with new ones, but still seem to be getting the same problems.
Any pointers? Thanks!
UPDATE: I've gotten further by using the following code from this example:
// Program: Sound Level Measurement
#include <ESP8266WiFi.h>

int num_Measure = 1280 ; // Set the number of measurements
int pinSignal = A0; // pin connected to pin O module sound sensor
long Sound_signal;    // Store the value read Sound Sensor
long sum = 0 ; // Store the total value of n measurements
long level = 0 ; // Store the average value

void setup ()
{
  pinMode (pinSignal, INPUT); // Set the signal pin as input
  Serial.begin (74880);
}

void loop ()
{
  // Performs 128 signal readings
  for ( int i = 0 ; i <num_Measure; i ++)
  {
   Sound_signal = analogRead (pinSignal);
    sum =sum + Sound_signal;
  }

  level = sum / num_Measure; // Calculate the average value
  Serial.print("Sound Level: ");
  Serial.println (level);
  sum = 0 ; // Reset the sum of the measurement values
  delay(1000);
}

The result is an output that seems to be pretty close to the relative sound level in the room. I've got a couple of issues that I'm still working on:

NodeMCU randomly crashing. The stacks are not exactly alike, but I've copied one of them down below. I've yet to decode this.
Pretty high noise floor. I.e. anything below around 60dB reads as 3/4/5. I've got to test this some more, it might just be the microphone is not sensitive enough.

Exception (0):
  epc1=0x40103861 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000
  depc=0x00000000
ctx: sys
  sp: 3ffffcd8 end: 3fffffb0 offset: 01a0
stack
  3ffffe78:  3fffc200 00000022 00000000 03c4345f
  3ffffe88:  00000000 4000050c 3fffc278 4010268c
  3ffffe98:  3fffc200 00000022 3ffffeb0 00000000
  3ffffea8:  000002ea 00000000 40000f68 00000030
  3ffffeb8:  0000001e ffffffff 40000f58 00000000
  3ffffec8:  00000020 00000000 3ffe91f0 c06301dc
  3ffffed8:  3ff20a00 c0000000 00003000 00000000
  3ffffee8:  00000058 3fffdab0 00000000 3fffdcc0
  3ffffef8:  3ffe8b88 00000030 00000000 00000000
  3fffff08:  00000020 40101612 3ffe8ae0 40203ebb
  3fffff18:  3fff01ac 40106fb4 00000000 40208a24
  3fffff28:  3ffed518 40222a2d 3ffef904 3ffef900
  3fffff38:  01331819 40105e3e 00000000 00000000
  3fffff48:  60000600 00000100 00000058 00000001
  3fffff58:  4010483a 3ffecc60 3fff01ac 401011a6
  3fffff68:  00000001 00000000 402187a8 40100f73
  3fffff78:  00000000 00000000 40100fae 00000000
  3fffff88:  00000002 3fffdcb0 40203b76 3fffdab0
  3fffff98:  00000000 40202303 3ffe8b88 40000f49
  3fffffa8:  3fffdab0 40000f49 40000e19 40001878
  stack

Where did you copy and paste from to get that question title?

Found it. Crosspost from: http://forum.arduino.cc/index.php?topic=587394.0

the schematic on the wiki shows that the module has two outputs ..... one is an analog output and the other is digital ..... the digital output is generated by amplifying the analog output by a large amount and clipping the result ..... the digital signal leading and trailing edges probably coincide with the zero crossings of the analog signal

Majenko: did I mess up the title when crossposting? :)
@jsotola so I guess I can just as well go with the the analog signal only? I spent a lot of time last night trying to figure this out, and I've gotten a lot further I think. I'm updating the original post.


text:
How is this simple transistor circuit suppose to work?
I've tried to replicate this circuit today.

My motor is a computerfan, they apperntly don't need a flyback diode since there are no brushes.
I used a 12V power source for my arduino and hooked it up via
VIM.
I used the arduino ground as external power source.
I verified that the transistor worked as expected with a voltmeter.

Here is the transistor I used:
As I understand this, the transistor is stimulated to "steal" electrons away from the motors circuit. But it seems connected to the base. Why would you do that?

Not all transistors have the same pinout. How do you know what transistor is used in that drawing?

An answer may be found here: https://www.arduino.cc/en/Tutorial/TransistorMotorControl

The circuit might be totally wrong. Where does it come from?

It seems like it is wrong, it's from a magnetic stirrer tutorial https://www.hackster.io/jdale18/magnetic-stirrer-88e726

@Himmators Thanks. Google picture search could not find the original picture. They use a tip31a, which has the pin in BCE order and is for a maximum current of 3 amps, that is more than the 100 milliamps of the bc548. They have forgotten a resistor to the base of the transistor.

There are many bad schematics and pictures online, and these pictures are really bad.
Do not try to make that. You may damage the Arduino board and the transistor.

Even the picture of the BC548 is wrong. The BC548 is always
called "BC548" and never "BC-548".
The BC548 is not a good choice to drive a motor. It can only
do 100 mA continuous.
The DC barrel socket has plus and minus wrong connected.
The 12V plus is connected to the Arduino GND.
That is not okay.
The transistor in the first picture is probably a
transistor with the pins in BCE order.
A resistor is missing to the base of the transisor.
Because of the missing resistor, the Arduino board
can be damaged.
When the breadboard has a bad connection to GND,
the 12V can go to pin 9 of the Arduino board.

@Dorian, there are no mystical higher alien intelligent thoughts for that schematic. It is obvious a wrong circuit that is meant to drive a motor with PWM using a transistor.
And last but not least:
There are a few different types of computer fans. Some have a capacitor inside and some will only accept a PWM signal to a PWM input.
Are you sure that your fan is able to accept PWM for the 12V power?

Wow, I sure learned a lesson here! I have a basic fan witout a PWM input, so the plan is to regulate the speed of the fan by changing the voltage. I tried this with a powercube and it seems to work fine :)

@Himmators please tell us what you want to do so we can help. You can add that to your question. Do you have a mosfet? A diode is always good, even if it might seem that it is not needed.

This looks like a circuit to monitor the power loss in the motor supply. If the motor is powered and the circuit is not interrupted then the collector will poll Arduino pin 9 to GND.


text:
Arduino Uno: avrdude: stk500_recv(): programmer is not responding
I have an original Arduino Uno board purchased directly from the official arduino website. I have used it successfully with IDE v1.8.5 on my Windows 10 laptop for various projects in the last 6 months.
Recently my laptop stopped working and I tried shifting the IDE to my old windows 8 laptop. I installed the latest IDE v1.8.8 on it. But whenever I am trying to upload the sample blink code to the arduino, I am getting the following - "stk500_recv(): programmer is not responding" error.
I have verified that the I have selected the right board - "Arduino/Genuino Uno" in the IDE. I can also see the driver installed in the windows "Device Manager" with COM3 as the port. I have selected COM3 as the port in the IDE as well.
Thinking that its a bit old windows 8 laptop, I tried installing the IDE on two other newer laptops (windows 7 and 10) along with the same troubleshooting steps as above. But unfortunately, same results.
I looked at the many links on internet and tried the following steps, but no luck so far.

Resetting the board: It flashes the LED on the pin 13 twice which means the chips are ok and resetting the board. This where I think the board is functioning well.
Tried using both "Upload" and "Upload using programmer" mode from IDE.
Restarting laptops multiple times.
Unplugging USB cable between laptop and arduino several times.
Reinstalled arduino ide version 1.8.5 which was on my old laptop.

Do I need to choose Tools --> Programmers? I guess this is not needed as I am using USB to upload code, but please advice. What else can I try? Please help !!
Here is the complete error:
================================================================
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Anurag\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         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 : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\Anurag\AppData\Local\Temp\arduino_build_337690/Blink.ino.hex"
avrdude: writing flash (930 bytes):

***Writing | avrdude: stk500_recv(): programmer is not responding
######avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding***
================================================================

UPDATE 1:
In the meanwhile -

I also changed my USB cable.
Tried on a MAC laptop as well.

No luck with these approaches as well.
I also tried the Arduino loopback test with my board and it is giving me positive results which suggests that my board is processing the data. May be the problem is only when uploading the code. I have updated my original post as well with these steps.
Still need help!
Thanks in advance,
Anurag

Have you tried to test with another Arduino?

@MatsK - Thanks for looking at this query. Unfortunately, I do not have another Arduino board to check. I have ordered a clone on ebay and expecting to receive it in a couple of days. Will try that as well.

@Matsk ... In the meanwhile, I also changed my USB cable and tried on a MAC laptop as well. No luck with these approaches as well. I also tried the arduino loopback test with my board and it is giving me positive results which suggests that my board is processing the data. May be the problem is only when uploading the code. I have updated my original post as well with these steps.

The output shows that avrdude (the uploading program) can contact your Arduino and is able to detect some settings. But as soon as it tries to upload it doesn't get the correct answers. Seems like the bootloader is damaged. Try to burn a new bootloader (you need an ICSP programmer for that, another Arduino with a special sketch and some basic hardware might do the job too).

A Programmer connects to the ICSP header. There are two - one for the 328P, with 2x3 male header pins. The 2nd is near the Aref header, is usually just holes (or solder filled holes), that is the one for the Atmega16U2 for the USB interface.  Select Upload using Programmer does nothing if you do have a Programmer connected to the 328P's ICSP header.

@Pylon - Thanks for looking at this query ! Yes, apart from trying a new Arduino, I guess putting a new boot loader is the only other option. I have seen some articles for this which used Arduino and some jumper wires. Is there a special sketch involved too? Do you have any good reference which I can try? Also, is this another arduino approach different than using ICSP programmer? Should I try both of the first does not work?

@CrossRoads - Thanks for the info about the programmers. Actually, I have not used any programmer so far. On one internet post, I saw someone trying that too, hence I also tried. At that time, I thought "programmer" is some internal software. But of course, it did not work as I was not using an actual hardware programmer at all.

Using an Ardiuno as a programmer to reload the 16U2 should supposedly work. I don't use any cards that use 16U2, I prefer FT232 for USB interface, so I go with ProMinis and plug on an FTDI Basic for downloading and debugging, then remove it when I use the ProMini (I don't do projects needing fulltime internet access for example). The 16U2 sketch is available in the Arduino folders somewhere.


text:
Cannot get pins on esp 8266 adafruit wifi module to read HIGH on pin 15
I have an esp8266 and I cannot get the value to read HIGH when 3.3v is applied to directly to pin by hand. I have an Arduino Uno powering the esp8266. It connects to the WiFi like it should, and now all I want is to manually see that when I apply 3v that the state will change from 0 to 1. Does anyone know how I can do this.
When I apply 3 volts directly to pin 15 it outputs 0. Even if I try digitalWrite on the pin and set it to HIGH it still says 0 and i serialPrint. My end goal if to use the arduino uno to fire and ouput on pin 8. On the arduino UNO side I am using a super sonic sensor. When the sensor is triggered I want to turn pin 8 on. From there I want to take pin 8 to feed pin 15 on the 8266 as an input. Before I did that I just wanted to see that when you manually apply 3v that the pin would read 1 or HIGH but no matter I do it wont change value. Once I get that value as HIGH I can send  a second request to the server like im already but now I want to say  that there was an intruder. Im not sure why the value wont change but being a beginner with arduino Im trying to keep it simple and ideally would like to wire it in this manner.
#include <SoftwareSerial.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "********";
const char* password = "********";

HTTPClient http;

static const uint8_t D8 = 15;
int featherPin = D8;

//int trigPin = 13;
//int echoPin = 12;
//int ledPin = 10;
//int hornPin = 11;
//
//int spaceIntruded;
//
//long duration, cm, inches;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin,INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Waiting for connection");
 }

//  Serial.begin (9600);
//  pinMode(trigPin, OUTPUT);
//  pinMode(echoPin, INPUT);
//  pinMode(ledPin, OUTPUT);
//  pinMode(hornPin, OUTPUT);
//  delay(5000);
//  Serial.println("Armed...");

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("yay connect");

    http.begin("http://10.150.40.121:3000/");
    http.addHeader("Content-Type", "text/plain");

    int httpCode = http.POST("Message from ESP8266");
    String payload = http.getString();
    Serial.println(payload);
    http.end();

    } else {
      Serial.println("Error in Wifi connection");
    }
//    digitalWrite(featherPin, HIGH);
    int sensorValue = digitalRead(featherPin);
    Serial.print(sensorValue);

//    if (digitalRead(featherPin) == HIGH) {
//      http.begin("http://10.150.40.121:3000/home");
//      http.addHeader("Content-Type", "text/plain");
//
//      int httpCode = http.POST("Message from ESP8266");
//      String payload = http.getString();
//      Serial.println(payload);
//      Serial.print("hi");
//      http.end();
//      } else {
//        Serial.print(featherPin);
//        Serial.println("I am not hot");
//      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(30000);

}

do you see how part of your code is properly formatted on gray background? .... that is because the text is indented by at least 4 spaces ....... please format the rest of the code ..... select all the code and click the {} icon

when I apply 3v that the state will change from 0 to 1 what are you applying 3v to? which pin? for how long? because you have a delay of 30 seconds in each loop - so you're only checking every 30 seconds

p.s. - I didn't think the esp8266 liked such long delays

also, what output are you currently getting with your code?

Right now when I apply 3 volts directly to pin 15 it outputs 0. Even if I try digitalWrite  on the pin and set it to HIGH it still says 0 and i serialPrint. My end goal if to use the arduino uno to fire and ouput on pin 8. On the arduino UNO side I am using a super sonic sensor. When the sensor is triggered I want to turn pin 8 on. From there I want to take pin 8 to feed pin 15 on the 8266 as an input. Before I did that I just wanted to see that when you manually apply 3v that the pin would read 1 or HIGH but no matter I do it wont change value. Once I get that value as HIGH I can send a...

a second request to the server like im already doing saying that there was an intruder. Im not sure why the value wont change but being a beginner with arduino Im trying to keep it simple and ideally would like to wire it in this manner.

Pin 15 is one of the boot configuration pins (0, 2, 15) and must be LOW at boot. To ensure it, dev boards with esp8266 have external pull-down on pin 15 (and pull-up on 0 and 2). To read the pin HIGH you must overcome the pull-down.
Adafruit Feather HUZZAH has 4.7kOhm resistor for the pull-down, so it is a 'strong' pull down. NodeMcu has 12kOhm resistor on io 15.
From schematics of Adafruit Feather HUZZAH

Note: setting pin as OUTPUT and HIGH doesn't make it read HIGH in code. Only INPUT pin state can be read with digitalRead (only on some MCUs digitalRead reads the same register set by digitalWrite).

This is unclear to me. What do you mean by overcome the pulldown? Could your break it down a little further or send me in a direction to find a resource that can clarify this. I having a hard time visualizing what you mean fully. Thanks again for taking the time to reply. I am also setting the input on line 36 as an input. I tried making forcing it HIGH to try a different idea but I know Im not fully versed with what I can and cannot do.

which esp 8266 adafruit wifi module you have exactly?

https://www.microcenter.com/product/460313/feather-huzzah-with-esp8266-wifi
Also it doesnt have to be pin 15 if the pulldown is an issue. I tried Serial printing all the pins digitalRead states from the arduino feather and i picked one that was in an off state so that it would be hot with 3.3v from the arduino when it fires the output on pin 8 when it meets the alarm triggered condition. Let me know if what Im sating is clear.

you can't determine the state of output pin with digitalRead. most of esp8266 pins are HIGH at power-up or boot

Im not trying to dertermine the state of the output pin with digital read. Im plan to fire the arduino uno on pin 8 as an output. From the that output will be hot at 5v. I take the 5 volts from the arduino board and step it down to 3.3v with a voltage regulator and two capcitors. Once I have that voltage I want to feed the output from the volatege regulator to then feed pin lets say 15 on the wifi module. Pin 15 on the wifi module would be an input. I want to determine the state of the input on the wifi module like this. I have already confirmed power all the to pin 15 and to negative

even though I read the voltage on my meter the state of the input will not change went i serial print the digital read value that is saved to a variable

I understand it but from here I can't say more that, that the input must be stronger then the pull-down. but it shouldn't be a problem, but the pull-down is strong (4.7kOhm. 10 kOhm is usual). try other pin.

Ok I understand. Im trying to understand your clue. Im not sure what you mean by pull down and 10kOHM is the usual. I just started working with arduino yesterday so I am not familiar with those terms or what I should be searching for online" I've been reading docs for several days to get it up to this point. I will try to see what I can find from what you expressed. Thanks

https://www.electronics-tutorials.ws/logic/pull-up-resistor.html

http://hyperphysics.phy-astr.gsu.edu/hbase/electric/watcir.html

Thank you very much. I understand what you mean now. This is very helpful. You're saying that I theres a high resistance on the pin and that my value is not being accurately translated. I will read this material and see if I can find for getting the pin back to a true state.

So im reading something about using input_pulldown or input_pullup to change the state. Does this sound familiar to you at all? Wondering if I am on the right track.

Hey thanks for your help yesterday. It helped a lot. Got me to the next step.