text:
Help combining digital and analog code in arduino programming
So I'm making a device that does 3 things,

Measures frequency of an audio signal through a microphone
Checks whether there is a weight placed on a pressure pad (my pressure sensor works through the resistance of the material changing when a weight is placed on it)
Measure ambient room temperature

I have coded each individual section and tested them individually to find them work great, here are the sketches.
Frequency sketch :
// runs every time thru the loop
  setInputState();

  // count every transision HIGH<->LOW
  if (inputState != lastInputState) {
    count++;
    lastInputState = inputState;
  }

  if (millis() - previousCountMillis >= countMillis) {
    previousCountMillis += countMillis;

    // show Hz on Serial too if available
    Serial.print(count);
    Serial.println(" Hz");
    ledtest = count;
    // reset to zero for the next half second's sample
    count = 0L;
  }
  if (ledtest >= 400 && ledtest <= 850){
    digitalWrite(A2, HIGH);
  }
  else if (ledtest < 400 || ledtest > 850){
    digitalWrite(A2, LOW);
  }
}

Here is the pressure sensor sketch
int Vin = 5;
float Vout = 0;
float raw1 = 0;

int R1 = 770;

int R2old1 = 0;

int R2new1 = 0;

int R2avg1 = 0;

int pressurelog = 0;

void setup() {
  pinMode(A0, INPUT);             //Receive pressure voltage
  pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
}

void loop() {
  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2old1 = Vout*R1/(Vin-Vout);

  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2new1 = Vout*R1/(Vin-Vout);

  R2avg1 = (R2new1+R2old1)/2;

  Serial.print("Resistance: ");
  Serial.println(R2avg1);

  if (R2avg1 >= 1000){
    digitalWrite(A1, LOW);
    pressurelog = 0;
  }
  else if (R2avg1 <= 1000){
    digitalWrite(A1, HIGH);
    pressurelog = 1;
  }
}

here is the temperature code
float raw = 0;
float tempC = 0;
float tempF = 0;

void setup() {
  pinMode(A5, INPUT);
  pinMode(A1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
 raw = analogRead(A5) * 0.004882814;
 tempC = (raw - 0.5) * 100.0;
 tempF = (180.0/100.0)*tempC + 32.0;

 Serial.print("temp: ");
 Serial.println(tempF);
 delay(1000);
}

I coupled the "void loop" of all three and defined everything and ran the code to give a peculiar output. It does the temp and pressure reporting just fine but seems to constantly skip the frequency measurement. It seems to like doing the pressure and temperature measurement like 50 times then do an audio measurement which doesn't make sense as it should do it sequentially.
I TRIED:

adding a delay between the frequency measurement and the other two. This didn't work as now the audio measurement work, as it relies on the millis () function
adding the 3 components in 3 different functions and calling them sequentially. This results in the exact same stupid output.

Does anyone have an idea or solution?
Combined code:

int Vin = 5;
float Vout = 0;
float raw1 = 0;

int R1 = 770;

int R2old1 = 0;

int R2new1 = 0;

int R2avg1 = 0;

int pressurelog = 0;

const byte inputPin = 2;

boolean inputState = false;
boolean lastInputState = false;
long count = 0L;
int ledtest = 0L;

unsigned long previousCountMillis = millis();
const long countMillis = 500L;

void setInputState() {
  inputState = digitalRead(inputPin);
}

int crylog = 0;

float raw = 0;
float tempC = 0;
float tempF = 0;

int templog = 0;

void setup() {
  pinMode(inputPin, INPUT);       //Receive microphone data
  pinMode(A0, INPUT);             //Receive pressure voltage
  pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
  pinMode(A2, OUTPUT);            //Blue led, FREQUENCY/CRYING
  pinMode(A3, OUTPUT);            //Green led, TEMPERATURE
  pinMode(A4, OUTPUT);            //Red led, MAX WARNING
  Serial.begin(115200);
}

void loop() {
  Serial.println("HI");
  Cryometer();
  delay(2);
  Serial.println("YO");
  Pressure();
  Temperature();

  // WARNING SETUP
  if (pressurelog == 1 && templog == 1){
    digitalWrite(A4, HIGH);
  }
  else {
    digitalWrite(A4, LOW);
  }
}

void Pressure() {
  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2old1 = Vout*R1/(Vin-Vout);

  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2new1 = Vout*R1/(Vin-Vout);

  R2avg1 = (R2new1+R2old1)/2;

  Serial.print("Resistance: ");
  Serial.println(R2avg1);

  if (R2avg1 >= 1000){
    digitalWrite(A1, LOW);
    pressurelog = 0;
  }
  else if (R2avg1 <= 1000){
    digitalWrite(A1, HIGH);
    pressurelog = 1;
  }
}

void Cryometer(){
  // runs every time thru the loop
  setInputState();

  // count every transision HIGH<->LOW
  if (inputState != lastInputState) {
    count++;
    lastInputState = inputState;
  }

  if (millis() - previousCountMillis >= countMillis) {
    previousCountMillis += countMillis;

    // show Hz on Serial too if available
    Serial.print("Frequency: ");
    Serial.print(count);
    Serial.println(" Hz");
    ledtest = count;
    // reset to zero for the next half second's sample
    count = 0L;
  }
  if (ledtest >= 400 && ledtest <= 850){
    digitalWrite(A2, HIGH);
    crylog = 1;
  }
  else if (ledtest < 400 || ledtest > 850){
    digitalWrite(A2, LOW);
    crylog = 0;
  }
}

void Temperature() {
   raw = analogRead(A5) * 0.004882814;
   tempC = (raw - 0.5) * 100.0;
   tempF = (180.0/100.0)*tempC + 32.0;

   Serial.print("Temperature (F): ");
   Serial.println(tempF);
   Serial.println();

  if (tempF >= 75 && ledtest <= 50){
    digitalWrite(A3, HIGH);
    templog = 1;
  }
  else if (ledtest < 50 || ledtest > 75){
    digitalWrite(A3, LOW);
    templog = 0;
  }
}

So post your combined code. You also need to combine the setup() functions and make sure you don't have any pin conflicts (hardware) or naming conflicts with your variable names (software)

Sorry forgot the combined code, but to answer to rest of your post; I have done all of that and made sure it should run perfect, it seems to execute the frequency analysis perfectly but for some reason just doesn't want to do it with every cycle of doing pressure&temp.

Your approach is globally sound. However, the code that measures the
input frequency is very time sensitive. Thus, you have to make sure this
piece of code is never delayed by anything else. This means that
everything in your sketch should be fast and non-blocking.
I see a few instances of blocking behaviour you should get rid of: the
call to delay() and the serial prints. The first is particularly
useless, so just remove it. Printing to the serial port is fine as long
as you do not try to print too much. If you try to print at every loop
iteration, you end up filling the output buffer. From there on every
print becomes a blocking call: the serial library has to wait for the
port to send out the data, until there is enough room in the buffer for
what you want to send. The solution is to throttle down the output rate
by only printing once in a while. You have done this brilliantly in the
frequency-meter code:
if (millis() - previousCountMillis >= countMillis) {
  previousCountMillis += countMillis;
  Serial.print("Frequency: ");
  Serial.print(count);
  Serial.println(" Hz");
  // ...
}

Now you just have to apply the same technique to every instance of
Serial.print() and Serial.println(). Well, maybe the "HI" "YO" could
just be removed instead...
Once you remove these blocking behaviors from your sketch, it will
probably run fast enough for the frequency counting to perform
correctly. There is still something you may want to optimize though: the
computations in Pressure() are horribly inefficient, especially
considering that you have an 8-bit CPU with no hardware floating point
support. If you need to average, I suggest you average the analog
readings rather than computed resistances. Also note that computing the
voltage at the analog pin is completely useless:
void Pressure() {
    int raw = analogRead(A0) + analogRead(A0);
    float R = (float) R1 * raw / (2048 - raw);
    // ...
}

You may even replace float by long if you don't need a resolution
better than 1 Ω.


text:
USing arrays, binary data and bitRead
This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:
@code1=('10101010', '01010101');
$bit=$code1[0][0] (..through to..) code1[0][7]
$bit=$code1[1][0] ... code1[1][7]

So this is my Arduino code. Welcome to suggestions.
int pinArray[]={2,3,4,5,6,7,8,9};
int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
int count=0;
int split=0;    // Counter for the bit loop
int led;    // Store bit data
byte x;     // Used to store the binary data in code1

void setup(){
    for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
    ]
}

