text:
Project doesn't work after 2 - 3 times, requires frequent turning off and on
I am new to Arduino and I am working on a project. This project inspired me and I tried doing it.
The following code was provided in the description:
int maxPeople = 5; // maximum number of people allowed before the alarm goes off
int sensitivity = 5; //lower values will make it more sensitive and higher values will make it less
sensitive
//---------------------------------------------------

#include <TM1637.h>

int currentPeople = 0;

int buzzer = 8;

TM1637 tm(2,3);

int sensor1[] = {4,5};
int sensor2[] = {6,7};
int sensor1Initial;
int sensor2Initial;

String sequence = "";

int timeoutCounter = 0;

void setup() {
  //Setup code
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  tm.init();
  tm.set(2);

  delay(500);
  sensor1Initial = measureDistance(sensor1);
  sensor2Initial = measureDistance(sensor2);
}

void loop() {
  //Read ultrasonic sensors
  int sensor1Val = measureDistance(sensor1);
  int sensor2Val = measureDistance(sensor2);

  //Process the data
  if(sensor1Val < sensor1Initial - 30 && sequence.charAt(0) != '1'){
    sequence += "1";
  }else if(sensor2Val < sensor2Initial - 30 && sequence.charAt(0) != '2'){
    sequence += "2";
  }

  if(sequence.equals("12")){
    currentPeople++;
    sequence="";
    delay(550);
  }else if(sequence.equals("21") && currentPeople > 0){
    currentPeople--;
    sequence="";
    delay(550);
  }

  //Resets the sequence if it is invalid or timeouts
  if(sequence.length() > 2 || sequence.equals("11") || sequence.equals("22") || timeoutCounter > 200)
 {
    sequence="";
  }

  if(sequence.length() == 1){ //
    timeoutCounter++;
  }else{
    timeoutCounter=0;
  }

  //Print values to serial
  Serial.print("Seq: ");
  Serial.print(sequence);
  Serial.print(" S1: ");
  Serial.print(sensor1Val);
  Serial.print(" S2: ");
  Serial.println(sensor2Val);

  //Display current people count on 4-digit display
  tm.display(3, currentPeople % 10);
  int pos2 = currentPeople / 10;
  tm.display(2, pos2 % 10);
  int pos1 = pos2 / 10;
  tm.display(1, pos1 % 10);
  int pos0 = pos1 / 10;
  tm.display(0, pos0 % 10);

  //If the number of people is too high, trigger the buzzer
  if(currentPeople > maxPeople){
    tone(buzzer, 1700);
  }else{
    noTone(buzzer);
  }
}

//Returns the distance of the ultrasonic sensor that is passed in
//a[0] = echo, a[1] = trig
int measureDistance(int a[]) {
  pinMode(a[1], OUTPUT);
  digitalWrite(a[1], LOW);
  delayMicroseconds(2);
  digitalWrite(a[1], HIGH);
  delayMicroseconds(10);
  digitalWrite(a[1], LOW);
  pinMode(a[0], INPUT);
  long duration = pulseIn(a[0], HIGH, 100000);
  return duration / 29 / 2;
}

The required libraries are installed. I uploaded this on my Arduino nano and it worked fine. I varied the maxPeople and checked, then too it worked correctly. The third I made objects enter and leave the room by crossing the ultrasonic sensors. It seemed to work correctly, the maximum count (maxPeople) got reached and the buzzer went on. Then I made the object leave the room. Instead of decreasing the number in the display (TM1637 4 digit display) kept on increasing.
Then I turned the USB source OFF and tried again. Again it worked correctly once or twice and the same problem persists.
Sometimes even before the max count is reached, while making an object leave, the count gets increased. And sometimes the count in the display stays still at 0000 or oscillate between '''0000''' and '''0001'''.
(I thought it may be a fault in the Arduino or the ultrasonic sensor or the display, but I checked them with other open-source programs, they worked fine.)
I also tried allocating different pins to the buzzer, sensors and display, still the problem persists.
The declared integer sensitivity is never used in the code. Someone has commented. I tried that too, even then it doesn't work properly.
Is there any mistake in the code that causes this problem or something else?  I am stuck on this since last week.
Any help is appreciated.

Edit:
As per @Michel's comment, I tried to change the strings into character arrays.
int maxPeople = 5; // maximum number of people allowed before the alarm goes off
int sensitivity = 5; //lower values will make it more sensitive and higher values will make it less sensitive
//---------------------------------------------------

#include <TM1637.h>

int currentPeople = 0;

int buzzer = 8;

TM1637 tm(2, 3);

int sensor1[] = {4, 5};
int sensor2[] = {6, 7};
int sensor1Initial;
int sensor2Initial;

char sequence[2];

int timeoutCounter = 0;

void setup() {
  //Setup code
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  tm.init();
  tm.set(2);

  delay(500);
  sensor1Initial = measureDistance(sensor1);
  sensor2Initial = measureDistance(sensor2);
}

void loop() {
  //Read ultrasonic sensors
  int sensor1Val = measureDistance(sensor1);
  int sensor2Val = measureDistance(sensor2);

  //Process the data
  if (sensor1Val < sensor1Initial - 30 && sequence[0] != '1') {
    strcat(sequence, "1");
  } else if (sensor2Val < sensor2Initial - 30 && sequence[0] != '2') {
    strcat(sequence, "2");
  }

  if (strcmp(sequence, "12") == 0) {
    currentPeople++;
    sequence[0] = '\0';
    sequence[1] = '\0';
    delay(550);
  } else if (strcmp(sequence, "21") == 0 && currentPeople > 0) {
    currentPeople--;
    sequence[0] = '\0';
    sequence[1] = '\0';
    delay(550);
  }

  //Resets the sequence if it is invalid or timeouts
  if (strlen(sequence) > 2 || strcmp(sequence, "11") == 0 || strcmp(sequence, "22") == 0 || timeoutCounter > 200) {
    sequence[0] = '\0';
    sequence[1] = '\0';

  }

  if (strlen(sequence) == 1) { //
    timeoutCounter++;
  } else {
    timeoutCounter = 0;
  }

  //Print values to serial
  Serial.print("Seq: ");
  Serial.print(sequence);
  Serial.print(" S1: ");
  Serial.print(sensor1Val);
  Serial.print(" S2: ");
  Serial.println(sensor2Val);

  //Display current people count on 4-digit display
  tm.display(3, currentPeople % 10);
  int pos2 = currentPeople / 10;
  tm.display(2, pos2 % 10);
  int pos1 = pos2 / 10;
  tm.display(1, pos1 % 10);
  int pos0 = pos1 / 10;
  tm.display(0, pos0 % 10);

  //If the number of people is too high, trigger the buzzer
  if (currentPeople > maxPeople) {
    tone(buzzer, 1700);
  } else {
    noTone(buzzer);
  }
}

//Returns the distance of the ultrasonic sensor that is passed in
//a[0] = echo, a[1] = trig
int measureDistance(int a[]) {
  pinMode(a[1], OUTPUT);
  digitalWrite(a[1], LOW);
  delayMicroseconds(2);
  digitalWrite(a[1], HIGH);
  delayMicroseconds(10);
  digitalWrite(a[1], LOW);
  pinMode(a[0], INPUT);
  long duration = pulseIn(a[0], HIGH, 100000);
  return duration / 29 / 2;
}

Is there any mistake in this? On uploading this code, the display stops at '0001' and doesn't work further.

It might be worthwhile to get rid of the String type and use a fixed character array. Because of dynamic memory allocation to String you  might get memory gaps, and eventually running out of memory.

@MichelKeijzers Thank you! I just came to know about character arrays. I'll try that and update.

You will need to change quite some things, like defining a constant for the MAX array size, and use functions strcat, strln and strcmp instead of adding, checking the size and comparing.

When using C strings, you have also to keep one \0 for the end symbol, so to store "01", you need 3 bytes., otherwise the strlen/strcmp will not work.

Also I think that with - 30 you want to convert '0' to 0, but then you need to use 0x30 (hex), which is '0', or better: use '0' directlly (with a cast if needed)

Try using 0x30 instead of 30 (assuming you want to convert '0' to 0 (the character zero to the number 0)

@MichelKeijzers Thank you so much for all your help. It works pretty well now. However if someone is moved out (not possible in real, as the minimum count = 0) when the current people = 0, it gets stuck at 0000 and doesn't sense anything further. Can I add something like,
if (currentPeople < 0 ) continue;
in the code? It's not possible to use continue in loops, is there anything similar that can be used?
Kindly post all your comments as an answer, so that I could accept that.

You can use the statement, I'm not sure if it will do what you want but it's a valid statement syntactically wise.
Also, you can probably skip all sequence[1] = '\0'; statements. When the first element is 0, a string is considered to end there and e.g. strcmp does not check further.


text:
How to close humidity sensor at specific humidity
I am using dht humidity and temperature sensor on arduino and i would like to add relay and buzzer on the system. What I would like to do is to close it via buzzer and on 65% humidity run buzzer. The code i use is:
/* DHT-22 sensor with 12c 16x2 LCD with Arduino uno
   Temperature and humidity sensor displayed in LCD
   based on: http://www.ardumotive.com/how-to-use-dht-22-sensor-en.html and
   https://www.ardumotive.com/i2clcden.html for the i2c LCD library by Michalis Vasilakis
   Recompile by adhitadhitadhit
   Notes: use LCD i2c Library from link above, i'm not sure why but new Liquidcristal library from Francisco Malpartida  isn't working for me
   other thing, check your */

//Libraries
#include <dht.h> // sensor library using lib from https://www.ardumotive.com/how-to-use-dht-22-sensor-en.html
#include <LiquidCrystal_I2C.h> // LCD library using from  https://www.ardumotive.com/i2clcden.html for the i2c LCD library
#include <Wire.h>
dht DHT;

//Constants
#define DHT22_PIN 2     // DHT 22  (AM2302) - pin used for DHT22
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 after finding it from serial monitor (see comment above) for a 16 chars and 2 line display

//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
    Serial.begin(9600);
    lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setBacklight(HIGH);
}