void loop(){
    for (count=0; count<6; count++){
    x=code1[count];
    ledDisplay(x);
    }
}

void ledDisplay(){
    for (split=7; split>=0; split--){
    led=bitRead(x,split);
        if (led == 1){
        digitalWrite(split+2,HIGH);
        }
        else{
        digitalWrite(split+2,LOW);
        }
    }
}

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value.  Does this need to be enclosed in brackets,ie (split+2) ?

Your indents are confusing. Press Ctrl+T

When I write my code in text editor, I use the tab key to indent code, so that the "for" opening / closing brackets etc are in the same column, (which seems to view correctly in my desktop browser - maybe perhaps incorrect on phone - so will use CRTL+t in future when posting. (I know CODE1 doesn't follow the same convention, but then I try to keep open/close on same  line so it doesn't 'run into' the next array, bearing in mind I will have 14 such arrays) This isn't meant to be 'nasty' to you as I do appreciate your taking the time to be helpful, just showing my personal 'naming convention'

Ctrl-T is just a quick way to get the code correctly indented in whatever is the IDE's default style. You don't have to use it though. You can use whatever indentation style you like if you handle it manually. Alternatively, you can configure the IDE for your favorite style. Just make sure to adopt one indent style and apply it consistently.

There are only two errors I can spot in your program:

A block of code should be delimited by curly braces:
for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT);
}  // ← ‘}’ instead of ‘]’

If a function expects to be passed arguments, these should be
declared as parameters in the function prototype:
void ledDisplay(byte x){  // ← mind the “byte x”
    // ...
}

Other than that, here a few suggestions to make the code look nicer, and
hopefully more maintainable:

indent consistently
use const to qualify constants
use named constants instead of magic numbers
keep variables local if possible
note that an int that is either 0 or 1 is equivalent to a boolean
use pinArray[] for accessing the pins

Applying those suggestions, I get the following:
const int PIN_COUNT = 8;
const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int CODE_COUNT = 6;
const int code1[CODE_COUNT] = {
    B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
};

void setup() {
    for (int count = 0; count < PIN_COUNT; count++) {
        pinMode(pinArray[count], OUTPUT);
    }
}

void loop() {
    for (int count = 0; count < CODE_COUNT; count++) {
        ledDisplay(code1[count]);
    }
}

void ledDisplay(byte x) {
    for (int split = 7; split >= 0; split--) {
        if (bitRead(x, split)) {
            digitalWrite(pinArray[split], HIGH);
        } else {
            digitalWrite(pinArray[split], LOW);
        }
    }
}

For once, I honestly wish I had the ability to upvote a reply. You have given me very constructive advice, rather than just a pointer here and there. (The "]" was just a typo,but thanks for pointing it out) I like too the boolean comment,which will save an extra few bytes. I shall now research "const" to see what that does exactly ...  Again, I honestly am very grateful for your indepth feedback

source: Stack Exchange

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

sort: votes


text:
Arduino controlled LCD 16x2 is very very dim
I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.
Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.
FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

Looks like you have no back light. Is the back light wired correctly?

I can't see much solder on the LCD on that photo. Are all of those wires soldered on?

I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).
It will light up when the backlight is correctly connected, which is impossible to tell from your photo.

It even looks like the “K” pin does not have a wire on it at all. Just a blob of solder filling the pad.

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


text:
Serial communication questions
I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:
1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?
2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?
Thank you

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

The Arduino has a 64 byte (software) buffer.  You will get the numbers in sequence up until that buffer overflows. Then it's not easy to predict what the results will be.
Probably something like:
121212121[...]2121212121212111111111111111

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

If there is nothing in the buffer the read function returns -1.  That can be mapped (IIRC) into ASCII (depending on your software) as ÿ so you would get:
1ÿ1ÿ1ÿ1ÿ1ÿ...

You should read my tutorial on reading serial on the Arduino.

thank you very much


text:
Arduino USB host + RS232
I'd like to get a word of advice regarding the subject. Basically there's a COM port based device which I need to connect to an Android tablet via USB. The tablet will be exchanging data packages with the COM device, but a) Arduino may need to do same transformation of the packages b) the tablet should not leverage OTG feature and shouldn't be a master itself.
So, my questions are
1) Which Arduino board is the best fit?
2) Is it an option to use Chinese boards for the sake of cost optimization?
3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?
Apology for this quite a noob question but that's exactly who I am for Arduino platform. Appreciate any answers.

No Arduino implements a USB host. That would require a more or less complete OS to work. And it's not quite clear how are parts of your project connected together.

@DmitryGrigoryev I believe Arduino Duo must support USB Host mode, at least I saw that in various blogs and forums on the Internet : https://forum.arduino.cc/index.php?topic=548469.0 So, can you explain what do you mean, please?

True. Yet you have accepted an answer suggesting a 32U4, which doesn't have the host mode, so I still fail to understand what you're trying to do. Did you decide to use OTG, or use a Duo to connect your COM device and Android device together? Or is Arduino itself the COM based device you're talking about?

@DmitryGrigoryev sorry for being not clear. Given is a) COM device, b) Android tablet. To be solved is how to connect them allowing the tablet to send/receive data to/from the COM device, but keeping the tablet charged (so OTG is not an option as it would make it into master, thus giving it's charge away). Also, some additional transformation may be required to apply to data flowing between the devices.

1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.
Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is not used by the USB communication.
Then you need to convert the UART into RS232 using (for example) a MAX232 board.

yeah I've got full control over Android app and basically marrying it together with a bord won't be a problem.

I'm a bit puzzled now. Cuz ATMega32U4 is used in Arduino Micro and Leonardo which I believed are not able to be host devices. By reading docs I was leaning to Arduino Due, cuz the documentation for USBHost class specifically says the class is compatible with Due model only.

@Ivan You want the Android device to be the host.

Not exactly, I'd like it to be slave and a bord act as a host.

@Ivan Then you've got a long job in front of you. There's no (AFAIK) API for that kind of thing in Android. You can do file transfers, network sharing, etc, but not serial communication.  For that you need the Android device to be the host.

@Ivan Have you considered connecting to Android through Bluetooth instead?

Hmm, so basically you saying that I won't be able to use UsbDevice, UsbInterface, UsbEndpoint classes from Android SDK in case if the tablet is connected as slave and won't be possible to respond to Arduino bord when that requests a data?

Unfortunately, Bluetooth is not an option at all.

@Ivan The only resources you are likely to find are for using Android as the host. It's the normal option, it's the sensible option, and the only other mention I can find of someone wanting to do this mentions modifying the Android installation and compiling your own kernel. So.... no.

Cool, thanks a lot for helping. Will try to think something.

Sorry for bothering you, didn't do a deep dive into the subject but seems Android allows to connect USB accessories https://source.android.com/devices/accessories/custom#connecting-over-usb and I found an example (which I'm not sure is functional) - https://github.com/Geotab/android-external-device-example/blob/master/app/src/main/java/com/geotab/AOA/AccessoryControl.java So, will try to play with it.

Backing to the original question :) Do you think Arduino Due is the best board to experiment with this?

@Ivan That is with the Android being the master. An accessory is a device.

And no, I'd go for a Pro Micro or a Leonardo.

Hmm, that doc says "Due to the low power output of Android devices, AOA requires the accessory to act as a USB host, meaning the connecting accessory must power the bus.".

@Ivan AOA is a strange beast. It's not normal USB communication. "Host" mode is only from a power perspective in that system - the android device still has to connect to the accessory rather than the accessory connect to the phone. Also there is no AOA support in Arduino

right I see and seems it's exactly what I need. Basically the main goal is not to exhaust the tablet's battery. If AOA allows do software side of things on tablet but power still supplied externally, I'm okay with that. Will try to play with the boards you mentioned and maybe Arduino Due too. Thanks a lot for the help!

Damn, just noticed the last phrase "Also there is no AOA support in Arduino" :(

There's always the possibility that someone somewhere has written an AOA library plugin for the Arduino USB stack, but I doubt it. You may be working in Atmel Studio...

AOA is supported in Arduino (or was) but it is called ADK. https://www.arduino.cc/en/Guide/ArduinoADK. The last time anyone was excited about this was 2012. The USB Host Shield Library 2.0 has references to ADK as does the Due USB host library https://github.com/arduino-libraries/USBHost/tree/master/examples/ADKTerminalTest. Whether Arduino ADK still works, I do not know. BLE or WiFi are better options to communicate with an Android device.


text:
Public IP for Arduino with Ethernet shield and Arduino Uno
I'm new Arduino and I would like you to help me. I would like to have a public IP so that anyone can get access to it, not only from domestic domain. What could I do?. I'm using Arduino Uno, Arduino Ethernet Shield w5500 and a RTC.
My code:

#include <SPI.h>
#include <Ethernet.h>
#include "RTClib.h"
#include <EEPROM.h>

#define time 1
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
//----------------------------------------------------------------------------------------------------------------
 int i=0;
String hora="";
String readString;

RTC_DS1307 RTC;

void setup() {

  pinMode(2,OUTPUT);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
RTC.begin(); // Inicia la comunicaci¢n con el RTC

RTC.adjust(DateTime(__DATE__, __TIME__)); // Establece la fecha y hora (Comentar una vez establecida la hora)

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Sistemas Digitales");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield no se encontro.  No se puede correr el programa sin el hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("El cable Ethernet no esta onectado.");
  }

  // start the server
  server.begin();
  Serial.print("El servidor esta en: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients

delay(1000);
DateTime now = RTC.now(); // Obtiene la fecha y hora del RTC

  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
//---------------------------------------------------------------------------------------------------------------------------------
        char c = client.read();

if(i==11 || i==12 || i==16 || i==17){
 if(i==16){
  hora +=':';
 }
  hora += c;
}

        if(readString.length()< 100){
          readString += c;
        }
        i++;
        //Este escribe el texto en pantalla letra por letra
        Serial.write(c);

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n') {
            Serial.println("acabo lectura");

            Serial.println(hora);
             Serial.println(readString);

client.println("HTTP/1.1 200 OK"); // Enviar una respuesta tipica
             client.println("Content-Type: text/html");
             client.println("Connection: close");
             client.println("Refresh: 10");
           client.println();
           client.println("<!DOCTYPE HTML>");
          client.println(" ");
          client.println("");
          client.println("<meta charset='UTF-8'><title>Sistemas Digitales</title>");
          client.println("");
          client.println("
");
client.print("
Fecha y hora del servidor:");
client.print(now.day(), DEC);
client.print('/');
client.print(now.month(), DEC);
client.print('/');
client.print(now.year(), DEC);
client.print(' ');
client.print(' ');
int horini;
horini=now.hour();
String horartc = "0";
if(horini<10){
  horartc += horini;
}else{
horartc= String(horini);
}
client.print(horartc);
client.print(':');
int minuto;
minuto=now.minute();
String mainut;
if(minuto<10){
  mainut='0'+ String(minuto);
}else{
mainut= String(minuto);
}
client.print(mainut);
client.println("
");
client.println("<form method='get'>");
client.println("

¿A que horas le quiere dar de comer al chucho?

");
client.println("<input type='time' name='hora'>");
client.println("

que dias lo quiere alimentar?

");
//dias en checkbox
//client.println("<input type='checkbox' name='cbox1' value='?LunesOn'>Lunes
<input type='checkbox' name='cbox2' value='?MartesOn'>Martes
<input type='checkbox' name='cbox3' value='?MiercolesOn'>Miercoles
<input type='checkbox' name='cbox4' value='?JuevesOn'>Jueves
<input type='checkbox' name='cbox5' value='?ViernesOn'>Viernes
<input type='checkbox' name='cbox6' value='?SabadoOn'>Sabado
<input type='checkbox' name='cbox7' value='?DomingoOn'>Domingo
");
client.println("<input type='submit' value='Enviar' id='enviar'> ");
client.println("</form>");
if (readString.length() >0) {
Serial.println("hora del rtc");
String horiux = horartc +':'+ mainut;
Serial.println(horiux);
EEPROM.put(0, hora);

if(EEPROM.get( 0, hora ) == horiux){
digitalWrite(2, HIGH);
delay(10000);
digitalWrite(2, LOW);
delay(60000);
}
readString="";
i=0;
hora="";

          client.println("");
          client.println("");

          delay(1);
    // close the connection:
    client.stop();

        }

      }
    }

  }

  }
}

There it is  a part of the code:
IPAddress ip(192, 168, 0, 177);

I would like to make that IPto be public domain so you can get access anywhere instead of neededing to be in the same ethernet connection.
Any help would be wonderful, thanks for your time.

There is a discussion about the same topic in Arduino's Forum here. The most valuable comment was this:

To get an internet static IP address, contact your ISP. You will probably have to pay extra for that. Most people use a dynamic IP service such as www.noip.com to forward traffic to your current internet IP address. You put your dynamic ip address url in your web page so the browser request get routed properly.

I assume (by the address) that you want to do something like this:

The NAT device might have a port forwarding feature.
  You can use that.
  Assume the WAN ip is 198.51.100.1 and the server's ip is 10.1.1.1, the server is listening on port 80.
  So the port forwarding configuration will be something like :
  198.51.100.1 80 ---> 10.1.1.1 80
  From the outside you connect to the public IP - 198.51.100.1 80
  When the NAT device receives packet, it forwards it to 10.1.1.1.
  more info here

This is direct copy from source. So in your case WAN IP is the static IP (or another else) that is visible about you outside your network and the private one is that 192.168.0.177 which you used. Like stated in first yellow box, you can use dynamic ip service, too.

Thanks you so much!


text:
Using use the STM32F103C8T6 board with the Arduino
last two days I am trying to program my blue pill with Arduino IDE, helplessly...
Actually, I managed to install simple blink program, but after that, all other attempts ended up with:

Failed to init device.
  stm32flash Arduino_STM32_0.9
http://github.com/rogerclarkmelbourne/arduino_stm32
Using Parser : Raw BINARY
  Interface serial_posix: 115200 8E1
An error occurred while uploading the sketch

I crawled internet but no help so far... I followed simply tutorial:
https://www.youtube.com/watch?v=K-jYSysmw9w just as this https://github.com/rogerclarkmelbourne/Arduino_STM32/wiki/Installation, and as I said, first time was problem but finally successfully upload it. However, after that when I wanted some real working program to install failed.
All mappings ftdi -> stm32 are correct, jumper booto is set to 1 mode, for programming, I have required files within /etc/udev/rules.d, stm32 library folder in sketch folder, and yet the error above is happening for a last 20 hours... (I am using Ubuntu 16.04)
Please, if anyone point me what is wrong (why first time worked and second wont), or to give me precise steps to perform in order to work, I appreciate.
EDIT: Blinking program works just fine when I move jumper to 0, and supply power via usb.

Rewind to where you had some success. Do you still have that same success?

I did... Clean up and delete everything, and started from scratch. But nothing, really frustrating... FTDI red led is on, stm32 red led is on, but when I do upload, the same error, over and over again..
stm32flash Arduino_STM32_0.9
http://github.com/rogerclarkmelbourne/arduino_stm32
Using Parser : Raw BINARY
Interface serial_posix: 115200 8E1
Failed to init device.

thanx for help... It turns out that I have been sold crappy additional pins to plugin into breadboard. Even STM32 blink, turns out that one of the tx/rx has no contact with board (probably for microns).
However, firmed them altogether without breadboard, and it works...I spent 15 hours with this issue...

I don't think additional pins are really crappy. It supposed to be soldered on the board.


text:
Water pump controlled by soil moisture sensor
I'm just learning to code in Arduino.
The purpose is that first the sensor measures the moist level (I mapped the reading values from 0 to 100). If the value is less than threshold 70, then it will turn on a water pump. As soon as the value goes beyond 70, the pump stops pumping water.
The problem is that even when the value is less than 70, the pump doesn't work.
I tried replacing the pump with a LED, it turns on a the right moment. I tested the pump itself, and it also works perfectly.

//for mapping values
int mostMoist = 100;
int leastMoist = 600;
int percent;

//direct value from sensor
int raw;

//threshold for minimum percentage to turn on pump
const int threshold = 70;

//initial state of water pump
bool dosomething = false;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  //if it's not pumping water:
  while (dosomething == false){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  Serial.println(percent);
  Serial.println("dosomething is set to false");

  //check if percentage moist is less than threshold. if so, set dosomething true, orelse, loop dosomething false
  if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
  delay(2);
  }

  //if it's pumping water:
  while (dosomething==true){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  //turn on pump
  digitalWrite(13,HIGH);
  Serial.println("dosomething is set to true");
  //check if percent moist is less than threshold value, if so, loop dosomething true, orelse, set dosomething false
    if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
    Serial.println(percent);
  delay(2);
  }

}

please do not post pictures of text ... post the text itself

I don't see a second power-supply in your photo. If you're trying to run the pump directly from an Arduino pin, it is highly likely that the pump needs way more current than the pin can supply.
It may be possible to power the motor from the USB but 1) the Uno board doesn't make that readily available, 2) it puts your PC at some risk (of back-EMF or of over-drawing the port's capability. But the ideal would be a separate power supply (don't forget to connect that supply's ground to the Uno's ground).
Also, if you tested the pump while dry it may have been able to run, yet with water in it, have been unable pull enough starting current to get going.

To control the pump you will need either a transistor or a relay board to handle the current. The arduinos pins can only drive 20 mA which is not enough for most pumps, even very small ones.
If the pump can run on 5 V and with <400 mA a transistor (FET) may suffice an power could come from VCC or so. Otherwise an extra supply with a relay is one simple solution.
You could start here for instance.
Look for tutorials, there are so many out there to be found with search engine, it's worth :)


text:
Stuck with bad sketch
How can I get my programmer board/windows computer to recognize my board again. I am using the esp32 cam and have put two boards in a state where I am unable to flash them anymore. here is the error:
serial.serialutil.SerialException: could not open port 'COM5'WindowsError(2,'The system cannot find the file specified.')Failed to execute script esptoolthe selected serial port Failed to execute script esptool

I tried reinstalling the drivers and understand that the com port is a separate chip
https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e
Here is the sketch I used. I uploaded it using the dev module board setting as well as with 80mhz and 112500 speed. I uploaded with 3v and then provided 5v to the board to run the sketch. The sketch runs but prints out gibberish.
Edit:
Here is a schematic of the board
https://github.com/SeeedDocument/forum_doc/raw/master/reg/ESP32_CAM_V1.6.pdf

You can't "put them in a state" where the COM port can't be found. The COM port is a completely separate chip. Check your USB cable. Reinstall the drivers.

And check if the boards still have COM5. Sometimes the numbers change

thanks fellas for the quick replies. I tried reinstalling the drivers for the USB device in question. holding down the reset button before doing so. However, while the com port is still there, it says the drivers are up to date.

Is there a way to reinstall the drivers other than uninstalling > unplugging the usb > plugging the usb back in > and hitting update drivers and browsing to the file where the drivers are?

@majenko I tried reinstalling the drivers before I came here. I just figured there was a quick fix to fixing a broken sketch. I wrote my OP hastily and can update it if needed

The sketch can only affect reflashing on boards that provide a native USB interface, like the Micro and Leonardo. All others that use a USB bridge chip of some form are completely independent of the sketch.

This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -> Port menu -- or, in other words, go there and select the port that is listed there while the board is plugged in.
Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).