void loop()
{
    int chk = DHT.read22(DHT22_PIN);
    //Read data and store it to variables hum and temp
    hum = DHT.humidity;
    temp= DHT.temperature;
    //Print temp and humidity values to LCD
    lcd.setCursor(0,0);
    lcd.print("Humidity: ");
    lcd.print(hum);
    lcd.print("%");
    if (humidity <= 50)
{
   digitalWrite(ledPin, HIGH);
   digitalWrite(buzzer, HIGH);

 }

 else

 {

 digitalWrite(ledPin, LOW); digitalWrite(buzzer, LOW);

    lcd.setCursor(0,1);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.println("Celcius");
    delay(2000); //Delay 2 sec between temperature/humidity check.
}

How to add relay and buzzer to close it with buzzer run on 65% humidity value?

Do you know how to implement the required subtasks (control relay/buzzer, compare values)? If yes, where exactly do you have problems?

Yes i did it once but this time i changed my LCD connection with socket. Defining buzzer and relay it gives error on ide. I have follewed arduino official code. So i need to adapt it to above code which provides humidity and temperature on LCD

Hmm, we need to see the code that doesn't work and which you have problems with... how do you actually "define" a relay/buzzer? You just need to set the desired pins to outputs and control them with digitalWrite() and tone() corresponding to some logic you have to implement. Without seeing what you do we can't know what you're doing wrong.

you don't have any code that says if humidity is equal to 65%, then sound a buzzer

I would also suggest you include your schematic, not a fuzzy drawing, that will help a lot.

For ther buzzer I have added if (humidity <= 50) {
digitalWrite(ledPin, HIGH);
digitalWrite(buzzer, HIGH); }
else {
digitalWrite(ledPin, LOW);
digitalWrite(buzzer, LOW); } But it provides error.  My connection is as follow: LCD: SCL to A5
CDA to A4
GND to GND
VCC to 5V
DHT Data to D2
VCC to 5V
GND to GND
Buzzer: Data to 7
GND to GND

A) edit the code in the question instead of posting snippets in comments. B) which error?! C) though it's probably not related to hardware, if you want to inform us about your circuit you should draw circuit diagram.

I have uploaded the infos you asked for. I couldn't decide the relay connection so I need your help on relay connection and code.

Is it a relay module or a standalone relay?

It is external 12V relay. I will feed it seperately out of arduino. What I want is to run the buzzer at 65% humidity and close the system via relay around 80% huımidity. I know that I didn't add relay code and buzzer library because that side is completely the part I need the halp.

ledPin and buzzer are neither declared/defined, nor are the corresponding pins configured as outputs. I assume the black dot in the drawing is the buzzer. The problem here is that you must not connect the buzzer between Vin (connected to 9V battery) and a GPIO - this will fry the arduino! What kind of buzzer is it (datasheet)?

Did you actually google for "arduino buzzer"/"arduino relay"? There are tons of tutorials out there... those also show you how to wire everything up

https://components101.com/misc/buzzer-pinout-working-datasheet

yes I did. But it didn't work. As I mentioned I did the same system once before but I wouldn't use IC12 LCD and It corrupted everything :)

Normally I am python developer and I haven't been using C# for years. It seems totlly bunk to me at tyhe moment.

yes I googled it BTW. I have problem where i should add the buzzer and relay lines.

Currently I am able to show temperature and humidity values on LCD. Other sides I corrupted.

Can you recommend your solution on draft and code if possible?

Consider upgrading your power supply, a 9V battery will not cut it. Also a Schematic would be a big help, the frizzy thing is difficult to interpret. You can get KiCad free but it is nice to leave a donation.

yes I am using external 12V adapter instead.

In this code:
void loop()
{
   sample temp and humidity;
   display temp;
   display humidity;

   if humidity <= 50
      LED on;
      buzzer on;
   else
      display temp
      wait 2 sec
   end

There is a missing '}' to to close the if/else.
Why do you display temp twice within the loop?
Where is the logic for the relay and the buzzer at 65%?
Pin numbers for the LED and the buzzer are undefined.
The LED and buzzer pins need to be set to OUTPUT mode in your setup() function.

If I understand your description, you probably need somethng like the following, in your loop function:
   if humidity <= 50
      LED on;
      buzzer on;
   else if hum >= 65%m
      close relay;
      buzzer on;
   end

When I have a problem with program logic that isn't obvious to me, I write it out in pseudo-code as I did above. Once I figure out the logic, then I'll type in C++ with proper syntax.
If I haven't understood your intentions in the above pseudo-code, I'd suggest you do the same thing, until you believe what you've written. Only then try to make it into working code.

What I missed was seems to be added humidity function into void main function. By checking c# I solved it. Now the system works fine thank you.

source: Stack Exchange

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

sort: votes


text:
PubSubClient - MQTT_MAX_PACKET_SIZE How is it calculated
I'm using an ESP32, and I want to rule out a probable MQTT error. In PubSubClient , MQTT_MAX_PACKET_SIZE is set to 256. Is 256 the size for message only ? if not, what is left for message only ?

It is the maximum size of an entire packet.  In publish() this check is done:
if (MQTT_MAX_PACKET_SIZE < MQTT_MAX_HEADER_SIZE + 2+strlen(topic) + plength) {

So the maximum length of a message payload will be
MQTT_MAX_PACKET_SIZE - MQTT_MAX_HEADER_SIZE - 2 - strlen(topic)

MQTT_MAX_HEADER_SIZE is defined as 5, so if you have, for example, a 20 character topic you would have 256 - 5 - 2 - 20 = 229 bytes left for your payload.

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


text:
Using a template inside a class
I'm trying to use a template function, but I get an error
home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: sketch/emptyCode.ino.cpp.o: in function `startIOTservices()':
/home/guy/Documents/git/Arduino/HomePi/emptyCode/emptyCode.ino:37: undefined reference to `void myTest::funcOne<bool>(bool)'
/home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: sketch/emptyCode.ino.cpp.o: in function `setup':
/home/guy/Documents/git/Arduino/HomePi/emptyCode/emptyCode.ino:70: undefined reference to `void myTest::funcOne<bool>(bool)'
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

inside .cpp file:
myTest::myTest()
{
        Serial.println("start");
}

template <class T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

inside .h file:
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

and calling it from .ino file:
testA.funcOne(true);
What am I doing wrong ?
EDIT 1:
complete .h .cpp files - which originaly belongs to myJSON library which are deleted in this snip
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define DOC_SIZE 1000

class myJSON
{
};

class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

#endif

.cpp file
#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

#define LOG_LENGTH 4

myJSON::myJSON(char *filename, bool useserial)
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

myTest::myTest()
{
        Serial.println("start");
}

// template <typename T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

put the template function definition in the .h file.

@Juraj when leaving the template defining inside .h file only I get :error: variable or field 'funcOne' declared void  void myTest::funcOne(T1 arg)

Please provide a minimal complete example. The error might be in the calling/using source.

@thebusybee Since it is only example -  I've put myTest class inside another .cpp  , and .hfiles I'm currently using. funcOne is called during setup() function

Would you mind to show us the commands to compile and link? Oh, and the source of this other module, please. You can enable verbose output of the build in the preferences.

@thebusybee what do you mean commands to complie and link ?

You might like to [edit] your question with the now-current code. Please don't remove the old code because comments refer to it.

@thebusybee, there is nothing to edit. it is simple to reproduce the problem. it is build with Arduino IDE.

@thebusybee see edit 1

@Juraj you are right - Arduino IDE 1.8.2

@Juraj The OP said "when leaving the template defining inside .h file only I get :error..." so the source is not up-to-date. Therefore I asked for current sources. And I still miss the main module which calls funcOne(), since the mentioned error presumambly points there.

move the template method definiton to .h or define it in class. it is not a real function, only a prescription for functions. Like this:
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

template <class T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

or this
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg)
    {
            Serial.println(arg);
    }
};

Can you please explain what does it differ from what I originaly wrote in my question ?

the template is a declaration. the source where you use the template can't see it in cpp

Actually duplicate the function insde .h file ?

I write "move". It should be only in .h