thank you for this throrough reply. The com5 port (the one i have always used) shows up when i plug in the programmer board without the esp32 cam board attached. However if I attach the esp32 cam board to the programmer (the same way i had it wired all times before) the com port disappears and the USB is not recognized by windows. Could it be that the programmer is stuck trying to program and needs to be reset somehow?

Hi, what do you think is going on?

"the programmer is stuck trying to program" - if you power cycle (i.e. disconnect from power) the "programmer" has no memory of what it was doing before. At a guess, you've "fried" and probably permanently destroyed something

@DavidGraff This sounds more like that the cam board produces a short, rendering the programmer inoperable. Either you have created a solder bridge or something like that (e.g. between Vcc and GND) on the cam board, or your esp32 is fried (did it come into contact with 5V?) and shorts internally. (On a completely different note: your name sounds familiar. Does TUDO tell you anything?)

@orithena no that doesnt ring a bell. So it is likely I fired both boards when uploading the sketch and then providing 5v via the 5v input on the esp32 cam board? I have tried all options to reset the board.

I cannot answer that without seeing the schematics (can't find them online), but it seems unlikely that applying 5V to the 5V pin fries the chip, as the board seems to have a voltage regulator onboard. It's more likely that you fried the chip by applying 5V to any input/output pin (a.k.a. GPIO pin), e.g. by using a programmer or external component that outputs a 5V signal level without inserting a level shifter into the signal line. Have you been able to flash the chip exactly once? Then I'd say your programmer outputs a signal level of 5V and the esp32 fried during flashing.

That last hunch comes from: a chip does not fry immediately when exposed to a slightly higher voltage. It needs some time to get hot enough to fry. So the initial handshake to flash it worked, but the actual flashing process after that is: just shove the bytes over the line. So when the chip fries during programming, the next handshake in order to flash it will not work anymore.

thank you for the replies. I don't have the two boards with me to check today but maybe I will later today... I have fried two esp32 cam boards it seems. Both of which were fried when I uploaded a sketch and then applied 5v to the 5v pin. I provided 3v each time while uploading the sketch, however. Could changing any of the settings in the configuration cause the boards not to like the 5v?

I added the sketch I used and a schematic to the OP @orithena

@DavidGraff Interesting schematics. There is an AMS1117 low-dropout voltage regulator to pull the 5V input voltage down to 3.3V. But: did you change anything on the "solder jumpers" marked "5V" and "3V3"? (follow the white line from VCC). If they are both connected, you're effectively bridging the voltage regulator out of the schematics, which means: if they're both connected and you apply 5V to the 5V pin, the chip will be driven with 5V instead of 3.3V, which will fry it (see circuit around U2 and P1 in the schematics; R1 and R2 are the solder jumpers, only one of them may be closed).

Let us continue this discussion in chat.


text:
Arduino and NodeMCU problem with wifi conecction
Hello guys I am beginner with micro controllers but I am trying to make a simple IoT with Arduino and NodeMCU as WiFi. I was using this tutorial and code https://www.electronicshub.org/wifi-controlled-led-using-esp8266-and-arduino/.
When I upload the code for the first time everything worked perfectly but every other time when I upload the same code my program is stuck in a loop.
Program is in infinite while loop while(!esp8266.find("OK")) because as far as i understand it didnt receive the OK status from ESP.
But in fact esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG); prints OK in my console so it means that it should work but it doesnt...
Do you guys have any idea whats the reason?
Code looks as follows;
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //Pin 2 & 3 of Arduino as RX and TX. Connect TX and RX of ESP8266 respectively.
#define DEBUG true
#define led_pin 11 //LED is connected to Pin 11 of Arduino

void setup()
  {
    pinMode(led_pin, OUTPUT);
    digitalWrite(led_pin, LOW);
    Serial.begin(9600);
    esp8266.begin(115200); //Baud rate for communicating with ESP8266. Your's might be different.
    esp8266Serial("AT+RST\r\n", 5000, DEBUG); // Reset the ESP8266
    esp8266Serial("AT+CWMODE=1\r\n", 5000, DEBUG); //Set station mode Operation
    esp8266Serial("AT+CWJAP=\"SSID\",\"Password\"\r\n", 5000, DEBUG);//Enter your WiFi network's SSID and Password.

    while(!esp8266.find("OK"))
    {
      }
    esp8266Serial("AT+CIFSR\r\n", 5000, DEBUG);//You will get the IP Address of the ESP8266 from this command.
    esp8266Serial("AT+CIPMUX=1\r\n", 5000, DEBUG);
    esp8266Serial("AT+CIPSERVER=1,80\r\n", 5000, DEBUG);
  }

void loop()
  {
    if (esp8266.available())
      {
        if (esp8266.find("+IPD,"))
          {
            String msg;
            esp8266.find("?");
            msg = esp8266.readStringUntil(' ');
            String command1 = msg.substring(0, 3);
            String command2 = msg.substring(4);

            if (DEBUG)
              {
                Serial.println(command1);//Must print "led"
                Serial.println(command2);//Must print "ON" or "OFF"
              }
            delay(100);

              if (command2 == "ON")
                    {
                      digitalWrite(led_pin, HIGH);
                    }
                   else
                     {
                       digitalWrite(led_pin, LOW);
                     }
          }
      }
  }

String esp8266Serial(String command, const int timeout, boolean debug)
  {
    String response = "";
    esp8266.print(command);
    long int time = millis();
    while ( (time + timeout) > millis())
      {
        while (esp8266.available())
          {
            char c = esp8266.read();
            response += c;
          }
      }
    if (debug)
      {
        Serial.print(response);
      }
    return response;
  }

use the WiFiEsp library

why do you need to upload the same code more than once?

@Juraj thanks for your answer, I will read about it.

@jsotola thanks for your answer, well i made some changes to my code and uploaded it but it stuck in infinite loop so i revert changes and upload original code which worked before but now it is also stuck in the same loop. It never finds "OK".

Your esp8266Serial function already read the response including the "OK" from the input so find() can't read it again


text:
How to wire a hall effect sensor to arduino?
it's a UGN3503 hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.
as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.
what i want is just simply read the data from sensor and if the number is above or under defined value do something.
do i need a pull up resistor and/or capacitor?
what's the right and standard way to wire a UGN3503 to arduino?

The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.
If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.
A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).
The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.


text:
Combining code for multiple sensors in one program (Arduino)
I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.
Here are the sketches:
Gas sensor MQ2 code :
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);

This is the DHT11 code :
#include <SimpleDHT.h>

int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
    // start working...
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Data");
}

void loop() {

  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared.  Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
  Serial.println("Starting");
}

void loop() {
  int analogSensor = analogRead(smokeA0);
  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop().  This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      Serial.begin(9600);
      Serial.println("Starting");
    }

void loop1(){
   int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

void loop2(){
  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

void loop() {
  loop1();
  loop2();
}


text:
LCD on top of SD datalogger flickers help!
I have a problem with my 16,2 with buttons lcd shield.(LCD Keypad Shield). It is connected on top of an SD dataloger. I came to the conclusion that every time the sd shield logs data and completes the loop it switches off and on,flickering the lcd, and moves on with the loop. Is there any way to stop the flickering while the sd shield logs??

Which LCD is that? I think the problem is that both boards use some of the same pins, creating a bit of conflict.

It says that it is a 1602 keypad lcd shield. I bought it from here: https://www.cableworks.gr/ilektronika/arduino-and-microcontrollers/displays/lcd/lcd-keypad-shield-with-16x2-for-arduino/

If it is this one then pin D10 is the backlight control. D10 is often used as a chip select pin, and is most likely the chip select for your SD card.  The only cure is physical modification of the LCD shield to remove pin 10 and connect it elsewhere (or leave it disconnected for always on by the looks of things).

I connected the lcd externally through a breadboard avoiding the d10 and it work like a charm!!! Thanks guys!

Some of these boards have solder-jumpers on the back, to change some of the pins. In your case, I'd snip the D10 header pin on the LCD shield. And then add a small wire from one of the free pins to (the now emasculated) D10 pin


text:
How to modify a created byte?
I have created a byte for 16x2 LCD. It is basically a custom character which I will have to change later.

byte char[8]{
 B10000,
 B01000,
 B00100,
 B00010,
 B00001,
 B11000,
 B11100
};

I want to edit the third number from fourth row. So, the fourth row will become B00110 from B00010. Is this possible? Are there any alternatives for this?

Well first of all you are trying to name the variable char? which is already a keyword for the variable type of char.   But you can access it by the index of the array. Also not sure if you intended to make the array 8 bytes in length, and then only use 7, but thats what you had done in your example
//define it all at once
// byte byteArray[8] = {B10000,B01000,B00100,B00010,B00001,B11000,B11100};
//or by index
byte byteArray[8];
byteArray[0]=B10000;
byteArray[1]=B01000;
byteArray[2]=B00100;
byteArray[3]=B00010;
byteArray[4]=B00001;
byteArray[5]=B11000;
byteArray[6]=B11100;

//if you need to change one in the code elsewhere
byteArray[3]=B00110;
//or
byteArray[3]=6;
}

In the second last line, why did you set the byteArray[3] equal to 6? Why not 3 because we want to change the third element?

B00110 = B110 = 1 (first 1) * 2^2 + 1 (second 1) * 2^1 + 0 (last 0) * 2^0 = 1 * 4 + 1 * 2 + 0 * 1 = 6

@MichelKeijzers Well, i didn't get it. What is the purpose of it? Is there simpler way? I just don't want to involve other elements.

E.g. in the normal (10 or decimal system) number 76 = 7 * 10^1 + 6 * 10^0 = 7 * 10 + 6 * 1 = 70 + 6 = 76. In the binary (2 system) number 110 = 1 * 2^2 + 1 * 2^1 + 0 * 2^0 = 1 * 4 + 1 * 2 + 1 * 0 = 4 + 2 + 0 = 6.

Was just showing that it could be set using decimal rather then binary  x=B00110(Binary), x=6(Dec),x=0x06(Hex) Are all equal. It doesn't really pertain to your question, so I should have just left it out to not be confusing.

You can use the following array initialization:
In the setup I shows how to set a bit. For this, the bit operator or (|) is used. To reset a bit, you can use &. You can set/reset multiple bits this way.
Also you can use 1 << 2 which means 1 (most right bit) shifted left two places (thus B100).
Btw, it is common practice to initialize all values.
byte lcd[8] =
{
  B10000,
  B01000,
  B00100,
  B00010,
  B00001,
  B11000,
  B11100,
  B00000  // Also initialize last element
};

void setup()
{
   lcd[3] |= B100; // Set 4th row (element 3), 3th bit (from the right)
   lcd[3] |= 1 << 2; // Alternative
}

void loop()
{
}

Explanation about the or arithmetics: OR means: if at least one bit is 1, the result is 1, otherwise 0.
Truth table:
A | B | A or B
--+---+-------
0 | 0 |   0
0 | 1 |   1
1 | 0 |   1
1 | 1 |   1

For your example it means:
Original value of lcd[3]: B00010
Or mask (in setup):       B00100
                          ------ OR
Result                    B00110

Why have we done this? lcd[3] |= B100; .Where did the other elements go?

lcd[3] will only change the 3th element, the other elements will remain equal. With the or (|) you can set a bit, all 0-values in an or 'mask' will remain unchanged.

Can I do directly like lcd[3][3] = B1; where first 3 is the 4th row and second is the 3rd element?

No you cannot use lcd[3][3] because lcd[3] is one element  (a byte) and not an array.


text:
Addresible led delay for 24 hours with arduino uno
Im working on a project with my addresible led strip and arduino uno
I need 3 leds on the strip to light for 24 hours and then the next 3 leds on the strip should light up for 24 hours and so on.
Can somone help me with the code

Can you show us the code you've written so far?

Im new to arduino if someone can just start me off with the code it will be a big help
Thanks

I know how to turn on and off.

@user57550 - Start with the BlinkWithoutDelay example that comes with the IDE. Once you have that sketch turning the LED on and off every 24 hours, edit your question and add the sketch.

@VE7JRO thanks for your jelp

turn on 3 .. wait 5 seconds ... turn on next 3 ... wait 5 seconds ... repeat .... when you get that going, increase the wait time

Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named How to Ask. You might also want to learn about minimal reproducible example and how to format your question.


text:
Why does my TFT keep turning white after moments?
Alright, seems there is something wrong I am doing that I don't understand. Before I start explaining, my question is different than this white screen question.
First of all my TFT ST7735 is working very well with the below code, let's name it, code part 1:
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <SD.h>

  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8

#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
float p = 3.1415926;
int Variable1;
int ledState = HIGH;
//  Variables
int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
int myBPM = 0;
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// constants won't change:
const long interval = 1000;

unsigned long previousMillis = 0;
static uint32_t tsLastReport = 0;

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

  Serial.print(F("Hello! ST77xx TFT Test"));

#ifdef ADAFRUIT_HALLOWING

  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
#else

  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

#endif

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  Serial.println("done");
  delay(1000);

}

void loop() {

  testdrawtext(" BPM: ", ST77XX_WHITE);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(2);

  int sensorValue = analogRead(A0);

  tft.print(sensorValue);
    delay(300);
  tft.fillScreen(ST77XX_BLACK);

}

void testdrawtext(char *text, uint16_t color) {
   tft.setCursor(0, 0);
 tft.fillScreen(ST77XX_BLACK);

  tft.setCursor(0, 0);
  //  tft.setCursor(10, 40);
  tft.setTextSize(2);
 // tft.setTextColor(color);
  tft.setTextColor(ST7735_YELLOW);
  tft.setTextWrap(true);
  tft.print(text);
   delay(200);
}

Here is the video for Part 1 running very good with a random analog number.
Secondly, I have a simple Heart Beat circuit and it is working very well when I apply this getting_BPM_to_Monitor code into it. I don't have a photo for it but trust me it is working good so please, when I do attach the schematic don't focus too much on the hardware side, it might not be very perfectly stable but it is working fine for me.
Now, is the magic when I combine the Heart Beat which is getting_BPM_to_Monitor & TFT ST7735 circuit things don't seem alright and I think a code with a video is better explaining the issue than me. The below code, let's name it, code part 2:
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <SD.h>

  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