Compilers don't know which class to use for the templated class if you compile the method separately. The common way is to put the method implementation into the header so the compiler is able to instantiate the specific implementation.

@thebusybee, there is myTest:: to assign the method to class

Sorry, I forgot the @Guy.D the comment was addressed to.

@thebusybee, I know, but Guy has it right

@Guy.D, did it help?

@Juraj - tested now. YES! thank you very much


text:
UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins
This board have pins to ESP8266's GPIOs.
What is Tout pin ?
On the back of the board it label pins :GPIO12, GPIO02, and another GPIO02 ? a continuity test shows that they are not connected. So what is it ?

From esp8266 datasheet:

TOUT - ADC pin. It can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin 6). However, these two functions cannot be used simultaneously.

from the pinout PDF of the Uno+WiFi board:

so there is a GP1012 and GP1O0 ? what is it ?

these are io pins of the esp8266. for example you can wire RX/TX to some pins of ATmega328p to use SoftwareSerial to communicate with the esp8266

I understand that these pins belong to ESP8266, but observe the text carefully - it goes not say gpio12 is says gp1012 (lower case in purpose )

@Guy.D, it is the normal quality level of the Robotdyn docs

So it is GPIO : 02,10,12 ?

gpio 0, gpio 2, gpio 12 and gpio 16. but Espressif doesn't call them general purpose io, only io, because the pins have constraints

@Jurag - see text on attached pic

sorry, I skipped io 4. should I see something different then on the pinout from the PDF?

next to ground is io 0 not io 2. switch 7 and the ESP BOOT pull io 0 LOW for bootloader mode of the esp8266


text:
PSF WiFi module - Is it similar to ESP8266
Some products (as TUYA and SONOFF) are using a PSF wifi module. In this link, PSF-B04 is reffers as ESP8285 design.
does anyone flash a sketch to such chip ? should it be reffered as ESP8285 when selecting chip type in Arduino IDE ?
Guy

This is actually an ESP8285 (not 8265) design, which is a version of the ESP8266 with integrated 1MB or 2MB Flash memory. From a programming perspective, aside from the memory size, it's identical to the ESP8266. The ESP8266 Arduino Core also supports this chip.

@StarCat That was a typo, thank you. So chip wise, I can upload sketch as any other esp8266 (without any change is MCU type at Arduino IDE ) ?

Did you look in the boards menu for the esp8266 support package?

@timemage what do you mean? I saw pics of a Tuya unit, and I want to know if my code can be uploaded to it (as any other ESP8266)

ESP8285 is supported by esp8266 Arduino. You can select it in Tools menu.


text:
ArduinoJSON :: How to determine Array's size in a DOC conatinaing not only Arrays
Parameter file containing MQTT topics as shown below, is read into StaticJsonDocument<1250> DOC variable.
Size of some groups may differ between MCU's, for example sub_topics_win may contain more topics, if MCU is 8 relay unit. For that I need the flexibility to read a specific topic that can differ in size.
What is the rifht way to do it?
{
    "pub_gen_topics": [
        "myHome/Messages",
        "myHome/log",
        "myHome/debug"
    ],
    "pub_topics": [
        "myHome/Cont_A/Avail",
        "myHome/Cont_A/State"
    ],
    "sub_topics": [
        "myHome/Cont_A",
        "myHome/All",
        "myHome/lockdown"
    ],
    "sub_topics_win": [
        "myHome/Windows/gFloor/TwinWindow",
        "myHome/Windows/gFloor/Pergola"
    ],
    "sub_topics_SW": [
        "myHome/Light/int/gFloor/SalAmbient1",
        "myHome/Light/int/gFloor/SalAmbient2",
        "myHome/Light/int/gFloor/Lobby",
        "myHome/Light/int/gFloor/Corridor"
    ],
    "sub_topics_win_g": [
        "myHome/Windows",
        "myHome/Windows/gFloor"
    ],
    "sub_topics_SW_g": [
        "myHome/Light",
        "myHome/Light/int",
        "myHome/Light/int/gFloor/"
    ],
    "ver": 0.1
}

https://arduinojson.org/v6/api/jsonarray/size/

@Juraj I tried to define DOC["pub_gen_topics"], for example, as an array and using size() to get its size, without any luck.

add some code to the question

If your question is How can I read each element of an array when I don't know its size?, then simply use a for-loop, like so:
JsonArray sub_topics_win = doc["sub_topics_win"];

for (const char* topic : pub_gen_topics) {
  Serial.println(topic);
}

See also: JsonArray::begin() / end(), JsonArray::size().

An early try was JsonArray array = DOC["sub_topic_win"].to<JsonArray>();. I tried to create it as an Array by adding .to<JsonArray>()

to<JsonArray>() creates an empty array, as<JsonArray>() casts the value to a JsonArray, allowing you to use the for-loop.

As I understand, your question is How can I determine the best capacity for a JsonDocument when my input varies?
If that's the case, I recommend that you read How to determine the capacity of the JsonDocument?. Here is an extract from the section "What if my input varies?":

If your program must deserialize a JSON document that changes, you must allocate a JsonDocument that is large enough for the largest valid input. I insist on the term valid because your program doesn't need to support any JSON document, but only the ones relevant to your use case.

Applying this to your problem, you need to put eight topics in each list and pass this document to the ArduinoJson Assistant, which results in a recommended capacity of 3027 bytes on ESP8266. Now, this is a bit large for a StaticJsonDocument, so consider switching to a DynamicJsonDocument.

Sorry for not explaining myself good enough.  Input, as show in my question is considered to be suited in  size of 1250. But there is a real life situation that "sub_topics_win" would be consisted of 8 elements and not 2 as shown.
When array size is known (2 in show case) I use a for loop of 2 iterations to read that array. And my question is - how can I read an array when is size can vary ?


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

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

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

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

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

so each device will use exactly the same MQTT topic?

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

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

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

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

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

@Majenko see in edit 1

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


text:
ESP32 - `Brownout detector was triggered ` upon Wifi begin
I'm Using an ESP32 - NodeMCU. One of the MCU's is acting weird upon boot, while at start I thought it was something to do with its sleep cycle. But, it seems that even on a minimal code as shown below, I get this message at the Serial output: Brownout detector was triggered
void setup()
{
  Serial.begin(9600);
  Serial.println("\nBegin");
  Serial.println(bootCounter);

  WiFi.begin("Xiaomi", "guy");

  while (WiFi.status() != WL_CONNECTED && millis())
  {
    delay(200);
    Serial.print(".");
  }
}

Edit 1: attaching MCU picture.
Can someone please explain ?
Edit 2: A workaround
stop alerting

Can you link to the actual board you are using?

@Majenko See edit 1

Those boards have an inherent weakness in that they don't provide enough decoupling capacitance for the module.
Not all modules are quite the same, and some have more internal decoupling than others (not by design, just due to component tolerances).
I have found that unless you provide adequate decoupling of your own some modules work just fine and some don't. Some brown-out and some fail to flash.
For all my designs now I always provide both a 100nF and an 10uF capacitor right at the power pins of the module. However those boards don't provide anything like that.
You need to modify the board to add a capacitor (about 10uF) directly across the power and ground pins (pins 1[ground]-2
[3.3v]) of the ESP32 module. I like to use an 0805 MLCC capacitor as they fit nicely across the pins and are discrete, but they can be tricky for a novice to solder. So an electrolytic through-hole capacitor can be a simpler proposition (make sure you get the polarity right).

Since I was it with solar panel and a battery, those RTC variables are vital to survive a proper boot. Can you please add a diagram foradding  capacitors?

Not really. You just connect one side to the GND pin (pin 1) and the other to the 3.3V pin (pin 2).

10uF and 100 nF in parallel ?

No, you just need the 10uF.

OK - soldered, and it helps!! ( when powered via 3.3v pin ), BUT when connected through USB i get this error constantly ( without booting at all ). what should I do about it ? Do you recommend adding this cap to all boards now ?

I always add a cap when designing an ESP32 board. Adding it to all development boards can't hurt, that's for sure.  For USB the on-board regulator may be a little weak, or your USB voltage may be a little reduced, maybe from a USB cable with too-thin wires.