float p = 3.1415926;
int Variable1;
int ledState = HIGH;
//  Variables
int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
int myBPM = 0;
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

static uint32_t tsLastReport = 0;

void setup(void) {
  Serial.begin(9600);
 // .  PulseWire = 3;
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  pulseSensor.begin();

  Serial.print(F("Hello! ST77xx TFT Test"));

#ifdef ADAFRUIT_HALLOWING

  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
#else
  // Use this initializer if using a 1.8" TFT screen:
 // tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 180x60 TFT:
  //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240
#endif

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  Serial.println("done");
  delay(1000);

  Variable1 = 90;

}

void loop() {

  testdrawtext(" BPM: ", ST77XX_WHITE);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(3);

  myBPM = pulseSensor.getBeatsPerMinute();
if (pulseSensor.sawStartOfBeat()) {
}

  tft.print(myBPM);
      delay(300);
  tft.fillScreen(ST77XX_BLACK);

}

void testdrawtext(char *text, uint16_t color) {
   tft.setCursor(0, 0);
 tft.fillScreen(ST77XX_BLACK);

  tft.setCursor(0, 0);
  //  tft.setCursor(10, 40);
  tft.setTextSize(2);
 // tft.setTextColor(color);
  tft.setTextColor(ST7735_YELLOW);
  tft.setTextWrap(true);
  tft.print(text);
   delay(200);
}

Here is the video or this video for Part 2
Lastly, I provided the schematic for more reasoning opinion and it was provided by Easyeda.com and you have to have an account to view my schematic
Things I have tried...

I have modified TFT pins since Gtting_BPM_to_Monitor uses Timer1 & Timer2
I have added/remove a lot of delays
I have insertednoInterrupts(); and interrupts();

Edit 1 :
Here is a PNG of the schematic if and hopefully, it is clear enough.

Make it easy for people to help you. Copy your schematic somewhere people can see it without having to create an account. I for one have too many accounts, I do not want to be creating more accounts and risk getting more spam from overseas companies.

Good, I added PNG file.


text:
Connecting Function Generator to Arduino
I want to send a function generator's signal to an Arduino UNO Analog pin. Can I use an Oscilloscope probe connected to the function generator output BNC, set to 1x to connect to the Arduino headers using jumper wires? I did read through the manuals of the function generator, but couldn't find a solution.
The function generator available is Tenma 72-14110.

Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).
But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.

Thanks, I read that the probes are used for 'probe compensation' in oscilloscopes and that they have resistors in them - hence was not sure if I could use them.

As a complement to chrisl's answer, I would recommend putting a
10 kΩ series resistor in series between the function generator and
the Arduino.
This is just for safety: if the function generator accidentally goes out
of the  Arduino's safe voltage range, the resistor will limit the
current that flows through the input pin's protection diodes. These
diodes are rated to only 1 mA, and a 10 kΩ resistor should
greatly expand the range of voltages you can send without frying them.


text:
How to stringtok this long string?
I have a string,
"id,port,password,ssid,delay,flag,class,category"
Please tell me how can stringtok this and find out the "flag" value(0 or 1)?
Here is what I tried:
void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}

I would remove the { and } in char input[] = {"id,port,password,ssid,delay,flag"};

Even with the (useless) braces Juraj suggest removing, your code works as expected. Please, be more specific about what your actual problem is.

how 'flag' substring separately taken ? what modification that i want to made in program?

based on position? 6th item?

For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop.  You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.
void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);

    char *id = strtok(input, ",");
    char *port = strtok(NULL, ",");
    char *password = strtok(NULL, ",");
    char *ssid = strtok(NULL, ",");
    char *delay = strtok(NULL, ",");
    char *flag = strtok(NULL, ",");
    char *class = strtok(NULL, ",");
    char *category = strtok(NULL, ",");
    if (category != NULL) { // Everything up to and including category worked
        Serial.print("Flag: ");
        Serial.println(flag);
    }
}

void loop(){}

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use strsep() instead of strtok() as I detail in my tutorial on splitting strings in C.


text:
how can i send get and post request from esp01 using arduino uno
I am using an esp8266 01 module with the Arduino Uno to establish a communication between the Arduino and my web site. I actually don't know how to send Rest HTTP requests from the Arduino to get data from my web site. I have done research but all I got is codes using nodemcu so I was wondering will the code of nodeMCU work fine on the Arduino using ESP01 and if not then how can I send get and post request from the Arduino using esp01
this the code that I found
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "SERVER NAME";
const char* password = "SERVER PASSWORD";

void setup()
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.println("Connecting...");
  }
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http; //Object of class HTTPClient
    http.begin("http://jsonplaceholder.typicode.com/users/1");
    int httpCode = http.GET();

    if (httpCode > 0)
    {
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());

      int id = root["id"];
      const char* name = root["name"];
      const char* username = root["username"];
      const char* email = root["email"];

      Serial.print("Name:");
      Serial.println(name);
      Serial.print("Username:");
      Serial.println(username);
      Serial.print("Email:");
      Serial.println(email);
    }
    http.end(); //Close connection
  }
  delay(60000);
}

use the WiFiEsp library

can you tell me what this library can offer to me

it works on Arduino over esp8266 AT commands with standard Arduino networking API used in the sketch you added to the question

can you tell me how can I use it

wire the esp-01 to the same way as sketches witch use the AT commands. install the WiFiEsp library in Library Manager and see the examples

thank you very much

i tried what you sid but when i run the code i code a lot of ??????? what does that means

it could be wrong baud rate. does the baud rate in sketch match the baud rate of the AT firmware? you should use 9600 baud

i changed it to 9600 but now i got [WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Warning: Unsupported firmware

send AT+UART_DEF=9600,8,1,0,0 to AT firmware. it will change the default baud rate

what AT firmware version do you have? it reports unsupported for the latest AT firmware. you can ignore it then

Let us continue this discussion in chat.


text:
ESP8266 Webserver not reachable after 2 minutes from reset
I have a Keyes Espressif ESP8266 NodeMCU, I have two LEDs that I want to control which are connected to the ESP. When I open the webpage http://10.0.0.5/5 after uploading the sketch it works fine. If I don't open and close the website before ~ 02:30[mm:ss] the server becomes unreachable even if I close the existing connection and open a new connection in a new tab the same error yields: ERR_CONNECTION_TIMED_OUT
If I don't open a web page before ~ 02:30[mm:ss] I also receive error ERR_CONNECTION_TIMED_OUT
The web server is only made available when I hard reset the board then the same rules apply as above.
ESP.getFullVersion() outputs:
SDK:2.2.1(cfd48f3)/Core:2.5.1=20501000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

Question:
How can I make the web server accessible constantly?
With the help of @Juraj I tried changing to SDK V3 which made no difference I also tried:

All lwip variants

My Code:

// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char* ssid     = "DO_231455";
const char* password = "0828842107";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 16;
const int output4 = 4;

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

  // Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);

  Serial.print(ESP.getFullVersion());
  //WiFi.disconnect() ;
  //WiFi.persistent(false);
  //WiFi.setSleepMode(WIFI_NONE_SLEEP);
  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
ESP8266 Web Server
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
GPIO 5 - State " + output5State + "
");
            // If the output5State is off, it displays the ON button
            if (output5State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("
GPIO 4 - State " + output4State + "
");
            // If the output4State is off, it displays the ON button
            if (output4State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }
            client.println("");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

Worth noting (while debugging):
The new client disconnects.

if a client is returned from server, then the problem is in sketch

What resources would you suggest I look at to learn how to fix this problem?

does it help if you restart the WiFi router/AP?

No effect, the site still drops if not requested from my W8.1 Chrome browser within 2 minutes of resetting or uploading.

does it stop working after two minutes - even if you do not make any requests to it until 2 minutes has passed? Or, does it stop after a certain number of requests that happen to take about 2 minutes to execute?? The point is, does it fail after a certain number of requests, or does it fail after a period of operation - irrespective of the workload???

I tested this by resetting then opening and closing a connection in my browser every minute  - I could do this for 30 minutes and continue to do it thereafter but if I don't make a new connection within ~2 minutes 35 seconds the server times out. It's as if the ESP goes into sleep mode after no requests.

it prints "New client" so it doesn't sleep

Yes, the ESP times out only if a new request not made. I'm trying to find a method to prevent webserver from timing out.

it doesn't time out. it returns a client. the sketch prints  "New client"

That's only if I send a request to the web server and not if it's left idle. If it's left idle it times out.

and the next client after that time is returned by the server. only not handled in your sketch

Is there a better way of solving this problem than how I dealt with it in my answer below?

I need to .stop() the older(first) client!

you stop() the client

in my case, I was reaching through http://esp8266.local/ I noticed that still can reach through ip but mdns failed i guess

The short answer: Config a static IP!
After looking at Git Issue #2371 I found out that I need to create a static IP address to fix this issue. I can do this by inserting WiFi.config(ip, gateway, subnet) just before WiFi.mode(WIFI_STA) in the code above.

First I found the information gateway & subnet I needed by opening the command prompt on a computer that's connected to the access point(router) as the one connected to the ESP8266 which functions in station mode. I did this on Windows by searching Command Prompt then typing ipconfig to obtain the following information:

Replace the points with commas! See this references for more information regarding other parameters and DNS.

To create an IP address you need to see your IP address in the red square in the picture above taken from the command prompt. The first three octects (numbers) of your router IP (probably 10.0.0.x, 192.168.0.x, or 192.168.1.x) must match your chosen static IP. For my example the numbers to match would be 10.0.0.
Next, I needed to obtain the DCHP range for my router. My router is a Netgear Wireless ADSL2+ Modem Router DG834Gv5. To obtain the range I needed to access my router settings. To access this I looked for an HTTP link under the router. For my router it was http://10.0.0.2 along with the username and password which was admin, admin respectively. This is what it looks like:

This will vary according to your router - Then I went into Advanced settings and saw the DHCP range. This is an error on my part noted by @djsfantasi. Please see his answer regarding DHCP range selection.The new static IP needs to be within the DHCP range According to one of the comments brendanmatkin made in Git Issue #2371 the last number of my static IP (which is ZZ in WW.XX.YY.ZZ) needs to be outside of this range. For me it didn't work, it worked when I used a value inside this range but brendanmatkin knows much more than me, I'm just a novice. There might be implications that I am not aware of so I think it's worth looking into. A DHCP range looks like this below:

My inserted code looks like this below:
void setup(void) {
  .
  .
  .
  Serial.begin(115200);
  //WiFi.disconnect();  //Prevent connecting to wifi based on previous configuration
  IPAddress ip(10,0,0,15); // this 3 lines for a fix IP-address
  IPAddress gateway(10,0,0,2);
  IPAddress subnet(255,255,255,0);
  //WiFi.hostname("ESP8266");      // DHCP Hostname (useful for finding device for static lease)
  WiFi.config(ip, gateway, subnet);
  //Station mode:
  WiFi.mode(WIFI_STA);
  .
  .
  .
}

Please comment for more info :)
Additional information and changes I've made to IDE:
OS : Windows 8.1
IDE : Arduino IDE V1.9.8
Board : Keyes ESP8266
Arduino IDE > Tools >Board (in boards manager) : Generic ESP8266 Board
Arduino IDE > Tools >lwip : V2 Low Memory
Arduino IDE > Tools >Esp FW:"nonos.." : nonos-sdk pr-3(known issues)*
Power Supply : USB COM from 300Watt desktop power supply. ~ 1.5A current output.
Much appreciation to @Juraj.  Juraj

It worked when the IP was in the range because there are no valid IP addresses outside the range.
WW.XX.YY.0 and WW.XX.YY.255 are reserved. The router is using the .1 and .2 addresses. That leaves 3-254 available, which as we see are the addresses within the DHCP range.
You can assign a static IP address within the DHCP range, but you run the risk of disabling 1 or 2 devices. DHCP doesn’t know you’ve used one of it's addresses, so can assign it to another device. Boom! Two devices with the same address and both will not function.
The correct way to resolve this is to log into the router and change the DHCP range. For example, increase the lower limit of 3 to (random pick) 20. Now, DHCP won’t be disturbed and will happily give out addresses to your devices. But if you need a static IP address, you’ve defined a pool, from WW.XX.YY.3 to WW.XX.YY.19


text:
cross correlation of two analogread value on arduino?
I am working on a final project called sound source localization using Arduino Uno. I want to use two sound sensor to capture a sound. The nature of the sound is clap or speech sound. I want to use the cross correlation method to estimate the time delay between the microphones then find the position and angle. My supervisor said to me you have to store the values on analogRead in two arrays then cross correlation the element of two arrays. But i am struggle the cross correlation part. I will appreciate any help from you guys.
#define LED_NORTH 2
#define LED_SOUTH 4

#define MIC_NORTH A0
#define MIC_SOUTH A2

/* let's said we want to read 100 samples */
const unsigned int numReadings = 100;
unsigned int analogVals[numReadings];
unsigned int i = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_NORTH, OUTPUT);
  digitalWrite(LED_NORTH, LOW);
  pinMode(LED_SOUTH, OUTPUT);
  digitalWrite(LED_SOUTH, LOW);
}