I had the same problem. I found that solution in a forum on Github, which helped at once:
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
void setup(){
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

Yes, I use it too now

Hey this work for me, thank you very much. even though i realized this is power issue, but It can be done with setup software :O

It is not a solution, it just suppresses the warning and may lead to other issues. Like other answers, you should try changing the cable, fixing the solder, or adding capacitors. If nothing works then I would say go with this. I tried it but it started showing different errors.

I came across the same issue on my experiments.
What sorted the issue for me was powering the ESP-32_CAM from the 5V pin on the programmer. Take the cable off the 3V and plug it into the 5V pin on the cam. Then use the jumper on the programmer to select the 5V.
I hope this makes sense and that it helps someone.

After some Tests i recognized, that the problem is between the miro-USB-connector to the Vin Pin. So i soldered a thin wire from Pin 5 of the USB-Connector (5V-Pin) to the Vin-Pin of The Dev-Board.
And it works without Problems.

for me it happend using batteries for solar panel uses ( while it didn't happen some other boards on same setup )

Swapping USB cable solved my issue of continuous brownout detector triggering.
I tried some above answers. Disabling brownout detector as suggested by Vahe Arakelyan helped on Blink sketch, but WiFi including sketches would still fail to run.
Then started to suspect HW and power failure. Did not soldering pins as suggested by user73106, but this made me notice voltage fluctuation. So swapped USB cable and this seemed to keep the voltage steady enough for good operation... It looks like some cable/connector fault may limit the current to allow some low power sketch to run but to fail on more current drawing sketch.

It could even be a software issue, i.e Code, if you use LedCWrite without its setup then it causes this issue.


text:
Init a calss inside a class
I'm building a monitoring IP class, IPmonitoring, that using an SPIFFS class that I wrote, flashLOG. Inside IPmonitoring I have 2 instances of flashLOG (code below).
My sketch have several instances of IPmonitoring for several servicesI wish to monitor. I Wish that connectionLOG and disconnectionLOG have unique and automated names.
For example if I'm monitoring a service called MQTT its connect and disconnect log will be MQTT_discolog.txt and MQTT_conlog.txt. In my code below, filename1 and  filename2 are consts.
class IPmonitoring
{
private:
        char *_IP;
        char *_nick;

        flashLOG connectionLOG;
        flashLOG disconnectionLOG;

public:
        IPmonitoring(char *IP, char *nick, char *filename1 = "/conlog.txt", char *filename2 = "/disconlog.txt")
            : connectionLOG(filename1), disconnectionLOG(filename2)
        {
                _IP = IP;
                _nick = nick;
        }

EDIT1 - example how to use class
my goal is that filename1 for example will be MQTTbroker_connlog.txt meaning a combination of _nick and a suffix,
IPmonitoring MQTT_service("192.168.3.200","MQTTbroker");

void setup()
{
MQTT_service.start();
}

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

Do you mean the variable names in the source code? Any reason why you want this and not use a member in the class flashLOG, initialized by its constructor, to retain its name?

@Sacha yes,  filename1 + filename2. I don't understand what is your suggestion, since this is the way flashLOG inits ( with a filename )

Forget about my first comment. In your example, how would the code creating the IPmonitoring instance know the name of the service it will monitor?

@Sacha - In a case I have more than one instance, using filename1 and filename2 in shown manner will over run each other - it is a not valid way to do so, unless I write each ones name in specific

you have the filenames as parameters. so construct it with different filenames

Please show us some example how you like to use the class IPmonitoring.

@thebusybee see edit 1

@Juraj see edit1

If you let the caller provide the complete filenames, the task would be quite simpler. I see this as a reasonable decision. -- Oh, and since you are programming in C++, the usage of std::string instead of C strings (char[]) can make things easier.

Judging from your example usage, you want the filenames to be built by
the IPmonitoring constructor. However, since that class cannot know in
advance how much space is needed for the file names, you are left with
two choices:

Let those file names be data members: arrays of char of some fixed
size. This will impose a limit on the maximum file name length.

Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};

Note the destructor, which is needed to avoid memory leaks, unless all
the instances of the class are statically allocated (which would be good
to avoid memory fragmentation). You may want to implement a copy
constructor and a copy assignment operator, as per the rule of
three.

Can you please explain : _IP(IP), _nick(nick) I never used such syntax

@Guy.D: It means “Initialize _IP with the value of IP”. It is functionally equivalent to the assignment you used in the constructor, but it is syntactically an initialization rather than an assignment. It is here intended to make clear that the constructor does nothing more than initialize the data members.

great! Didn’t know it

Can you please explain/ give an example for static allocate of class ?

@Guy.D: See your own usage example: the object is a global variable, and global variables are statically allocated. In this case the constructor is called at program startup, before main(), and the destructor is normally never called.

OK, just wanted to be sure your mean.

Would it make sense to use C++ strings (std::string) that can be dynamically concatenated? -- 2. Beginning with C++14 the rule to obey is the Rule of Five.

You have three options for the file names and generally.

constant string a.k.a. string literal
string buffer global or on stack with scope valid while the string is used
dynamically allocated string on heap

with 2) and 3) you can then build a string with C str or sprintf functions
option 3) is alright on MCU if you create these file names only at startup, not if you create them repeatedly as the sketch is running
If you choose option 3) you can build the strings in the constructor of IPmonitoring class, but you can't build the string in the member initialization part of the constructor. You have to add setters to flashLOG class and after building the strings for file names set them to the flashLOG instance with the setters.

@Guy.D I enhanced the answer


text:
Configure input pullup through registers
I can set pin mode to input or output through the DDRx registers. How can I enable the internal pullup resister through a register?

Credits to GoForSmoke.
Also see Gerben's comment below.
See: https://forum.arduino.cc/index.php?topic=286145.0
byte ddrcMask =       ~
(
        (1 << DDC0) |  // pinMode( 14, INPUT ); // Set to input
        (1 << DDC1) |  // pinMode( 15, INPUT ); // Set to input
        (1 << DDC2) |  // pinMode( 16, INPUT ); // Set to input
        (1 << DDC3)    // pinMode( 17, INPUT ); // Set to input
);

byte portcMask =
(
        (1 << PORTC0) |  // digitalWrite( 14, HIGH ); // Enable the pullup
        (1 << PORTC1) |  // digitalWrite( 15, HIGH ); // Enable the pullup
        (1 << PORTC2) |  // digitalWrite( 16, HIGH ); // Enable the pullup
        (1 << PORTC3)    // digitalWrite( 17, HIGH ); // Enable the pullup
);

byte pincMask = ( (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) );

void setup( void )
{
  // Configure the pins for input
  DDRC = DDRC & ddrcMask;

  // Enable the pullups
  PORTC = PORTC | portcMask;

  // Read all four inputs
  uint8_t Pdat = PINC & pincMask;
}

void loop( void )
{
}

For clarity. You are using the same register (PORTC) you would use to set an OUTPUT pin to HIGH. When the pin is an INPUT it will enable the pull-up resistor. So the function of the register depends on whether the pin is an INPUT or OUTPUT.

@Gerben thanks for the clarification (added a reference to your comment).


text:
LCD shows wrong value from MQ-135 sensor and the txt is stuck on screen
i am using a MQ-135 gas sensor and 20x4 LCD screen and it shows different values on the serial
monitor it shows 756 PPM and on the LCD screen it is stuck below 320PPM the text BAD is also stuck on the screen and doesn't update on the
lowering of PPM value of CO2

this is my code
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define sensor A0
int gas, co2lvl;
#define updateDisplay();

void setup()
{
pinMode(sensor,INPUT);
Serial.begin(9600);
lcd.begin(20,4);
  lcd.clear();
}

void loop()
{
co2lvl=gas-255;
co2lvl=map(co2lvl, 0,1024,400,5000);
Serial.print(co2lvl);
Serial.print("ppm");
Serial.println();
delay(200);
if(co2lvl>=699){
updateDisplay();
lcd.setCursor(0,0);
lcd.print("CO2 IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(6,1);
lcd.print("EXCELLENT");
}
else if(co2lvl<=700){
updateDisplay();
lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(4,1);
lcd.print("GOOD");}
else if(co2lvl<=900){
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("FAIR");}
else if(co2lvl<=1100){
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("MEDIOCRE");
}
else(co2lvl<=1600);{
  updateDisplay();
  lcd.setCursor(0,0);
lcd.print("CO2 PRESENT IN THE AIR");
lcd.setCursor(0,1);
lcd.print(analogRead(co2lvl));
lcd.setCursor(5,1);
lcd.print("BAD");}
}

use CO2 level in the air to get better fit on the display ... CO2 level is probably enough

You made a mistake in the line:
else(co2lvl<=1600);

Because of the semicolon (;) it will not do anything for that condition. But instead the following lines will be executed always.
The following is a slight refactoring making your code more clear, removing also duplicated code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define sensor A0
int gas, co2lvl;

void setup()
{
  pinMode(sensor,INPUT);
  Serial.begin(9600);
  lcd.begin(20,4);
  lcd.clear();
}

void loop()
{
  co2lvl=gas-255;
  co2lvl=map(co2lvl, 0,1024,400,5000);
  Serial.print(co2lvl);
  Serial.print("ppm");
  Serial.println();
  delay(200);

  lcd.setCursor(0,0);
  lcd.print("CO2 PRESENT IN THE AIR");
  lcd.setCursor(0,1);
  lcd.print(analogRead(co2lvl));

  if      (co2lvl <=  300) { show(6, "EXCELLENT"); }
  else if (co2lvl <=  700) { show(4, "GOOD"     ); }
  else if (co2lvl <=  900) { show(5, "FAIR"     ); }
  else if (co2lvl <= 1100) { show(5, "MEDIOCRE" ); }
  else if (co2lvl <= 1600) { show(5, "BAD"      ); }
}

void show(int position, char* text)
{
  lcd.setCursor(position, 1);
  lcd.print(text);
}

thank you a lot

You are welcome... if it helped you please upvote the answer, and if the answer is correct to solve your solution, accept the answer (by clicking the checkmark next to the answer). Good luck with your project.


text:
How can I use IRsend with a string or convert a char from serial to uint32_t?
I'm trying to control my arduino with a raspberry pi with python instead of C++ (which I don't know). I've found code to take a string from serial and print it, but instead I'd like to use IRsend to use the code. Unfortunately I'm getting the error invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]. I know this must be an incredibly dumb question but is there a int() function for uint32_t for arduino C++? that I could set blah=uint32_t(buf) and then use my irsend.sendNEC(buf, 32)? If it's not painfully obvious, I don't know C++ and my python isn't great.
#include <IRremote.h>

char buf[80];

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buf);
    Serial.println("<");
    irsend.sendNEC(buf, 32);

  }
}

Error:
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino: 39:27: warning: invalid conversion from 'char*' to 'uint32_t {aka long unsigned int}' [-fpermissive]
             irsend.sendNEC(buf, 32);

                  ^

In file included from
/home/pi/Desktop/sendIRfromserial2addingir/sendIRfromserial2addingir.ino:1:0:
/home/pi/Arduino/libraries/IRremote/src/IRremote.h:444:10: note:   initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
     void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
          ^~~~~~~`

Instead of
irsend.sendNEC(buf, 32);

cast it to an unsigned int32 type:
irsend.sendNEC((uint32_t) buf, 32);

That works! Thank you so much! It's sad how much time I spent looking for an answer. I think it's too simple of a question to have been asked before.

Maybe but it's ok ... Welcome anyway, next time also use ctrl-k to align your code and I advise to read a book about C/C++, it will help you greatly using the Arduino. Good luck with your project.


text:
Can I run 3 motion sensors with a voltage regulator?
I want to power 3 hc-sr501 PIR motion sensors with a voltage regulator that can output 5v-1A.
If I make such a system, will there be a noise?

You need to add up the current demand of each of the 3 PIRs.  Usually a power supply is chosen which can supply at least double the expected current demand.  What is the part number of the PIR?  Also, do not forget to add the current demands for all other components such as the Arduino board.  Which Arduino board are you using?  Noise is a complex problem.  Not only is a clean power source needed to mitigate noise, but short cables and a electrically clean environment just to name a few possibilities.

i am using only atmega 328p.  to sensors is hc-sr501.

Many internet sources like this one claim the HC-SR501 requires less than 50uA (or 0.00005 Amps).  Likely this is only in a quiet or quiescent state and current demand may increase initially when power is applied and when motion is detected.  Regardless, this is an insignificant fraction of a 2 Amp power supply.
Likely the Atmel 328p will require several times the total current of the 3 PIR sensors added together.  Still, the over all current of the described project (1 processor and 3 PIRs) is expected to be far less than half the capacity of a 2 Amp power supply.
It is suggested to keep the PIR to Arduino wires as short as possible to avoid noise.  It would be preferable they only be several inches (10s of centimeters).  And certainly not as long as several feet (a meter).


text:
how to detect when a transmitter is turned off?
Using the nrf24l01 wireless module I want to control a led with the sketch below.
The transmitter automatically sends data at intervals of one second continuously and when the receiver counter reaches 2, it turns on the LED at the desired time and then turns it off.
but what I want is when I turn off the power of the transmitter when 2 counts are detected from the transmitter, the led does not light up.
I want to turn the led on and off when I turn off the power of the transmitter after sending 2 signals from the transmitter.
Thank you for all the information you provide.
#include "nRF24L01.h"
#include "RF24.h"
#include "SPI.h"
int ReceivedMessage[1] = {000}; //  NRF24L01 tarafından alınan değeri saklamak için kullanılır
RF24 radio(3, 4); //  NRF24L01 SPI pimleri. uno'daki Pin 8 ve 9
const uint64_t pipe = 0xE6E6E6E6E6E6; // 2 NRF24L01 arasındaki iletişim için aynı olması gerekir

int led = A7;

bool flag = false;
bool ledflag  = false;
unsigned long  previous1 = 0;
unsigned long  interval1 = 5000;

unsigned long  previous2 = 0;
unsigned long  interval2  = 2000;
int button1PushCounter = 0;

void setup () {

  radio.begin(); // NRF24L01'i başlatın

  radio.openReadingPipe(1, pipe); // NRF24L01'i almaya hazır hale getirin

  radio.startListening(); // Bilginin alınıp alınmadığını görmek için dinleyin

  Serial.begin(9600);

  pinMode(led, OUTPUT);

}

void loop () {

  unsigned long currentmillis = millis();
  while (radio.available())
  {
    radio.read(ReceivedMessage, 1); // NRF24L01'den bilgileri okuyun

    if (ReceivedMessage [0] == 111) //  switch'e basıldığını gösterir
    {

      button1PushCounter++;
      Serial.println( button1PushCounter);
      delay(700);
    }

    if ( button1PushCounter == 2) {

      flag = true;
      previous1 =  currentmillis;

    }

    if ( flag ) {
      if (currentmillis - previous1 >= interval1  ) {

        digitalWrite(led, HIGH);
        ledflag  = true;
        previous2 =  currentmillis;
        flag = false;
        button1PushCounter = 0;
      }
    }

    if ( ledflag && (currentmillis - previous2 >= interval2  )) {
      digitalWrite(led,  LOW);
      ledflag  = false;

    }
  }
}

what problem are you seeing?

@ -jsotola when i turn off the power of the transmitter, the receiver does not light the led with the detecting data

it seems to me that you used a lot of words to ask how to detect when a transmitter is turned off?

This is what happens when the problem is not knowing the language

you already have the code ... just rearrange it a bit ... basically implement a watchdog timer ... when signal is received, store the value of millis ... if the difference between stored value and millis() is more than 1 second, then the signal did not arrive

I don't know how to do it with watchdog unfortunately

no, not a hardware watchdog timer ... just use software

I did as you said, but failed.It works when the power supply is on. It does not work when I turn off the power supply.

your code only runs if while (radio.available()) ... i am guessing that radio.available() may be false when the transmitter is turned off

Unfortunately, I couldn't run it according to this library.

I fixed the problem with the for loop

I found solution as below:-
if ( button1PushCounter == 3 ) {

  for (int i = 0; i < 5; i++)
  {
    delay(1000);
    Serial.println(i);
    a = HIGH;
  }
}

if ( a == HIGH ) {

  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led,  LOW);
  a = LOW;
  button1PushCounter = 0;
}


text:
Variable Fan Controller - Properly Sized Transistor
I would like to a build a temperature sensing variable speed fan controller for my truck. Currently using a purchased 2 speed on/off relay based controller, but my fans are overloading the whole circuit when the controller is powered on during a high speed temperature scenario. On low speed, I have the fans wired in series to spin both slower - works great. Each fan initially draws 100 amps at full 12v. On the low speed (6v/series), they cruise about 20a together. On high speed, they settle in around 25a each.
I am somewhat experienced with arduino and using a few references to build in specific features I want, but here is the main example I am going by.
https://circuitdigest.com/microcontroller-projects/automatic-temperature-controlled-fan-project
My question is around the type and size of transistor that I would need to handle the amount of current these fans draw. Some examples have MOSFET while others have FET or even standard PNP. I am pretty new to working with transistors and can't find any references that make sense. Would love to get a reference to learn this calculation and appropriate type.
Edit: removed picture with incorrect wiring diagram.

You would typically have a bank of parallel power MOSFETs with a big heatsink.

the arduino cannot induce current flow into the base of Q1 because the arduino ground is not connected to the emitter of Q1 ... therefore Q1 will not turn on

@jsotola I didn't catch that before linking to that picture. Thanks for pointing out, though it's not my question. Removed the picture.

The easiest might be to use a solid state relay. There are devices for DC and they often can be controlled directly with 3.3V or 5V. In any case, thermal management will play an important role

Doing a quick search for high-current MOSFET transistors, I ran across the following:
https://www.digikey.com/en/products/detail/ixys/IXFK170N20T/2126313
The important spec here is the Rds ON (max) of 11mOhm @ 60A, 10V
At your peak current of 100A, you would drop 1.1V across the transistor, for a power dissipation of 110W.
The advertised P(max) is 1150W, so assuming the junction temp can be held to under 175C (and with an entire metal truck to use for a heat sink, this shouldn't be a problem) you should be OK with this device.  In the 'cruise' configuration with 25A motor current, you should have no problem controlling the fans.
YMMV ;-)

Your answer is fine, but as the OP mentioned to have little experience with transistors, I want to add that this mosfet can't be controlled with qn arduino's logic level and needs an additional drive circuit

Good point - thanks for the addition!


text:
Can't detect I2C displays with Arduino Nano
All cables tested and work:
SCL - A5
SDA - A4
VCC - 5V
GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

This is the code I used, i2c_scanner, and this output:
Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

... is all I get.
Any suggestions, or is my board output fried?

To use i2c you normally need pullup resistors on sda and scl, except if the slave device has some. Add 2 pullup resistors to your circuit (you can use 10k, that should be ok).

You need to understand how I2C works first.

@ChetanBhargava what has he misunderstood?

You seem to have two issues here:

As already pointed out, you have the white wire connected to the wrong pin on the Arduino
Also, you need to solder the headers on the Arduino. There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers

Agreed absolutely. Shoving the header pins into the holes simply won't work. You must solder them.

Check the solder jumper on the display. Note the example code is for one address, but two addresses are supported. Try the other address in code, or solder the LCD address pads to select the address to match the code. I had the same problem, the printed address on the LCD solder pads is just the last address bits that make the difference.

I had the same problem, with a lot of time lost, I tried to give current from another source, (an Arduino one) is all works, I think these Nano clones have some bugs on output voltages, to be checked. Anyway, so it worked.

I am not sure if this is an answer, or a comment.

@Greenonline You could flag it as "not an answer", but it will probably be declined and you'll be told the reason is - flags should not be used to indicate technical inaccuracies, or an altogether wrong answer. In my opinion, if a person is going to answer a 3 year old question that the OP has abandoned, it better be a good answer. This answer does not address any of the issues that are clearly visible in the OP's picture, not does it point out the incorrect wiring. You could try flagging it as "very low quality" and see what happens.

@VE7JRO - Good point, I had flagged it as "Not an answer" but I have retracted it, for the reasons you state, although it would serve better as a comment. I'll leave it be, even though the obvious answer is that of Anonymous Penguin, as I don't want to earn any more declined flags :-). Also, I am not sure why there are two answers from the same user.

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


text:
More flash memory with SD card
I am pretty sure that everyone have seen the low flash memory error, the same I have got while making my raycaster. So, I was thinking that is there any way to increase the flash memory of ESP32 with an SD card?
I'll connect an SD card module to ESP32 and I'll have 4GB of flash memory. Is there any way? The SD card should act as an external flash memory in any way.

Have you try to change the partition scheme setting (from IDE, tools->partition scheme)? If you don't use OTA, you could allocate more flash memory to your code. SD card is more for storing data, it does not help if you are running of program space.

I did but my code exceeded even that limit and there is much to add to my 3d game

Is there any way to use a sd card as my flash memory

There are ESP32 boards with 8MB or even 16MB available in the market. Or replace your existing flash chip with bigger one if you are capable of doing electronics hack (provided the module use external flash chip). Another alternative is to pick a linux box (such as Raspberry Pi) with CPU instead of a MCU for game development.

I know I can do it but if sd card could act as an storage for flash then it could help in other project . But right now I am determined to do this

Can I exchange og flash chip with the sd card

I mean sd card module ,externally without opening the steel case

You need to understand how MCU work. For MCU, program is directly executed in flash memory, only variables get load into RAM, it is therefore does not load program from storage such as SD card. For CPU (like your PC or Raspberry Pi), program is loaded from storage (hard disk, usb, sd card, whatever) and execute in RAM.

Actually I found a code to do the same thing.should I send it??

You should be able to use the Huge APP partition scheme:

Reference: [Solved] Increasing the flash memory size Using Partition in ESP32....


text:
Arduino keypad shield with motor
I bought an Arduino keypad shield.
I want to operate a DC or servo motor when I press button on the keypad shield.

In image, I connected keypad shield with an Arduino Uno by wiring up J1, J2, RW, E, RS, D4, 5, 6, 7, 5V, GND, GND and A0.
I checked that the keypad shield is operating normally with only these 13 connected.
But is it possible to operate a DC or servo motor when I press button on the keypad shield?
If so, where should I connect the motor?

No, you can't connect a motor or servo directly to the LCD/keypad shield.
You will also need an Arduino Motor shield, for a motor, something like this:

or an Arduino Servo shield, for a servo, something like this:

As can be seen from the photo, the motor shield is stackable, allowing you to have you LCD/keypad shield on top (the screw terminals will be accesible, although you will probably have trouble using the header pins).
However, the servo shield isn't (generally) stackable, due to the servo(s) plugging into the header pins on the top. You would have to use DuPont jumper leads to connect the LCD/keypad shield at the same time.
Note: For the servo shield you have to supply additional current (see the screw terminals bottom left), and maybe the same for the motor shield. The Arduino by itself (or rather its power supply) can't really supply enough power to move a motor.

Then, you mean that Arduino Uno board can't operate the motor by receiving a button from LCD without the parts you introduced? Here, motor is connected to Arduino Uno.

"Here, motor is connected to Arduino Uno." Here? Where? Is there meant to be a link? Anyway, for the servo shield you have to supply additional current (see the screw terminals bottom left), and maybe the same for the motor shield. The Arduino by itself (or rather its power supply) can't really supply enough power to move a motor


text:
wdt reset cause:4, boot mode:(3,6)
I'm working on Python and nodeMCU with websocket connection.
So, I send a string from Python to nodeMCU and nodeMCU collects the string and decodes to set values to a stepper motor. Initial code worked fine before updating with stepper motor code. Now it triggers watchdog resets.
Here's my full code:-
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AccelStepper.h>

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 8  // clk+
#define stepPin 9  // cw+
#define motorInterfaceType 1

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

const char ssid[] PROGMEM ="PencoNetwork2";    //change it to your wifi SSID
const char password[] PROGMEM ="Penco1234567890";    //change it to your wifi password

AsyncWebServer server(80);
AsyncWebSocket ws("/test");

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

  WiFi.begin(ssid, password);

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

  Serial.println(WiFi.localIP());

  ws.onEvent(onWsEvent);
  server.addHandler(&ws);

  server.begin();

}

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){

    Serial.println("Data received: ");

    for(int i=0; i < len; i++) {
//          Serial.print((char) data[i]);
           String data_String = (String) data[i];

          int commaIndex = data_String.indexOf(',');
          int secondCommaIndex = data_String.indexOf(',', commaIndex+1);
          String firstValue = data_String.substring(0, commaIndex);
          String secondValue = data_String.substring(commaIndex+1, secondCommaIndex);
          String thirdValue = data_String.substring(secondCommaIndex+1); //To the end of the string

          int mDist = firstValue.toInt();
          int mspeed = secondValue.toInt();
          int mAccel = thirdValue.toInt();

          stepper.setMaxSpeed(mspeed);
          stepper.setAcceleration(mAccel);

          stepper.moveTo(mDist);
          stepper.runToPosition();
          delay(1000);
          stepper.moveTo(0);
          stepper.runToPosition();
          delay(1000);

    }

//    Serial.println();
  }
}

void loop(){

  }

It would be a great help pointing out my mistakes.

Does stepper.runToPosition(); block the code from continuing until the stepper has moved into position? wdt reset cause:4 is a hardware watchdog crash type, and occurs because your ESP8266 has been busy for too long without giving control back to the underlying RTOS. IIRC, it fires for perceived 'lockups' of approx 8 seconds. You can try scattering a few yield(); in your onWsEvent function and see if that helps.

You're calling delay() in the onWsEvent() callback. The ESPAsyncWebServer documentation specifically says not to do that in the 'Important things to remember' section:

You can not use yield or delay or any function that uses them inside the callbacks

When you call delay() or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.
The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in loop().
For instance,
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){

and
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){
    flag_move_stepper = true;

    // you'll need to rewrite this code to share variables with `loop()` and do the work there

and
void loop(){
  if(flag_move_stepper) {
    flag_move_stepper = false;

    // do the work formerly in onWsEvent() here
  }

}

You'll need to make the variables you stored data in in the event handler available to loop() and move the stepper code there for this to work.


text:
One of my my buttons is interfering with the other (i think)
So for school i have to make a code for my arduino, that let's me turn 4 led's on and off (as an input) with 2 buttons (one to select the led, one to toggle the led), run the inputs trough a logic circuit and based on the output toggle a fifth led on or off. The only thing i can't manage to get working is the button that turns the leds on and off. My main problem is that if i want to let the second button (setButton) do anything, i have to hold it down and press the other button which then kind off controls setButton & inputButton at the same time..
so my main question: How do i make my setButton work in this script..
(sorry for the Dutch comments inbetween)
int led1 = 5;                    // van links naar rechts: led 1
int led2 = 6;                     //led 2
int led3 = 9;                    //led 3
int led4 = 10;                     //led 4
int ledRuben = 3;                  //led 5 (geeft de output aan)
const int inputButton = 7;         //select a led/input mode on
const int setButton = 8;       //toggle a led
int buttonState1;                 //inputButton state
int buttonState2;                 //setButton state
int pushCount = 0;                //how many times the button is pushed (used to select the right led)
int lastButtonState1;           //last inputButton state
int lastButtonState2;           //last setButton state
int inputLeds[4] = { 0, 0, 0, 0 };  //used to save the signal needed for the logic gates
char currentLed[4] = { led1, led2, led3, led4 }; //used to select a led
int i16, i09, i61, i34;           //inputs
int t16, t09, t61, ruben;          //in between and end signals
int ledState = false;              //current led on or not

void setup() {
    Serial.begin(9600);     // hoe veel data er verstuurd wordt.

    pinMode(ruben, OUTPUT);
    pinMode(led4, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led1, OUTPUT);
    pinMode(inputButton, INPUT);
    pinMode(setButton, INPUT);
}

void loop() {
    buttonState1 = digitalRead(inputButton);
    buttonState2 = digitalRead(setButton);

    if (buttonState1 != lastButtonState1) {

        if (buttonState1 == HIGH && pushCount == 0) {
            analogWrite(led1, 125);
            analogWrite(led2, 125);
            analogWrite(led3, 125);
            analogWrite(led4, 125);
            Serial.println(pushCount);
            pushCount = pushCount + 1;
            delay(200);

        }
        else if (lastButtonState1 == HIGH && pushCount >= 1 && pushCount <= 4) {

            if (buttonState2 == HIGH && lastButtonState2 == LOW && ledState == false) {
                analogWrite(currentLed[pushCount], 255);
                inputLeds[pushCount] = 1;
                Serial.println("test 2");
                ledState = true;
            }

            else if (buttonState2 == HIGH && lastButtonState2 == LOW && ledState == true) {
                analogWrite(currentLed[pushCount], 1);
                inputLeds[pushCount] = 0;
                ledState = false;
            }

            Serial.println("test");
            Serial.println(pushCount);
            pushCount = pushCount + 1;
            lastButtonState1 = buttonState1;

        }

        if (buttonState1 == HIGH && pushCount >= 5) {
            Serial.println(" currentLed > 4;");
            pushCount = 0;
            delay(200);
            return; 55
        }

        circuit();                                        //zorgt dat void circuit gerunt word.
        if (ruben == 1) {                                  //Als output ruben 1 is, wordt ledRuben aangezet.
            analogWrite(ledRuben, 255);
        }
        else {                                            //als output ruben 0 is zet ledRuben uit
            analogWrite(ledRuben, 1);
        }

    }

    lastButtonState1 = buttonState1;
}
void circuit() {                   //logic gates
    t16 = !i16;                     //Dit is de NOT gate, maakt van output 1 een 0, en andersom
    t09 = t16 && i09;               //Dit is de AND gate, als alle inputs 1 zijn, is de output 1
    t61 = i61 || i34;               //Dit is de OR gate, alleen als alle inputs 0 zijn, is de output 0
    ruben = !(t09 || t61);           //Dit is de NOR gate, alleen als alle inputs 0 zijn, is de output 1

    return ruben;
    5
}

You might want to look at putting you LED pin numbers into an array, or rather using the one you already have.  led1 is the same as currentLed[0]  Apart from the type of the array is not strictly correct.

Thanks for the tip, i gues you're right because now i'm just using more variables then needed. But do you have any idea how to fix the button issue?

lastButtonState2 never changes in your code.

@gerben i added lastButtonState2 = buttonState2; to both the if and else if that should toggle the button, it didn't change anything tho..

Can't you just move the button2 code out of the if button1 block, and directly into the loop function?

lastButtonState2 still never changes in your code!

@gerben thanks to you i've fixed it! i put
if (buttonState1 != lastButtonState1) {
around the button2 if/else, ending with
lastButtonState2 = buttonState2;
}

Do you use a pullup or pulldown resistor for your buttons? If not, then add one or use pinMode(..., INPUT_PULLUP). Second, you probably have to debounce your buttons (by software or hardware), Google is your friend to find out how.

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


text:
Arduino serial controlled tone generator only working with single digit ints?
I'm writing a small program for my arduino which allows me to send two int values over serial to be interpreted. The first is a frequency Hz value and the second is a a length milsec value.
The code works, and plays the correct tone for the correct amount of millis, but only for single digit integers. If a double or more digit integer is sent then the arduino loops through the code several times and plays the wrong tone.
Here is my code:
const byte LED = 13; /* LED Pin */
const byte SPK = 12; /* Speaker Pin */
const int BAUD_RATE = 19200; /* Baud Rate of Input */

void setup(){
  pinMode(LED, OUTPUT);
  pinMode(SPK, OUTPUT);
  Serial.begin(BAUD_RATE);
  Serial.setTimeout(0);
  tone(SPK, 1000);
  delay(200);
  noTone(SPK);
  Serial.println("System ready for data");
}

void loop(){
  Serial.println("tone");
  while(Serial.available() == false){
    delay(0);
  }
  int toneToPlay = Serial.parseInt();
  Serial.println("delay");
  while(Serial.available() == false){
    delay(0);
  }
  int delayValue = Serial.parseInt();

  tone(SPK, toneToPlay);
  delay(delayValue);
  noTone(SPK);
}

Expected result is the ability to enter any tone and delay and the arduino plays it then asks for another tone and delay.
Any help is much appreciated.
EDIT: Here is my new code. It does what I want, the only issue is there is a pause after I type the tone value before it asks for the delay value, and a pause after the delay value before it plays the tone. I can't have this delay as data will eventually be sent by a piece of software to the arduino. How can I fix this delay? New code:
const byte LED = 13; /* LED Pin */
const byte SPK = 12; /* Speaker Pin */
const int BAUD_RATE = 19200; /* Baud Rate of Input */

void setup(){
  pinMode(LED, OUTPUT);
  pinMode(SPK, OUTPUT);
  Serial.begin(BAUD_RATE);
  tone(SPK, 1000);
  delay(200);
  noTone(SPK);
  Serial.println("System ready for data");
}

void loop(){
  Serial.println("tone");
  while(Serial.available() == false){
    delay(0);
  }
  int toneToPlay = Serial.readString().toInt();
  Serial.println("delay");
  while(Serial.available() == false){
    delay(0);
  }
  int delayValue = Serial.readString().toInt();

  tone(SPK, toneToPlay);
  delay(delayValue);
  noTone(SPK);
}

What do you mean by delay(0)? 2) Have you tried typing faster?

Try non-blocking read to a buffer instead. Build a string to convert to an integer. And check how parseInt() works. There is a timeout! This might not be sufficient.

@EdgarBonet the delay(0) is a time filler which make the arduino do something while it waits for serial data. I can't type fast enough, I get five requests within a fraction of a second.

@MikaelPatel Non-blocking read buffer?? Whats that?

@MikaelPatel I know there is a timeout. I tried to turn off the timeout at the start of the code with Serial.setTimeout(0). I'll try the string thing now.

This “filler” serves no useful purpose. You can just remove it, your code will only be cleaner. 2) If you really did setTimeout(0), then of course you cannot type fast enough! You have just asked Serial to wait no more than 0 milliseconds for you to type the digits.

The Arduino readString, parseInt() etc functions are inherently flawed in the way they work. Don't use them if you value your sanity. Read this for how to do it properly: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Hint: How does it know when you've fished typing your number and there are no more digits to follow?

@Majenko I'll try this later


text:
Get image from Arduino Ethernet Shield sd card
I have a code that uploads the temperature and humidity from a dht22 to a website.
Now i want to add an image to the "add to homescreen" button in safari on ios.
Apple has a html code for this:
<link rel="apple-touch-icon" href="/custom_icon.png">

Now I want the "custom_icon.png" to be a link or some other method to a file "Icon.png" on the ethernet shield sd card.
I think I need something like this:
client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png\">");

But this doensn't work. It doesn't give an error, but its just the wrong way to acces that file.
I tried using the SD.h library but I am not able to use the library for my code. This is my code.
#include <dht.h>
#define dht_apin A0

#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>
#include <LiquidCrystal.h>

File root;
// initialize the library with the numbers of the interface pins

byte mac[] = {I HIDE THIS};   // physical mac address
byte ip[] = {I HIDE THIS};                        // ip in lan (that's what you need to use in your browser. ("I HIDE THIS")
byte gateway[] = {I HIDE THIS};                   // internet access via router
byte subnet[] = {I HIDE THIS};                  // subnet mask
EthernetServer server(10000);                          // server port
String readString;
dht DHT;
int Temp;

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
   while (!Serial) {
    ;
  }
  delay(100);
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");

  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

    Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

 Serial.println("done!");

}

void loop() {

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

        if (readString.length() < 100) {    //read char by char HTTP request
          readString += c;
         }

         if (c == '\n') {      //if  HTTP request has ended
          Temp = 0;
  switch (Temp){
  case 0:
           DHT.read22(dht_apin);
           Serial.print("Vochtigheid = ");
           Serial.print(DHT.humidity);
           Serial.print("%  ");
           Serial.print("Temperatuur = ");
           Serial.print(DHT.temperature);

           delay(500);

           File dataFile = SD.open("Icon.png");

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println();
           client.println("");
           client.println("");
           client.println("<TITLE>Home Damian</TITLE>");
           client.println("<meta http-equiv=\"refresh\"content=\"1 \">");
           client.println("<meta name=\"apple-mobile-web-app-title\" content=\"Home\">");
           client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png"/>");
           client.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
           client.println("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
           client.println("");
           client.println("");
           client.println("
");
           client.println("
Temperatuur =
");
           client.println(DHT.temperature,1);
           client.print("&#176C");
           client.println("

");
           client.println("
Vochtigheid =
");
           client.println(DHT.humidity,1);
           client.print("%");
           client.println("
");
           client.println("");
           client.println("");

           delay(1000);
           Serial.println("OK");
           Temp = 0;
           client.stop();

         }
       }
     }
   }
  }
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

Are Apple computers missing the function for copy pasting the code?

Try a simpler file name e.g. ICON.PNG. The SD library might not support extended names.

You have to write code that responds to the http request for the image and load the image (using the SD library) and pass it on to the web browser in the right format.

@gre_gor yeah sorry for the screenshot, i asked the question on my phone and had that screenshot.

@Majenko Do yo have code? I don't find my way

http://www.websiteoptimization.com/speed/tweak/inline-images/

Really nobody that just can give me the code

No, nobody can just give you the code. Write your code. We told you what you need to do. We do not hand out code willy nilly, especially not to people who post screenshots of a fraction of the code they have.

Here is a picture of my answer.

@Majenko okey, sorry your write. I'll post my code to but please help me. I really need it and I dont understand that part. Really sorry. But your image inswer tho? Haha thats really not needed ;)

@Majenko I added the code

The Arduino uses the 8.3 File Format. meaning that your filename must not be more than 8 characters and the file extension must not be more than 3 characters.
eg:
picture1.png
12345678.123
Hope that helps.
I have been toying with this for the last few days, and managed to find out that it uses the 8.3 format.
Also the index.html must also be in the 8.3 format.
so index.htm
Hope that helps.

You are reading the HTTP request into readString. You need to parse that request to see what is actually being requested.
If the URL being requested is "icon.png" then you need to open the file on the SD card and send the data back as a properly crafted HTTP response - something in the form:
HTTP/1.1 200 OK
Content-type: image/png
Content-length: <file size here>
Connection: close

<Raw PNG data>

The first line of the readString will contain the request:
GET HTTP/1.1 /icon.png

You needt to split that up and find what the request is. You could trap specific entries (/, /index.html, etc) and serve those as specifically crafted responses, and all other unmatched requests you could forward on to your SD card reading code. You should, though, extract the file extension and match it to a MIME time so you can set the Content-Type header correctly.


text:
How can I stock data, and send them over by serial?
I want to make an array with data from the sensor. In data, I have displacement in x/y axis. I want to send them in the array, because in my python code I don't send them one by one, slow down really quickly program.
Arduino code responsible for sensor
class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    Serial.print(mi ->dX, DEC);
    Serial.print(",");
    Serial.println(mi ->dY, DEC);

};

I tried to do something on my own, but I get stuck with an error about data not in the scope. I try some variant placing it, but I don't succeed .
class MouseRptParser : public MouseReportParser {

 void OnMouseMove (MOUSEINFO *mi); };

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{ int i;   for (i=0;i<10;i+2)   {
        data[i]=(mi ->dX, DEC);
        data[i+1]=(mi ->dY, DEC);   }
  Serial.println(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9]);

    delay(20); };

EDIT:  I have now program that's making an array of 10 cells, but values in it are constatnt 10.
#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
int data[10];

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    for (int i=0; i<10; i=i+2)
  {
    data[i]=(mi->dX, DEC);
    data[i+1]=(mi->dY, DEC);

  }
  for(int j=0; j<10; j=j+1)
  {
  Serial.print(data[j]);
  Serial.print(",");
}
Serial.println();
  delay(100);
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
    Serial.begin( 9600 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    //Serial.println("Start");

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

    HidMouse.SetReportParser(0, &Prs);
}

void loop()
{

  Usb.Task();

}

There is no such thing as "all at once" with serial. The whole point of serial is that it sends things one character at a time.
It is entirely up to you to decide what constitutes one "block" of data.
There is absolutely no difference (besides some slight processing overheads) between:
Serial.print("Hello");
Serial.print(" ");
Serial.println("World");

and:
Serial.println("Hello World");

Both of them result in Serial sending:
H
e
l
l
o
[space]
W
o
r
l
d
[cr]
[lf]

No matter how you "batch" stuff together (or attempt to) it makes no difference.
You need to have:

Some way of identifying the start of a block of data,
A mechanism to receive the entire block a byte at a time, and
Some way of identifying the end of a block of data.

How you do that is entirely up to you.

Here's an example of how to arrange the storage:
class MouseRptParser : public MouseReportParser
{
    private:
        int dx[10];
        int dy[10];
        int dpos = 0;

    protected:
        void OnMouseMove (MOUSEINFO *mi) {
            dx[dpos] = mi->dX;
            dy[dpos] = mi->dY;
            dpos++;

            if (dpos == 10) {
                dpos = 0;
                for (int i = 0; i < 10; i++) {
                    Serial.print("X");
                    Serial.print(dx[i]);
                    Serial.print("Y");
                    Serial.print(dy[i]);
                }
                Serial.println();
            }
        }
};

What that gives you is a pair of 10-entry arrays, one for X and one for Y values. Each time a report arrives the current DX and DY values are stored. The pointer for where to store is incremented.  Then, if that pointer equals 10, reset it to 0 and print all the values.
I chose a format that gives you:
X3Y-2X2Y-4X6Y8X-3Y7X6Y38X176Y76X-4Y8X8Y3X39Y-32X71Y4

That is, an "X" followed by a decimal value for a change in X, and a Y followed by a decimal value for a change in Y. The whole lot is then terminated by a standard CR/LF line ending pair.

OK. I get it. I just need a a way to storage data, and send them over. I have now code to make an array of 10 elements and send them in loop, but its sending constant value. Check my edit post.

@Trzywu I don't think you are clear in your own mind exactly what you are trying to achieve. At the moment you take the X/Y coordinates and save them 5 times each in an array: x,y,x,y,x,y,x,y,x,y. Then you print those. What do you actually want to do? What data do you want to save? When do you want to send that data to the PC?

I want to send data in format like this x1,y1,x2,y2  and so on to x5,yy or x10,y10.  I want them send in some delay, i will figure out exact number when i get this portion of data.

So you want to store 5 coordinate pairs, and only when you have gathered 5 pairs do you want to send them to the PC. So you need to have some concept of how many pairs you have received, and only store the current pair in the current slots of the array. Only when the array is full do you do anything with Serial.

Please, can you be more specific?  I am reserving storage in this line"int data[10];" and  saving for respective cell here  " for (int i=0; i<10; i=i+2)
{
data[i]=(mi->dX, DEC);
data[i+1]=(mi->dY, DEC);
}"
Or am i missing something?

You are saving in every cell from 0 to 10. You do not want a for loop there. You just want some variable to say where in the array you currently are, and increment it only once for each report you receive. Only when the array is full (current == max) do you print the contents and reset the "current" pointer to the start of the array.

@Trzywu I have added an example to my answer.

Thank you, i was sleeping over.  I change some code to have specified character to split in.  Once again thank you very much.


text:
Help me determine the power consumption/rating of the circuit below?

Please help me determine the circuit's power consumption from the battery and help me outline the steps to calculate?

Battery power consumption is a tricky engineering problem.  Many estimate then find them selves to be way off.  Especially when using ultra low current processors (processors which support sleeping features).  Added complexities may result when assumed features are unavailable in various levels of sleep mode.  Like, for instance, an accurate clock.  Further, special considerations are necessary when designing for low power consumption.   Simple things like not using pull up or pull down resistors can spell the difference between an extra hour to extra days of operation.

Use a multimeter to measure it in its different states (relay on/off; MCU in sleep mode, etc)

Why the frog are you using a TIP122 to switch the gate of a MOSFET?!?!

You can use higher values for r5 and r6, for example 100k and 10k. Don't connect aref to vcc. The crystal requires two 22pf capacitors. pd5 to q1 is missing a resistor. The buzzer might be inductive. Are those soil moisture sensors resistive or capacitive? If they are the resistive type, they will become useless very quick. What kind of battery is it? Are you relying on your programmings skills to prevent that the battery will be charged too much? The omih-sh-124l is a 24V relay and requires a minimal voltage of 18v.

It's not a simple matter of "calculating the power". Instead you need to:

Calculate (or obtain) the current consumption of each individual sub-module or component
Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
Calculate the current consumption of static items such as voltage dividers and power LED

Then:
For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.
And finally:
Sum up all the average hourly usages to get a final AH value for the whole circuit.
Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.
Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.


text:
Button Matrix Code and Wiring

Bear with me here, I'm new to arduinos, so what I'm saying might only make sense in my own mind.
I'm trying a button matrix and I not completely sure on my wiring and I have a few questions.

Is the diagram correct?
I wire D2 to D3 and set them to output and input respectively. In the code I digital write to D2 a HIGH, will D3 then read high?
What is the best way to read the state of each button? Is there a Library that can simplify it?

I'm sorry if this is all just confused gibberish.
EDIT: I got the idea from this video, which explains some of it, but no code. He however uses an arduino micro.
EDIT #2: I realized I wired the buttons incorrectly.

Is this what you are looking for: https://playground.arduino.cc/Code/Keypad

you are using 4 wires to read 4 switches .... you could just use one pin for each switch ..... enable internal pullups on the pin and connect the switch between the pin and ground

@Jot commented to use the Keypad Library. Which I got to work using the tutorial. Took a few minutes to set up.