void loop() {
  int north = analogRead(MIC_NORTH);
  Serial.println(north);
  int south = analogRead(MIC_SOUTH);
  Serial.println(south);
  /* take numReadings # of readings and store into array */
  for(unsigned int i = 0; i < numReadings; i++)
  {
    analogVals[i] = analogRead(A0);
    delay(1000);
  }

What have you tried so far? Show us your code. What is its expected behavior? What is the actual behavior?

thanks Edgar Bonet , i update my question and i post my code i have done so far

The code you posted is incomplete. It cannot be compiled nor tested.

İ change a little bit the code.now i assume i can compile

Don't assume. Try.

Once you know how cross correlation works (https://en.m.wikipedia.org/wiki/Cross-correlation), the answer in this question might help you: https://arduino.stackexchange.com/q/11754/38721

you really need to think about what you need to do ... your code indicates that you have not done that yet ... in the loop() block, you read a value from the north mic, then you spend time printing, then you read a value from the south mic, then spend some time printing .... why are you doing that? ....... in the for loop, you read a value from the north mic and store the value, then you pause for one second and repeat .... why are you pausing? .... why are you not reading the south mic at the same time?

If you need to find a direction of sound in a full 360 you need at least 3 microphones. Otherwise will you not be able to detect the if the location of the sound is directly from front or behind.

I am not going to directly answer the question, as I think it is
ill-posed. Before posting a question here, you are supposed to have done
your research, and come with very specific problems you cannot solve
by your own. I may be mistaken, but it looks to me like you are at a
very preliminary stage where you barely started to think about the
project.
So, instead of trying to answer an overly broad question, I will try to
provide some guidance by asking questions back to you. Below is a list
of some problems and challenges you will have to consider for advancing
your project. It may not be complete: it's just what I can think off the
top of my head. This will hopefully help you tackle the right problems.
Non-stereo sampling
Your Arduino is incapable of stereo sampling. Since it has only one ADC,
it can only sample one channel at a time. This means you will have to
alternatingly sample the left channel, then the right channel, then the
left channel... Since the left and right samples are not taken at the
same time, this will have an implication on how you interpret the
results from the cross-correlation. Did you think about how you will
handle this? Is this acceptable? Will you have to instead use external
ADC chips in order to have real stereo sampling?
Slow sampling rate
If you analogRead() in a tight loop, you are taking at most one sample
every 112 µs. And since you are alternating between the channels,
on each channel you get one sample every 224 µs. This is a sampling
rate of 4.46 kHz, and a Nyquist frequency of 2.23 kHz. Is this
fast enough for your application?
In 224 µs, the sound travels about 76 mm, which is thus the
spatial resolution of your cross-correlation. How does this translate into
angular resolution? Is this resolution satisfactory? Do you plan to use
interpolation methods to try to improve it?
If the time resolution is not good enough, you can speed up the ADC by a
factor 2 or 4 at the cost of lowered accuracy. You will have to dig on
the MCU datasheet (or the Internet...) in order to learn how to do that.
Inconsistent sampling rate
When you use analogRead(), the time between consecutive samples can
depend on the code you run between the consecutive calls to
analogRead(). It can also depend on how your code gets interrupted by,
say, the timer interrupt, or the UART interrupt if you are sending data
out. An inconsistent sampling rate is something you want to avoid when
doing cross-correlations.
You could try to mitigate this problem by running the acquisition with
interrupts disabled. However, the only way to guarantee periodic
sampling is by configuring the ADC to be triggered automatically, either
by a timer or by itself (free running mode). Walking this path will
require you to forego the comfort of the Arduino library (analogRead()
is just so easy to use...), and carefully study the datasheet, which
would be a very significant time investment.
Do you have the time and energy for this? If you end up learning all
this low-level details on the configuration of the ADC, will this
learning be relevant to the course for which this is a project?
Finite data arrays
Mathematically, the cross-correlation is typically defined for infinite
series of samples. In your experiment, you will have to deal with finite
arrays, and this makes a subtle difference. Did you think about how you
will deal with the finiteness of the arrays? Are you going to zero-pad?
Remove the average before zero-padding? Apply a windowing function?

I hope it is clear by now that the “cross correlation part” is only one
of the many issues you will have to face. I suggest you discuss all
these questions with your supervisor. He might be able to advise you on
how to tackle them, whether it's worth it, where you may cut corners...


text:
Error Starting SPIFFS
There is a problem running a simple SPIFFS file system code on different versions of the Arduino IDE, as code shown below. In Arduino IDE version 1.8.4, works fine. No longer version 1.8.9, can not run.
ESP8266
IDE Arduino version 1.8.9
#include <FS.h>

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Init...");
  Serial.println();

  // Always get ERROR on init SPIFFS
  if (!SPIFFS.begin()) {
    Serial.println("SPIFFS.begin error...");
  } else {
    Serial.println("SPIFFS.begin OK!");
  }
}

So you have spiffs turned on in the IDE settings?

Where can I check that in IDE?

in Tools menu the "Flash size" option

OK. It works: Tools -> Flash size 4M (1M SPIFFS). Thanks!!!!


text:
Can't get fastled.h and remoteme.h to work together
I'm trying to make a Google Assistant controlled LED strip, but I'm stuck. I can control the on board LED of the nodemcu with Google Assistant, and I can control a LED strip too, but I can't combine the two. This is my code:

#define WIFI_NAME "****************"
#define WIFI_PASSWORD "********"
#define DEVICE_ID 1
#define DEVICE_NAME "Google_ESP"
#define TOKEN "************"

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#include "FastLED.h"

#include <RemoteMe.h>
#include <RemoteMeSocketConnector.h>

#include <ESP8266WiFi.h>

#define ledpin D0

RemoteMe& remoteMe = RemoteMe::getInstance(TOKEN, DEVICE_ID);

//*************** CODE FOR CONFORTABLE VARIABLE SET *********************

inline void setLedstrip(boolean b) {remoteMe.getVariables()->setBoolean("Ledstrip", b); }

//*************** IMPLEMENT FUNCTIONS BELOW *********************

// How many leds in your strip?
#define NUM_LEDS 120

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN D3

CRGB leds[NUM_LEDS];

boolean ledsOn = 0;

void onLedstripChange(boolean b) {
    Serial.printf("onLedstripChange: b: %d\n",b);

    if(ledsOn != b){
        if(b == 1){
            turnLedsOn();
        }
        else{
            turnLedsOff();
        }

        ledsOn = b;
    }
}

void setup() {
    FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

    Serial.begin(9600);

    WiFi.begin(WIFI_NAME, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED) {
        delay(100);
    }

    remoteMe.getVariables()->observeBoolean("Ledstrip" ,onLedstripChange);

    remoteMe.setConnector(new RemoteMeSocketConnector());
    remoteMe.sendRegisterDeviceMessage(DEVICE_NAME);

    pinMode(ledpin, OUTPUT);
    digitalWrite(ledpin, HIGH);
}

void loop() {
  remoteMe.loop();
}

void turnLedsOn(){
  digitalWrite(ledpin, LOW);
  leds[0] = CHSV(0, 100, 100);
  FastLED.show();
}

void turnLedsOff(){
  digitalWrite(ledpin, HIGH);
  leds[0] = CHSV(0, 0, 0);
  FastLED.show();
}

As you can see, it should turn on the on board LED and the first LED of the strip. It only does the on board one.

Hi @CodeHard, Could you provide links or the actual code to the two programs that work? Handy if you could provide links to the libraries you used. Thanks.

Wow, okay. Nevermind...
I just read my code of the ledstrip only program and the google assistant ledstrip to look for differences, and found out it didn't work because I used pin D3 instead of pin 3...

Also, ledpin should be 0 instead of D0.

Please add that as an answer down below. You can answer your own question and get some upvotes from solving it (hopefully).


text:
Can't get the right values with the pulse sensor and the LM35 temperature sensor . Reading 2 anolog sesnors
I am trying to combine the two sensors (pulse sensor using this library and LM35 temp)(on a Arduino UNO board),but there is a problem with them when is a noise at the pulse sensor .The values are fluctuates especially the LM35 it goes from 31 degrees (normal value ) to 25-50 and even the pulse one changes .
Here are the results .
The code is this(I got the code form the  Getting_BPM_to_Monitor sketch ) :
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

const int sensor = A5; // Assigning analog pin A5 to variable ‘sensor’
float tempc; //variable to store temperature in degree Celsius
float vout; //temporary variable to hold sensor reading
//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
void setup() {
  Serial.begin(9600);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {
  int temp = analogTemp();
  Serial.print(temp);
  Serial.println("Temp");

  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
    // Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    Serial.print("BPM: ");                        // Print phrase "BPM: "
    Serial.print(myBPM);                        // Print the value inside of myBPM.
    Serial.println(" A HeartBeat Happened ! ");
  }
  delay(20);                    // considered best practice in a simple sketch.
}
float analogTemp() {
  vout = analogRead(sensor);
  vout = (vout * 500) / 1023;
  return vout; // Storing value in Degree Celsius

}

Do all devices share a common ground?

This may be a hardware problem (eg wrong/no capacitors etc). Can you please post your schematic.

Yes they share the same ground .Here is the scheme

I used this pulse sensor


text:
Cannot import library file from ESP32 sdk library in "Eclipse C++ IDE for Arduino" project
I have successfully installed "Eclipse C++ IDE for Arduino" and the Plugin works fine. Now I installed a custom board (ESP32) by adding package_index.json URL in windows>prefrences>C/C++>Arduino. The board installed and also work fine.
The only problem I'm facing is that I'm unable to import platform SDKs and libraries.(e.g. #include "driver/adc.h") which are present in the path: G:\program\eclipse.arduinocdt\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include
I just want to import files just like in the Arduino IDE.
Eclispse version :
Eclipse IDE for C/C++ Developers
Version: 2019-03 (4.11.0)
Build id: 20190314-1200
Thank You

what Eclipse Arduino plugin? Sloeber? you don't need to import them. they are part of the esp32 Arduino core

I'm using  Eclipse C++ IDE for Arduino, that is included in Eclipse CDT tools, when I import "driver/adc.h" i get build error. here is the link of the plugin: https://marketplace.eclipse.org/content/eclipse-c-ide-arduino


text:
20x4 LCD shows up as 20x2
I need help with my LCD. I have a 20x4 LCD and it shows up as 20x2. The LCD address said "// Set the LCD address to 0x27 for a 16 chars and 2 line display". I changed it which says "// Set the LCD address to 0x27 for a 20 chars and 4 line display" and uploaded it, thinking it would show up as 20x4 as it should. But it didn't work:

it says lcd.begin(20,4)

In which way your 20x4 LCD 'shows up' as 16x2? What do you mean by that?

@nori I suggest you to explain what you mean by "shows up", as smajli said, and moreover to add the code you are running, explaining what you expect it to do and what it actually does. Otherwise it is impossible to understand what the problem is

Hi i added a picture to my question so i hope that could give you an insight on it

Are you saying that you changed the textual content of a comment and expected the code to magically know what was required...?

on the picture I see 20 columns and 4 rows.

@majenko , i wanted to show what pops up on my lcd

@juraj im sorry, i meant it shows up as 20 colums and 2 rows, the other 2 are missing.. im really sorry i have no experience in arduino uno. Im doing this for my highschool project

@nori did you properly regulate the contrast? Usually with this kind of displays you have to connect a potentiometer; try to rotate it so that the writings become visible (and use a demo program to test it - if you have issues with this, post the demo program)

@nori, do you have the model number of the display?  I have some 4 row displays.  It took a while, but I finally realized there were actually 2 sets of Hitachi like controllers.  Essentially, there were 2 displays in one.

@Majenko: it's not magic, it's AI uprising! LOL...

@frarugi87: i don't thinkt it's a contrast issue, otherwise every cell should be full-on or full-off, not only half of them. I guess it's an i2c address issue...

Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.
Look at the LCD rear, you should see your I2C chip, search google typing
["chip's code"  20x4 arduino]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...
Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.
Another way to find the address is to upload this code, it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.
If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.