text:
Pilot the the reset line by two input
I have two input signal that when activated have to restart the ardiuno board so I have to connect them to the RESET pin. As you know the arduino board have only one RESET pin so I can't connect both to the same pin.
I think that a good idea is a circuit that takes the two inputs and activate the RESTART pin when one of the two is active.
Have you any idea to solve that problem?
Thank you.

use a logic IC (OR gate) or two reset lines in parallel with appropriate resistors.

Can you tell us why? What are those signals and why do you want to reset the arduino? Such questions might be the xy-problem: http://xyproblem.info/

Just use diode logic.
The resistor is probably not needed because the Arduino has an internal pullup resistor.
This assumes that the two reset inputs are active low

simulate this circuit – Schematic created using CircuitLab

This seems like the simplest solution. (Voted)

What you want is an AND gate (e.g., 74HC08, which contains 4 AND gates).
An AND gate is a chip which sets its output HIGH when both inputs to it are HIGH.
Symbolically it looks like:

simulate this circuit – Schematic created using CircuitLab
This, of course, is assuming that both your reset signals are active low - that is, they are normally in the HIGH state, but when they want to reset the board they go LOW.
You can do the same thing with three transistors.  Two transistors in series make a NAND gate (like an AND gate but the output is inverted), and a third makes a NOT gate to invert the output:

simulate this circuit
Note that R4 is optional, since the RESET pin already has a 10KΩ pullup resistor in it.


text:
WebClient Not Working On Shared Network
I'm working on a school project, and I use Arduino Uno to collect some data with sensors, and then send it to an online database. The Arduino is connected to the Internet via an Ethernet Shield and an Ethernet cable. I connected the Ethernet cable to my home router, and to the Arduino and everything works fine, the data is colledted, and sent to the database. But when I will present the project I won't have an access directly to a router, so I have to connect my laptop to WiFi and connect the Arduino to my laptop and share network. When I tested this it just did't work, I changed the Wifi network properties on my Windows 10 Laptop, to a shared network. The Arduino boots up and optains an IP adress, but when it tries to send data to the database it it doesn't work. I connected it to the home router again and everything worked so the problem is with the shared network. What is the problem? And how to solve it?

If the problem is with the shared network then you should head over to SuperUser.com - they know all about Windows and networking.  If you're getting an IP address and a gateway address and DNS address then the Arduino is fine. The problem is with Windows and we can't help you there.

can you reach the database server from the laptop?

@jsotola yes I can.

source: Stack Exchange

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

sort: votes


text:
Arduino to check if digital connected to analog
Is it possible to check if a Analog pin is touching a digital?
I have an Arduino Uno, and I want to have a small matrix, A0 A1 A2 A3 (all have rows of 6 buttons)
All the 6 buttons are connected to the digital pins
This is how I want it to work
Digital (1,2,3,4,5,6)
(A0)1,2,3,4,5,6
(A1)1,2,3,4,5,6
(A2)1,2,3,4,5,6
(A3)1,2,3,4,5,6

I've tried writing code but for each key pressed it gives the same value for each row i.e it's not detecting different sections.

https://playground.arduino.cc/code/keypad

please post your code so that we can check for errors

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


text:
Why is dtostrf() not working for this one value?
I'm building a weather station using an ESP32 and BME280. I'm feeding the data via MQTT and Python into a database that is then used to make a nice dashboard for the data.
The MQTT message needs to be a char, and the sensor readings are floats, so I'm using dtostrf() to convert them. This works fine for the temperature and pressure readings, but for some reason not for the humidity reading.
I declare my variables:
float temp;
float hum;
float pres;

char mqttTemp[6];
char mqttHum[6];
char mqttPres[5];

Then I get my readings:
temp = mySensor.readTempC();
Serial.print("Temp: ");
Serial.print(temp);
hum = mySensor.readFloatHumidity();
Serial.print("Hum: ");
Serial.print(hum);
pres = mySensor.readFloatPressure();
Serial.print("Pres: ");
Serial.print(pres);

This returns:
Temp: 25.57 Hum: 40.15 Pres: 97684.39
Then I run the results through the function:
dtostrf(temp,4,2,mqttTemp);
dtostrf(hum,4,2,mqttHum);
dtostrf(pres,5,0,mqttPres);

Then I output these to Serial:
Serial.print("Temperature: ");
Serial.print(mqttTemp);
Serial.print("Humidity: ");
Serial.print(mqttHum);
Serial.print("Pressure: ");
Serial.print(mqttPres);

Which gives me:
Temperature: 25.57
------------------------------
Humidity:
------------------------------
Pressure: 97684

There is also no message sent via MQTT for humidity, but it works perfectly for the other two readings. What gives?

Using a esp32 and trying to squeeze an array to the very last byte and beyond? That makes no sense. Can you make the char arrays 16 bytes each (or 20 or 100 bytes). The size for dtostrf is the minimum size, plus perhaps a negative sign, plus zero terminator, plus some extra for safety, that makes a lot more than just 6 or 5. What if the sensor is disconnected and some error values are returned and those errors are converted to text?

two basic errors - 1) you haven't declared the variables with enough room for the data they need to contain, and 2) you're using dtostrf incorrectly (the width of temperature is at least 5, or 6 if you can get temperatures at -10.00 or less, and the width of humidity is at least 6, since 100.00 is 6 characters

What is happening is that the variables you declared for mqttTemp etc are stored in memory something like this
variable   memory address
mqttPres @ 1000-1004 (5 bytes)
mqttHum  @ 1005-1010 (6 bytes)
mqttTemp @ 1011-1015 (6 bytes)

For a start, you only have enough room (with the mandatory NUL byte string terminator) for 4, 5 and 5 characters
When you convert pressure, the NUL byte is being placed as the first byte in mqttHum, therefore, when printing mqttHum you get an empty string output (since the first byte is NUL)
To really see what's happening, here's some code that illustrates the issue
char mqttTemp[6] = "TTTTT";
char mqttHum[6] = "HHHHH";
char mqttPres[5] = "PPPP";
void setup() {
  float temp = 25.57;
  float hum = 40.15;
  float pres = 97684.39;

  Serial.begin(74880);
  // put your setup code here, to run once:
  delay(100);
  Serial.println("before");
  printThem();
  dtostrf(temp, 4, 2, mqttTemp);
  Serial.println("converted temp");
  printThem();
  dtostrf(hum, 4, 2, mqttHum);
  Serial.println("converted hum");
  printThem();
  dtostrf(pres, 5, 0, mqttPres);
  Serial.println("converted press");
  printThem();
}
void printThem()
{
  Serial.print("mqttPres ");
  Serial.print((unsigned long) &mqttPres, DEC);
  Serial.print(": ");
  for (int i = 0; i < 5; i++) {
    Serial.print((int) mqttPres[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttHum  ");
  Serial.print((unsigned long) &mqttHum, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttHum[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttTemp ");
  Serial.print((unsigned long) &mqttTemp, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttTemp[i], DEC);
    Serial.print(' ');
  }
  Serial.println();
}

void loop() {
  delay(50);
  // put your main code here, to run repeatedly:

}

The above outputs the following:
before
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 84 84 84 84 84 0
converted temp
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted hum
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 52 48 46 49 53 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted press
mqttPres 1073644748: 57 55 54 56 52
mqttHum  1073644753: 0 48 46 49 53 0
                     ^ ======== note the leading 0
mqttTemp 1073644759: 50 53 46 53 55 0

The simplest fix, of course, is to declare your variables with the correct size
char mqttTemp[7]; // because -10.00 takes 6 characters + 1 for NULL
char mqttHum[7];  // because 100.00 takes 6 characters + 1 for NULL
char mqttPres[6]; // because 97684 takes 5 characters + 1 for NULL - if pressure can reach 100000 then use 7 here as well

and then use dtostrf correctly, i.e. the second argument is the total width, including . and a possible -
dtostrf(temp,6,2,mqttTemp);
dtostrf(hum,6,2,mqttHum);
dtostrf(pres,5,0,mqttPres);

Thanks for a very thorough answer! I suspected I was fundamentally misunderstanding something (not least because it's my default state of being). It now works perfectly.

It is the minimal width. Why not make the arrays 20 in size instead of waiting for the next problem when the text turns out to be longer than expected?

if the temperature is above 999 or below -99 - there's a lot more to worry about @Jot - agreed though, but with the minimal sizes in the code above there can't be any issue given the data

@JaromandaX I have to disagree. I even have to disagree very strong. A bug in software should not be the cause of an avalanche of errors throughout the code. Therefor when using dtostrf, the buffer should be large enough to hold every possible float value. Preferably a buffer on the stack. In case the float value is limited, that limit should be in the code with if-statements and with a comment section to explain why a smaller buffer is possible. Perhaps that is useful in a attiny, but certainly not in a ESP32.

@Jot - I understand what you're saying, but a BME280 will not give you any values outside its measuring range, and dtostrf will "write" at most 7, 7 and 6 bytes including the NUL termination in this code - there is no possibility, in this case of the avalanche you speak of


text:
Controlling 3 Steppers exactly
Update
Here the update regarding the code I tried to program. I have a stepper with an attached disc with little holes every 45 degrees where a microswitch can rest into (hole is the exact size of the microswitch; and be in off position then). I would like the stepper to move 45 degree (until hole 1) and then (as a first step) wait for 3 seconds and then move another 45 degree to hole and stop etc.
As a next step I would like the same to be controlled via serial from another software. So I can send to serial a "move" command and then the same as described above will happen once the Arduino get the "move" command.
Below my attempt. It does do the homing, but not very smoothly and the next step (just moving 3 seconds) is a very rough movement. Here my qestions:

How can I make this move smoothly ?
How should I adapt this code to make the stepper stop once it is in the hole ?
How can I make the microswitch get out of the hole after it rests in there ?

Thank you very much for your help !
Code
#include "AccelStepper.h"

int M2dirpin = 4;  //Motor Y direction pin
int M2steppin = 5; //Motor Y step pin
int M2en=12;  //Motor Y enable pin
#define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

// AccelStepper Setup
AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
// Stepper Travel Variables
long initial_homing = -1; // Used to Home Stepper at startup

void setup() {

  pinMode(home_switch, INPUT_PULLUP);
  pinMode(M2dirpin,OUTPUT);
  pinMode(M2steppin,OUTPUT);
  pinMode(M2en,OUTPUT);
  digitalWrite(M2en,LOW);
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

  // Start Homing procedure of Stepper Motor at startup
  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    stepperX.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    stepperX.run();  // Start moving the stepper
    delay(20);
  }

  stepperX.setCurrentPosition(0);  // Set the current position as zero for now
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    stepperX.moveTo(initial_homing);
    stepperX.run();
    initial_homing++;
    delay(20);
  }

  stepperX.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");

 // Move 10 steps forward from the limit switch (to get out of the switch)
  while (stepperX.currentPosition() != 10)
  {
    stepperX.setSpeed(10);
    stepperX.run();

}
}
void loop()
{
stepper1();
}

void stepper1()
{
  stepperX.move(22);
  unsigned long startMillis = millis();
  while( millis()-startMillis<3000 )
{
  stepperX.run();
}
}

Old question:
I apologize for the high level, pseudo code question, but I am trying to understand conceptional how I can achieve the following:
I have 3 steppers (1 circular motion, 2 linear motion) which I would like to stop every time at the exact same position. The first stepper should rotate e.g. 45 degrees and stop, after which the second stepper should push down (like a linear actuator) stay at that position for a certain time and move back to the initial position, after that the 3rd stepper should also (linear motion) move to certain position and return.
These three steps would than repeat for a very long time.
Do Steppers accumulate errors in position and if yes how can I make sure that this is not happening ?
I read abut "homing" and tried microswitches, but wasn't able to combine it with the three stepper setup. Also 3D printers should always stop exactly at the same place and therefore I assumed there must be a solution for this.
Is there a template code I can start from that is similar to the setup described ?
How can I make sure these steps are done strictly after each other.
Again I apologize for the high level question, but all my attempts so far to solve this failed.
Thank you !

Stepper motors can miss steps if they experience to high a resistance (or too fast acceleration)

You could home all three steppers every time it moves back. So move forward X amount of steps, move back as many steps as needed for the limit switch to activate

How can I make sure these steps are done strictly after each other. ..... i think that you need to run a few example sketches in the Arduino IDE to get a feel for how a microcontroller operates

all my attempts so far to solve this failed ..... please add the code which you tried and a connection diagram to your post

About errors with stepper motors: Stepper motors introduce errors depending on the forces, that act upon them. For example: If your stepper does not have enough power to accellerate the attached weight, it will loose steps when trying (meaning that the rotor does not do a step despite the coils being controlled for the step). (The same of course also goes for deacceleration or moving against a barrier) Since you only know the position bei counting the steps, that you "send" to the motor, you get an error.
You have basically 2 options to prevent this from happening:
1. Choose the correct strength for motors for your application and don't overburden the motors at any moment in operation.
2. You can attach a rotary encoder to the rotor, so that you can check, if the rotor really moved the number of steps, that you instructed it to do. (Here be sure, that the numbers of steps for rotary encoder and motor match, or calculate correctly, if they don't). The position in your program would then only be updated based on the rotary encoder. This solution is more difficult, since you need extra parts and good code, that will not miss any of the rotary encoder pulses.
About Homing: Yes, this can be used to prevent the accumulation of errors during a longer operation. Also this is often used, so that the device does not have to constantly save it's current position to peristent storage. If the power is cut off, the device will forget it's position and calibrate it again after powered on again by using the end switches. Also this means, that in the powered off state it's not a problem, when the motor is moved away from it's position by outer forces.
It is unclear, how precise you need the application to be and what errors are really introduced. It may be sufficient for you to just get the position of the motors by homing, when you power your device on, and then simply letting it work. If that's not sufficient, you might do a homing cycle after every sequence. The same goes for the rotary encoder solution. It might be an overkill here, depending on the exact properties of the application.
Template code: I simply googled "Arduino stepper homing" and found some articles about it, which also contain example code. That should enable you to write code for your own application. Since you didn't really described, what your setup is, we cannot see, if this really fits your application. But Homing is the same everywhere.
Steps strictly after each other: You can just write your program to finish one part and then go on to the next (blocking code). Or, if you want it to be more elaborate and flexible, you can use non-blocking code (like in the BlinkWithoutDelay example of the Arduino library) with a finite state machine. The states could be the 3 parts of your program, or divided further. In each state you are doing only 1 thing and change to the next state, when finished. The code in each state should be non-blocking, so that it only does something, when it needs to, and else let's the program continue (for example: When moving a stepper at a certain speed, you are doing 1 step, then waiting a bit, then doing the next step and so on. While waiting you can do other things.)
You didn't mention, what your problems with the limit switches were, so we cannot help you with that. Thus this answer is as high level as your question. Hope, that helps.

Thanks for the long and detailed answer, this is very useful. I know the substeps (as described above), but seem to have problems to unify these steps into one code. Thank you anyway, I will try to find a solution.


text:
Arduino stops logging data after ~32761 seconds
I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is  32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long.
Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.
void loop() {
 String date;
 unsigned long timer;
 int freq = 60;

 sensors.requestTemperatures();
 tempC1 = printTemperature(insideThermometer, 18);
 tempC2 = printTemperature(outsideThermometer, 19);

 // start serial port
 Serial.begin(9600);

 mainMenuDraw();
 operateMainMenu();

 CurrentTime = millis();
 timer=(CurrentTime - StartTime)/1000;
 date = TimeShowFormatted(CurrentTime - StartTime);

 if (timer > logCount * freq and StopStatus == 0) {
  logCount += 1;
  LastLoggedDate=date;
  DataLogg(date);

 }
}

What's StartTime? Add rest of your code so I can simulate it please.

To increment a variable, use logCount++;

@FilipFranik StartTime is a unsigned long that is initialized at zero when arduino is started or re-initialized at zero when the logging is restarted (via menu on LCD shield)

Instead of comparing absolute times you should use the following:
unsigned long now = millis();

if(now - time_last_log >= freq){
    logCount += 1;
    LastLoggedDate=date;
    DataLogg(date);
    time_last_log = now;
    // or if you really want fixed intervals
    // time_last_log += freq;
}

This is guaranteed to be overflow proof.

This code can also fail badly. It's possible for time_last_log to be close to max value of 'unsigned long' and then it never get's updated because now is always lower. I suggest adding || now < time_last_log to the if to escape that infinite loop.

@FilipFranik: No, it will not fail when time_last_log gets close to ULONG_MAX. Owing to the rules of modular arithmetic, this code is rollover safe. Try for yourself if you are not convinced.

@EdgarBonet You broke my brain. You are right.

@EdgarBonet Thank you for your helpful insight. It is always great to learn something! I'll test today the solution and validate the answer if everything is ok.

@EdgarBonet it works well, 21h of logging and still running.thank you very much


text:
How to map integer values and round to a count of tens/thousands?
I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:
maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

I didn't yet compiled it, but something like this should work:
#include <Math.h>

int converter(int x)
{
    if(x <= 5000)
        return 1000;
    else
        return (int)(round(x / 10000.0) * 10000.0);
}

I'm not sure that's what I'm looking for....for example, if the value (x) is 2500, dividing by 1000 is 2.5...the result I'm expecting is 1000. How is this going to round the values?

In the wonderful world if integers dividing 2500 by 1000 gives us 2. I thing I misunderstood your question. You want the system to show only values 1,10,20,30... Right?

right, but still I need it to be 1000 when smaller than 5000...but in this case I can just have an IF. But when higher than 5000, for example 8000, it should result in 10000...(rounds up 8 to 10, etc)..17000 to 20000...

Yes, 1, 10, 20, 30..that's it.

that's great! it looks good now, I will have a go and let you know. Thanks.

Sorry it's still not working for 17000 rounding to 20000 give me a minute.

yes, I noticed this way it will always round numbers down...which is not what I expected but it's OK, it should do the job. Although if you want to improve the answer I appreciate too. thanks! :)

Instead of using properties of integer unfortunately I had to use round method. It's not as elegant (it requires cast to double and then back to integer to work correctly) but this approach should do exactly what you want.

Just a note for future reference (if anyone is looking for a similar solution), on an Arduino Due this should work fine, but on Atmega boards I used an unsigned long instead of an integer since these values are over 32,767.


text:
Multiple Atmega328p wired communication
I am using multiple ATMEGA328Ps  (4 ATMEGA328P) (OR Arduino Unos). The distance between two farthest ATMEGAs is 14 meters (One is Master Device and Other is Node), and other 3 are connected to each other at a distance of 3 meters from the Master Device.
I have a case where i cannot use Wireless communication hence i will have to go Wired. I am also looking to achieve the Mesh topology if possible.
There are many examples on the internet regarding this case but still i am not be able to choose/compare which would be more reliable.
Please suggest me the best solution to work on this.
Thanks.

Mesh is kind of silly, if it's wired. You haven't told us what you want to communicate. That is; how much data, at what data-rate? Master to slave only, or bi-directional?

a token-ring-like topology will be easier to manage; just give each device a unique ID and each message a list of IDs which are intended recipients. Once a node receives the message, it removes its ID and forwards the message, if there are any IDs left to consume... Somewhat like I2C.

How about 1-Wire? Here is an example of a 1-Wire Master and Slave that allows distributed digitalRead/Write/pinMode/etc. Master https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/Arduino/Arduino.ino, and Slave, https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/Slave/Arduino/Arduino.ino.

@Gerben : Thanks for the quick reply. My Goal is to achieve bi-directional , one master and multiple slaves ( request , response , ack , broadcasting ), long distance upto 20 meters , max to max 20 bytes of data to be sent.

@dandavis : thanks i will think about this. nice idea.

@MikaelPatel : 1-wire not recommended over long distance.


text:
Arduino Pro mini does not wake up after a few interrupts from DS3231
I hope someone can help me. I'm building a GSM water level meter that runs on solar power, using an Arduino Pro mini, a DS3231 RTC, a JSN-SR04T - ULTRASONIC SENSOR, and a SIM800L along with a DFrobot DFR0535 solar power manager and 3.7V battery.
My project worked fine before I added the RTC; it connects to the Blynk server, gets the readings from the ultrasonic sensor, and posts them, before going to sleep.
I added the RTC in order to use it to wake up the Arduino using the interrupt signal and save some power during the evenings and no sun.
Even this works, but the interrupts stop after about 30 mins of firing. At the moment its configured to fire every 5 mins. My serial output looks like this:

So at this point the sketch works 100% and does exactly what I need, but unfortunately it stops after a few minutes. Do I need a pull up resistor somewhere maybe?
Any ideas?
Below is my sketch. Any help will be greatly appreciated.
    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
    #define interruptPin 2 //Pin we are going to use to wake up the Arduino
    #include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC
    #include <NewPing.h>
    #define BLYNK_PRINT Serial
    #define TINY_GSM_MODEM_SIM800
    #include <TinyGsmClient.h>
    #include <SoftwareSerial.h>
    #include <BlynkSimpleSIM800.h>
    #define SIM800_TX_PIN 9
    #define SIM800_RX_PIN 8
    #define uS_TO_m_FACTOR 60000000   // Conversion factor for micro seconds to minutes
    char auth[] = "a892d375xxxxxx0d5c086d6b1";
    char apn[]  = "";
    char user[] = "";
    char pass[] = "";
    const int MAX_DISTANCE = 120;                       //max distance to measure
    const int Diameter1 = 110;                                //internal Diameter of tank 1 in cm
    const int Depth1 = 110;                                 //total depth of tank 1 in cm , from sensor to base inside
    const unsigned int Period = 60000;    //period between pings, in milliseconds. i.e  1 munute = 60,000. max 65535. Want longer? use unsigned long
    const int PingPin1 = 6;                          //     GPIO5,  D1
    const int EchoPin1 = 7;                        //     GPIO4,  D2
    const int Area1 = PI * ((Diameter1 / 2) * (Diameter1 / 2));          //area of base of tank 1
    int Litres1, Distance1, WaterDepth1, Decimal, Persentage, battLevel, csq, kill;
    String gsmTime, gsmTime1;
    #include <SoftwareSerial.h>
    SoftwareSerial SerialAT(SIM800_TX_PIN, SIM800_RX_PIN);
    TinyGsm modem(SerialAT);
    //BlynkTimer timer;
    NewPing sonar = NewPing(PingPin1, EchoPin1, MAX_DISTANCE);
    //RTC Module global variables
    const int time_interval = 5; // Sets the wakeup intervall in minutes

    void setup() {
      Serial.begin(115200);//Start Serial
      delay(1000);

      pinMode(LED_BUILTIN,OUTPUT);//We use the led on pin 13 to indecate when Arduino is A sleep
      pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
      digitalWrite(LED_BUILTIN,HIGH);//turning LED on

      // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
        RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
        RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
        RTC.alarm(ALARM_1);
        RTC.alarm(ALARM_2);
        RTC.alarmInterrupt(ALARM_1, false);
        RTC.alarmInterrupt(ALARM_2, false);
        RTC.squareWave(SQWAVE_NONE);
         time_t t; //create a temporary time variable so we can set the time and read the time from the RTC
        t=RTC.get();//Gets the current time of the RTC
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);// Setting alarm 1 to go off 5 minutes from now
        // clear the alarm flag
        RTC.alarm(ALARM_1);
        // configure the INT/SQW pin for "interrupt" operation (disable square wave output)
        RTC.squareWave(SQWAVE_NONE);
        // enable interrupt output for Alarm 1
        RTC.alarmInterrupt(ALARM_1, true);
    }

    void loop() {
     delay(5000);//wait 5 seconds before going to sleep. In real senairio keep this as small as posible
     Going_To_Sleep();
    }

    void Going_To_Sleep(){
        sleep_enable();//Enabling sleep mode
        attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
        digitalWrite(LED_BUILTIN, LOW); //turning LED off
        time_t t;// creates temp time variable
        t=RTC.get(); //gets current time from rtc
        Serial.println("Sleep  Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//prints time stamp on serial monitor
        delay(1000); //wait a second to allow the led to be turned off before going to sleep
        sleep_cpu();//activating sleep mode
        Serial.println("just woke up!");//next line of code executed after the interrupt
        myFunction();
        t=RTC.get();
        Serial.println("WakeUp Time: "+String(hour(t))+":"+String(minute(t))+":"+String(second(t)));//Prints time stamp
        //Set New Alarm
        RTC.setAlarm(ALM1_MATCH_MINUTES , 0, minute(t)+time_interval, 0, 0);

      // clear the alarm flag
      RTC.alarm(ALARM_1);
      }

    void wakeUp(){
      Serial.println("Interrrupt Fired");//Print message to serial monitor
       sleep_disable();//Disable sleep mode
      detachInterrupt(0); //Removes the interrupt from pin 2;

    }

    void myFunction() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
      SerialAT.begin(57600);
      delay(1000);// make GPIO8 output low
      Serial.println("Initializing modem...");
      modem.restart();
      Blynk.begin(auth, modem, apn, user, pass);
      delay(1000);
      Distance1 = sonar.ping_cm();                                       //get distance to the top of the water tank 1
      if (Distance1 >= Depth1 || Distance1 == 0 )  Distance1 = Depth1;                   //check it does not go negative
      WaterDepth1 = Depth1 - Distance1;                     //calculate the depth of the water
      Litres1 = ((Depth1 * (PI * (sq(Diameter1 / 2)))) - (Distance1 * (PI * (sq(Diameter1 / 2))))) / 1000;
      Persentage = (Litres1 / 1000.00) * 100;
      battLevel = modem.getBattPercent();
      csq = modem.getSignalQuality();
      Blynk.virtualWrite(V1, WaterDepth1);
      Blynk.virtualWrite(V2, Litres1);
      Blynk.virtualWrite(V3, Litres1 / 10);
      Blynk.virtualWrite(V4, Persentage);
      Blynk.virtualWrite(V5, battLevel);
      Blynk.virtualWrite(V6, csq);
      Serial.println();
      Serial.println();
      Serial.println("Water depth: " + String(WaterDepth1));
      Serial.println("Water distance: " + String(Distance1));
      Serial.println("Litres: " + String(Litres1));
      Serial.println("Percentage: " + String(Persentage));
      Serial.println("Battery: " + String(battLevel));
      Serial.println("Signal Qlty: " + String(csq));
      delay(100);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

Do you have pullup resistors on SCL & SDA?

nope...directly from the RTC into the pro mini...I got a few 2N2222 & MPS2222A's? Or what would you suggest?

don't use String class

4.7K pullups on SCL, SDA are needed for I2C to work. Internal to Atmega328P are insufficient.

I think your code just hangs/crashes after some time. Try commenting out sleep_cpu(); and see if it hangs after half an hour. I don't think this has anything to do with sleeping.

With sleep_cpu(); commented out. The sketch runs in a loop, completely ignoring the sleep time, waking up straight after going to sleep. So far its been running for more than 30mins without freezing.

I have exactly the same issue, after 30 times waking up the code hangs up and the arduino nano is not waking up for the interrupt anymore.
Did you find the issue in the meantime? @Roelof Loots


text:
Upgrading NRF module for drone
Hello I am trying to make a drone by using Arduino as a microcontroller both for remote controller and the drone. And I have thought for using NRF module. But I came to know it only can transmit data to 1000 m maximum but I need the range around 8 km maximum. What can I do for increasing the range of my drone? Or is there some way to increase range of NRF module?

This is silly. You won't be able to see the drone that far. How are you going to control what you can't see? You will have to pick transciever that operate at a much lower frequency. Thus limiting the bandwidth. Don't even think about streaming live video on those.

Most countries have laws about operating drones out of line of site, or over a few hundred meters away, etc. An nRF24L01+ is more than adequate if you want to remain within the law...

I have managed all the settings there would be ground controlled station only i need to increase maximum range. And I already own drone license.

If I search I see plenty of examples of RF with 40 miles, e.g.:

XTend 900 1W RPSMA - 40 Mile Range
XBee-900-Datasheet

Possibilities to increase the range:

More powerful transmitter
External / better antenna(s)
Better receiver
Using directional communication (might be hard with a drone which flies/moves)

@Juraj ... I meant actually 1000 m, but probably that's his currently used nRF.

I need a arduino compatible device


text:
How to Home a stepper and make it move 45 degree after that
I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.
The setup part kind of works, but does not run smoothly.
The stepper1() part does not work at all (only jerking movements).
I would also like the motor to be disable when it waits which in my understanding should be achieved by digitalWrite(M2en,HIGH);but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.
#include "AccelStepper.h"

int M2dirpin = 4;  //Motor Y direction pin
int M2steppin = 5; //Motor Y step pin
int M2en=12;  //Motor Y enable pin
#define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

// AccelStepper Setup
AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
// Stepper Travel Variables
long initial_homing = -1; // Used to Home Stepper at startup

void setup() {

  pinMode(home_switch, INPUT_PULLUP);
  pinMode(M2dirpin,OUTPUT);
  pinMode(M2steppin,OUTPUT);
  pinMode(M2en,OUTPUT);
  digitalWrite(M2en,LOW);
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

  // Start Homing procedure of Stepper Motor at startup
  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    stepperX.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    stepperX.run();  // Start moving the stepper
    delay(20);
  }

  stepperX.setCurrentPosition(0);  // Set the current position as zero for now
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    stepperX.moveTo(initial_homing);
    stepperX.run();
    initial_homing++;
    delay(20);
  }

  stepperX.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");

 // Move 10 steps forward from the limit switch (to get out of the switch)
  while (stepperX.currentPosition() != 10)
  {
    stepperX.setSpeed(10);
    stepperX.run();

}
}
void loop()
{
//stepper1();
}

void stepper1()
{
  stepperX.move(22.5);
  stepperX.run();
  delay(3000);
}

You need to call run more often. From the documentation:

You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single run call and then a delay, will make the motor move only one step. So you need to rewrite for example:
stepperX.run();
delay(3000);

to
unsigned long startMillis = millis();
while( millis()-startMillis<3000 )
{
  stepperX.run();
}

Secondly, move only works on integers, stepperX.move(22.5); will actually become stepperX.move(22);
Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.


text:
DHT 11 temp. And hum. Sensor always 0 values

I am trying to get my DHT 11 from the official arduino store to work (https://store.arduino.cc/grove-temperature-humidity-sensor).
I am following this guide right here:
http://wiki.seeedstudio.com/Grove-TemperatureAndHumidity_Sensor/
But I'm only getting invalid output of 0 humidity and 0 degrees.
I hope the image helps in identifying my problem.
On a side note, my sensor looks like a part is missing which is very strange and makes me doubt the right product was sent to me.
Some more information:
- Black to GND
- Red to 5v
- White is wmpty
- Yellow to d2
- Using an arduino Uno
- Output does not change whether the sensor is actually connect or not.
- Total noob at this.
Help would be appreciated a lot!

that's not a DHT-11 in the photo. Why would they break out a non-connected pin like that? Also, you link to a DHT22 (white plastic), not an 11 (blue plastic)...

Well yeah the top cover is missing.. Does it carry an electrical connection though? Can you upload a detailed picture of the DHT11 module from above?

@Maximilian Gerhardt I have added an image. How do I know if it carries an electrical connection?

That is a Grove temperature and humidity sensor module with the si7005 made by seeed studio: http://wiki.seeedstudio.com/Grove-TemptureAndHumidity_Sensor-High-Accuracy_AndMini-v1.0/ They also make a module with a DHT sensor, but that is an other one.

Okay, this is not a DHT11 board. This thing has an I2C bus. Either you ordered the wrong product or they sent you the wrong product. You bought the "Grove - TH02 - I2C temperature and humidity sensor" (https://botland.com.pl/en/grove-series-for-arduino/4413-grove-th02-i2c-temperature-and-humidity-sensor.html)

You haven't bought a DHT11 module but the Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02 module.

Thus you should use the example code here or follow the guide at seedstudio wiki.
Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf

That's upsetting. It's not what I ordered. I'll try to follow the guide you suggested and will let you know how that turns out. :)

@JonasBergner The sensor on this board has a superior accuracy (+- 0.5°C) when compared to the DHT11 (+- 1 °C) so I wouldn't exactly complain^^

ok this actually seems to be the product I have here with me. But i have trouble getting it to work following the instructions. I do understand that I need to connect Red to 5V and black to ground, but what does it mean to connect white to "SDA" and "SCL" to yellow? I'm kinda lost :D. I know youve already helped me a lot. I really appreciate it! @Maximilian Gerhardt

@JonasBergner SDA (Serial-DAta) and SCL (Serial CLock) are the 2 signals of the I2C bus. The Arduino Uno has its I2C pins on A4 (SDA), A5 (SCL), this is where the cables need to go. (https://www.arduino.cc/en/Reference/Wire)

heck yeah i got it to work! without burning my house down! Thank you so much!

How does the Grove TH02 compare to the DHT22?

@DuncanC Refer to the specifications of the Si7005 (https://www.silabs.com/documents/public/data-sheets/Si7005.pdf) and the DHT11 sensor (https://www.mouser.com/ds/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf), especially the parameters accuracy, resolution and range.

I asked how it compared to the DHT22, which is also more accurate than the DHT11. I haven't had enough coffee yet this morning to pour over data-sheets. If you know the differences off the top of your head, cool. If not I'll wait until I am more awake and slog through some data-sheets.

It looks like the DHT22 is more accurate.The DHT22 data sheet says ±2% RH, and ±0.2°C temp, where the Grove TH02 says ±4.5%RH and ±0.5°C typical (±1.0°C max).

@DuncanC oh okay I just read DHT11 instead of DHT22; yes in that case DHT22 beats this board.

The OP was trying to buy a DHT11. I started out using DHT11s and then moved to DHT22's, So I was curious as to how they compared.


text:
How to read a 25 kHZ PWM signal from PC fan header?
I would like to control a DC motor's speed using the PWM output from my motherboard header.
Here's the standard pinout for a 4-wire PC fan header:
╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝

Since my DC motor doesn't have a PWM input, I thought of using an ATmega328P in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.
However, I'm not sure how I should read the PWM signal from the motherboard.

What is the HIGH voltage level of PWM output?
Do I need a voltage divider resistor for it?
A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.
Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

The PWM signal controlling the fan is allowed to be from 21 to 28kHz.  The pulses for the RPM indicator are simply one (or two) pulses per rotation.  Assuming 10000RPM (insanely high speed for a fan) and two pulses per rotation, you only get RPM pulses at a little over 300Hz.  Those can easily be read by an Arduino.

But, not neccessarily using the "pulse" command.  That gives you the width of the pulse, but not the time between pulses.

Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
  Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the documentation for pulseIn() says:

Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%
What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.
However since you want to

... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!

+1, Thanks for the well-explained answer, your solution makes sense! Although in addition to driving a motor, I still would really like to read the PWM output with something and feed the data to my microcontroller, so I can for instance display it. Is there a way I can achieve this digitally instead of using an RC filter?

@DavidRefoua analogRead(...) will return a value between 0..1023; where 0 is 0V and 1023 is 5V; the RC filter is to stabilize the voltage so the ADC can read it.


text:
No matching function call for timer?
I am using the Timer library here with the Adafruit feather m0:
https://github.com/JChristensen/Timer
https://playground.arduino.cc/code/timer
I cannot figure out why I am getting the error:
no matching function for call to 'Timer::every(int, void (&)())'
Here is that part of the code:
void setup(){
      everyAlt = t.every(100, readAltimeter);
      everyLaunch = t.every(500, detectLaunch);
      t.oscillate(blueled, 500, HIGH);
    }

    void readAltimeter(){
      alts[altPlace] = bmp.readAltitude()-zeroAlt;
      altPlace++;
    }

    void detectLaunch(){
      tempSpeed = 0;
      int x = 0;
      while (x < 5){
        tempSpeed += abs((alts[x]-alts[x+1])*10);
      }
      if (tempSpeed/5 > 5){
        t.stop(everyLaunch);
      }
    }

I am pretty new to arduino so any help would be much appriciated!

I cannot reproduce your problem with this code: https://pastebin.com/WQBCb1AQ Does the code above compile correctly?

Yea, I still have the same compiling error. https://pastebin.com/W63QC2r4

You and me are using two different versions of the library. The every function has e.g. an overload int8_t every(unsigned long period, void (*callback)(void*), void* context); in your library but not the current master version (https://github.com/JChristensen/Timer/blob/master/Timer.h#L40). Please uninstall your old Timer library from the library manager, download the newest ZIP from the Github repo, reinstall the lib and retry.

Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer


text:
Question on a car kit I bought
recently bought an UNIROI Smart Car kit.
(UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm_sw_r_cp_tai_wQExCbHT0YM8K)
I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://i.stack.imgur.com/7nhBO.jpg
I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins.
The description of the car also quotes
“Extended Pin Interface. The chassis is designed with
extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop
and build your own robot car kit”
Appreciate any help you guys got.

Does the CD come with a schematic PDF? I couldn't find it when googling it.. But basically if the pin is free, you can solder to it and modify the firmware as you like. You'd want to have a soldering iron and a multimeter to check connections.

Correction: They have a link to a megaupload drop for all the needed data: https://images-na.ssl-images-amazon.com/images/I/41Y9NGFGlBL.pdf

It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.
Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah_HlLFJ_NKxv7ILLY2g folder "5 SCH".

This means that the only way that you'll get new components into this project are:

removing components  and re-programming the firmware to not use them

e.g., the two tracking-sensors left&right -> A2 and A3 are free
e.g., the speaker pin (D13). Who needs a speaker?

restructuring components

e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. ADS1115) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.

Appreciate the reply. Do you think if I removed those tracking sensors and and ultrasonic sensor I could add an SD card module that takes 4 pins? They are also anolog pins so can I still use them as digital?                         As a side note, I also have a spare Arduino so would it be possible to receive signals from the avoid sensor to both Arduinos?

@Josh your SD card is a SPI device and must be connected to the hardware-SPI pins of the Arduino Uno, which are 11,12,13 (MISO, MOSI, SCLK) and any other digital pin for slave-select (SS). On your car, these pins are connected to the servo (D11), the button and the speaker, so you would have to re-locate all these components.. Or use a bit-banged SPI in software, which I haven't yet seen. And yes, the analog pins A0-A5 are all capable of outputting digital output (HIGH,LOW).

I wouldn’t be able to move those items, they’re attached in a way I wouldn’t know how to re-locate, but I appreciate the suggestion. What about using another Arduino? Since I am not great at coding when there’s tons and tons of lines, having a second Arduino that also reads the avoidance sensors would be perfect. Is that possible?

@Josh you could upgrade the entire thing to an Arduino Mega instead of the Uno.. should have similiar code but you have tons of I/O pins more.


text:
Does Arduino Uno come with Virtual Pin support?
I want to recieve Data with Virtuino from my Arduino Uno 3 (Ethernet Shield) via Ethernet.
Does Arduino Uno 3 support virtual pin? If so - is there a link with the Syntax I need?
Thank you very much

have you searched for virtuino arduino uno - second link in google uses an ethernet shield

Thanks, I am using an ethernet shield and established a connection with Virtuino already. I did use google. Doesn't answer my question if Ardunio Uni supports virtual pins though :/

What are virtual pins?

@Majenko The library he mentions allows to map variables in the mobile app to variables in the device firmware using the so called virtual pins. It's just a way to define a data binding between the two pieces of software: you change the virtual pin state/value in one to get the same change reflected on the other end.

Ah. So the answer is: "Yes. If you write the software to do it - or install whatever libraries this Virtuino thing provides for you".

Thats right, basically what I want to do. If I google for "Arduino Virtal Pin" and similiar things I often come to "Blynk" though I need to use Virtuino.
What I basically need is a library and/or Syntax to use virtual pins.

it appears that the virtual pin exists in the Android app .... when an Arduino hardware pin changes state, a message is sent to the app, which changes the state of the virtual pin ..........  changing the state of a virtual pin in the app, sends  a message to the arduino, which changes the state of the hardware pin  ..... because of the time required to send a message, you cannot use the virtual pin for fast changing pins such as PWM

@Red, the Virtuino  web site has a bunch of example sketches ..... you just have to look ....... you may also be misunderstanding what virtual pins are ...... that may be why you are not satisfied with the answers that you found

Virtual pins are, as the name gives away, virtual, thus not related to the hardware you are using. Imagine you have a board with 100 pins, you have 100 physical pins and can add 1 million virtual pins (memory permitting).
In other words, the question doesn't seem to make sense to me.
UPDATE
If you need a bootstrap on how virtual pins are defined and used you could give a look at the examples published by the authors, like these
If that's not enough, please provide additional information on what problem you are facing and which solutions you have already attempted.

Nono, thats everything I needed. I used many of the examples the IDE provided but I didn't find this one. It's perfect. Thank you very much Roberto :)


text:
How do you make a stepper motor move at decimal (such as 0.5) steps?
if I were to use a code with the following format,
//some loop
digitalWrite(STEP_PIN,HIGH);
digitalWrite(STEP_PIN,LOW);
//

each loop would make the motor move at one step. With this loop I can also make the motor move at 200 or other integer steps. However, is it possible to make the motor move at decimal steps such as 0.4?

It is called microstepping. There are modules with current control that can do microstepping. The easiest solution for you can be a geared stepper motor.

Depends on you stepper driver. It needs to support microsteps. Which driver do you use?


text:
nRF24L01 using sender as receiver and vice versa with RF24 library
I have two nRF24L01 modules (I tried 2 with antenna and 2 without antenna) paired with their power base module and connected to two different Arduino Mega 2560 boards.
I'm able to send from one module to another up to 32 byte of data and get the acknowledge without any problems. But when I switch them, when I try to send data from receiver and receive it on the sender I have nothing. No data received, no acknowledge sent as response.
As I said before, first part of this code works well, but when it comes to the second part, which is after delay(1000); there's silence...
my code is:
Receiver
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xE8E8F0F0A2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(1, pipe01_);
    radio.openWritingPipe(pipe02_);
    radio.enableDynamicPayloads();
    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        delay(1000);
        radio.stopListening();

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);
        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack: " + String(ack));
        }
        radio.startListening();
    }
}

Sender
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xA2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(2, pipe02_);
    radio.openWritingPipe(pipe01_);
    radio.enableDynamicPayloads();
    radio.stopListening();

    char message[32] = "qwertyuiopasdfghjklzxc1234567890";
    radio.write(message, 32);

    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

Please help me.

The string qwertyuiopasdfghjklzxc1234567890 contains 32 characters plus an implicit null terminator - for which there is no space in the array. It would be safer to declare this as char message[] = "...". You might suffer from corrupted memory here.

Update: It was working yesterday, but today... same thing as with "delay()". What's wrong with these radio-modules??
I have discovered that the delay() function was causing this abnormal behavior.
So I have implemented periods instead of delay() and now I'm able to switch operating mode between "receiver" and "transmitter". Moreover, I have discovered few additional conditions that must be met (read the comments for the code).
Below is working sample code where transmitter sends some large message. Receiver gets it, waits 2 secs, then responds with another large message and gets the acknowledge for this message:
Sender
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //At least one of reading pipes must be full adress
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(2, pipe02_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe01_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //If not set, size will be of fixed length. Default fixed length is 32 bytes

    /*Must run this if "startListening()" will be used anywhere in the code below.
    nRF24L01 remembers it's state even if Arduino was restarted*/
    radio.stopListening();
    Serial.println("Sending the message...");
    char message[32] = "qwertyuiopasdfghjklzxc1234567890"; //some test message
    radio.write(message, 32); //Send message over the predefined "writing pipe"

    Serial.println("Waiting for response...");
    radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"

    uint16_t ack = 123;
    radio.writeAckPayload(2, &ack, sizeof(ack)); //Custom ACK payload must be set after "startListening()". Because "startListening()" resets TX buffer
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

Receiver
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

#define period_  2000

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //At least one of reading pipes must be full adress
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

unsigned long checkPoint = 0;
bool messageReceived = false;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(1, pipe01_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe02_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //Writing pipe must be full address if acknowledges will be used
    radio.startListening(); //If not set, size will be of fixed length. Default fixed length is 32 bytes
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        checkPoint = millis();
        messageReceived = true;
    }

    unsigned long timePassed = millis() - checkPoint;

    //When it receives, controller waits for 2 seconds then sends the response just one time
    if (messageReceived && timePassed > period_)
    {
        messageReceived = false;
        checkPoint = millis();
        Serial.println("sending response...");

        //This must be called before sending anything (except acknowledges)
        radio.stopListening(); //Resets TX buffer and switches radio module's mode to transmitter

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);

        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack received: " + String(ack));
        }

        radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"
    }
}


text:
I want to get incomming call number and compare it
Hello i want to get and compare incomming call number, it works but not as I want.
When im calling from good number it print that I was calling form saved number when the number is stop calling i need to do it on start. And else is printing when nobody is calling. How can i do it? Here is my code:
String d = "";
void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(500);
  Serial1.println("AT+CLIP=1");
  delay(1000);
  Serial1.println("AT+CPIN=1439");
}
void loop()
{
 d = Serial1.readString();
 if(d.indexOf("xxxxxxxxx") >=0)
   {
 Serial.println("call is from saved number");
    } else {
       Serial.println("call is not from saved number");
      }
}

Hint#1: "readString()" has a timeout. What should your code do then? https://www.arduino.cc/en/Serial/ReadString

@MikaelPatel When it's recognised number I will be sending HTTP POST to my api.

You need to check that a string has received and not returned due to a timeout. It is only when a string with a number, a call, has been received that the valid phone number should be checked. Please fix the control logic of your sketch.

Could you help me with it? I'm new in C but I need it to build my system to mobile app

You could for instance add "if (d.length() == 0) return;" after "d = Serial1.readString();".

Should I add it below my if statements ?

The Arduino Serial class member function readString() has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with setTimeout().
The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:
void loop()
{
  String d = Serial1.readString();
  if (d.length() == 0) return;
  Serial.print(d);
  if (d.indexOf("xxxxxxxxx") >= 0) {
    Serial.println(": call is from saved number");
  }
  else {
    Serial.println(": call is not from saved number");
  }
}

Cheers!

It still doesn't work

Try the above and check the output to the serial monitor.

I have tried but the biggest problem is that serial print print call is from saved number after I decline calling

Please add an example of the output to the serial monitor. That would help understand the issue.

https://imgur.com/a/PKHDP84

Might want to use readStringUntil() if you want to capture per line and not until timeout. https://www.arduino.cc/en/Serial/ReadStringUntil

String d = Serial1.readStringUntil();  I got the following error : no matching function for call to 'HardwareSerial::readStringUntil()'

You need to give a terminator character. For instance '\r', please read the documentation page.

I will try it as soon as it will be possible. If it works I will give your answer "the best"


text:
LCD displays weird characters
I have connected the LCD by the 3 wire method using the LiquidCrystal595 library+74HC595 register shift; sometimes "hello world" is displayed but other times the LCD displays weird characters.
How to solve this problem?

do you have a question?

I want to know how to solve this problem  ?

Could be a bad wire, breadboard connector or power issue. Add a capacitor on the power line to the 74595 (VCC/GND). The next step is to check the timing in the library.


text:
Use 2 DHT22 AND PASS THE DATA TO SD?
I have the code to pass the data from dht22 to sd but for only one and i want to pass the data from 1 dht22 with one file and the data from other sensor to other file and logging in to sd. Anyone can help me?
#include
#include
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
File data_file;

int CS_pin = 10;
long sec=00;
long mint=00;
long hr=00;

void setup() {
Serial.begin(9600);
pinMode(CS_pin, OUTPUT);
dht.begin(); //This command will start to receive the values from dht22
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is initialized and it is ready to use");
} else
{
Serial.println("SD card is not initialized");
return;
}
}

void loop() {
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
delay(1000);
}

void getData(){
for(long sec = 00; sec < 60; sec=sec+2){
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
data_file.print(hr);
data_file.print(":");
data_file.print(mint);
data_file.print(":");
data_file.print(sec);
data_file.print(", ");
data_file.println(temp);
Serial.print(hr);
Serial.print(":");
Serial.print(mint);
Serial.print(":");
Serial.print(sec);
Serial.print(", ");
Serial.println(temp);
if(sec>=58){
mint= mint + 1;
}
if (mint>59){
hr = hr + 1;
mint = 0;
}
data_file.flush(); //saving the file
delay(2000);
}
data_file.close(); //closing the file
}

Thanks

It isn’t clear what you’re asking. You want to collect data from 2 sensors? What 2 files are you referring to? You have 2 source files? How are they structured? Why do you need 2 source files? Why not write a function that collects data from 2 sensors?

To me it was pretty clear, what the question was. And OP also acknowledged that in his comment below my answer...

@oh.dae.su you're a better man (or woman) than I. I took it to mean 2 different sketch files but outputting the data to 2 different files on the SD card makes a lot more sense.

@Duncan C my comment was not intended as a direct answer to you, but in general in response to the question being put on-hold as unclear... ;-)

First you need to setup the second DHT sensor and a second file. Please replace the X by the number of the pin your second sensor is connected to after #define DHTPIN2
#define DHTPIN 8
#define DHTPIN2 X
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
File data_file, data_file2;

In setup() you need to also start the second dht sensor:
dht.begin(); //This command will start to receive the values from dht22
dht2.begin(); //This command will start to receive the values from dht22

In loop() you have to open the second data file in addition to the first one:
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
data_file2 = SD.open("data2.txt", FILE_WRITE);
if (data_file2) {
getData2();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data2.txt");
}

Although not the most efficient/elegant solution, this requires you to duplicate your void getData() function as void getData2() to work for the second sensor/file, by replacing dht by dht2 and data_file with data_file2.
This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the void getData() function.

Thanks for your help. Now finally i can do it ;)

You are welcome. Glad I could help. Btw. please read the stack exchange tour page https://arduino.stackexchange.com/tour to learn, how things work out on this site, e.g. how to deal with answers to your questions.

I don't know why but the program now say File does not name a type.

@jawad bouhali please either ask a separate question including the code and the exact error message or edit your question and append this information to it.


text:
Would a 100KΩ resistor connected to ground pull an open analog line down to 0
I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.
I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.
If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how < 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.
What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?
(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

To whoever voted to close as not being about Arduino, how is this not about Arduino? My question is about the behavior of the analog pins on an Arduino Mega.

Sound fine to me. I'd probably even go with a higher value. You'd have to do the calculations as to how it would affect the readings of the photoresistor. PS. A lot of 3.5mm sockets have switches in them to detect if there is something plugged in. You could use one of those switches to connect the analog pin directly to ground if nothing is connected. Or you could connect it to a digital pin, and have the software ignore the analog input.

I would expect a 100K pulldown to quiet the A/D, but I'd have to actually try it. I'd think testing it on the bare board, outside of your project box would still give you useful information. But I would sketch up the schematic of the proposed voltage divider with the parallel pulldown and run the numbers to convince yourself of what effect it will have on your measurement. You may be able to ignore it, or you may want to correct for it.

What is the effective range of an analog pin on an Arduino?

0 - (1023/1024)*Vref, whichever reference, 1.1v, 2.56v, or Vcc applied to the Vref pin, you have selected.

(A Mega 2560, if that matters) What’s the lowest voltage that will
  register above 0?

Appx (Vref * 2^-11), i.e.,  1/2 an LSB of the 10-bit A/D range.
Update:
Is that a jumper selection?
No, it's programmable; the external Vref is reset default. See ch. 25 of the 2560 datasheet for the low-level details; Arduino.cc's function-reference, for the analogReference() function for the quick & dirty how-to. Remember to take and discard a measurement whenever you change the reference.

Is that a jumper selection? (I haven’t changed anything on the factory settings on my Arduino.) Based on the testing I did when I was building the voltage divider, it seemed to treat 5V as max, which is what I expected.

Thanks for the thorough answer. (Voted). I do have a 4 channel 5V (optically isolated) relay inside the box that switches 120VAC outlets at up to 10a, and will also be driving a pulsed 9V electromagnet (which will be outside the case) with about 200 mA of current, but the Arduino and it’s low power components, the relay, and the electromagnet all have separate power supplies. So there may be a fair amount of electromagnetic noise inside the box.

With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.
The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.
There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a pinMode(A0,INPUT_PULLUP); to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with pinMode(A0,INPUT);.

To repeat my comment on JRobert's answer:  I do have a 4 channel 5V (optically isolated) relay inside the box that switches 120VAC outlets at up to 10a, and will also be driving a pulsed 9V electromagnet (which will be outside the case) with about 200 mA of current, but the Arduino and it’s low power components, the relay, and the electromagnet all have separate power supplies. So there may be a fair amount of electromagnetic noise inside the box.

I tried it with a 100K resistor, and sure enough, when the relays are active and driving AC loads, the analog input still picks up noise. In fact it looks a lot like 60 Hz noise. I guess I need lower value resistor, and to just adjust for the lower voltage into my analog input.

@DuncanC do you use the average of a number of samples? That is often done to reduce noise. However, noise around zero volt will not average to zero, but it will average to the positive part of the noise above zero.

I don't do averaging yet. I like that idea (a software change) better than opening up the box and swapping out the resistor.

Averaging was a good idea. It works well. Thanks for the suggestion. I should have thought of that.


text:
Error: Does not name a type
I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.
Code for the class
class subject {
public:
  char subjectname[];
  char classroom[];

};

Code for the classroom and math
subject math;
math.classroom = "A1";

How can I set the classroom of math to A1?

class subject {
public:
  char subjectname[];
  char classroom[];

};

This creates a class subject which has two char arrays of unspecified size as its members. This will attempt to create an array of size 0 (see here). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then strncpy() your new string inside the buffer.
This would look like
class subject {
public:
  char subjectname[32];  //32 bytes buffer
  char classroom[32];
};

And later
subject math;
strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
Serial.print("Classroom is: ");
Serial.println(math.classroom)

Or, just use the Arduino String class.  For example
#include <Arduino.h>
class subject {
public:
  String subjectname;
  String classroom;
};

Then your first usage code can be used unmodified.
Example
#include <Arduino.h>

class subject {
public:
  String subjectname;
  String classroom;
};

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

    subject math;
    math.classroom = "A1";

    Serial.print("Classroom is: ");
    Serial.println(math.classroom);
}

void loop() { }

I tried using this code but it gives me the error 'math' does not name a type at the math.classroom line.
`#include <Arduino.h>
class subject {
public:
     String subjectname;
     String classroom;

};

subject math;
math.classroom = "A1";`

@TechnicProblem I can compile https://pastebin.com/5hVgtTi7 just fine. Does that compile for you?

Thank you. Didn't know I should've put some of the code in void setup(). Now it works.

@TechnicProblem You can put global variables outside of function scopes but not assignments and operations on them. Those must be in functions.

+1 for your excellent answer. FWIW, the String sketch's compile size is 3644 bytes, and the strncpy sketch is 2112 bytes. +100 for using a class in your sketch. The difference in compile size (using the strncpy sketch) VS the same strncpy sketch with all the added OOP code is 0 bytes. Using a class costs you nothing, and gives you a lot. It is unfortunate that there are 3 votes to close this question, stating it's off topic. According to this page: https://arduino.stackexchange.com/help/on-topic , "Specific questions about Arduino boards, code…" are "On Topic".


text:
Weird behavior with char/uint8 arrays
So I'm trying to read an 8-byte character string from an I2C device and print it to the serial console. This raw 8-char array is not terminated when it comes from the device, so I'm pretty sure I need to manually terminate it. Unfortunately, when I go to print the resultant string, the serial monitor just fills up with line breaks. Could someone take a look at this code and tell me where I went wrong?
uint8_t* HT_Controller::readMultiple(uint8_t reg, uint8_t num)
{
    Wire.beginTransmission(i2cAddr);
    Wire.write(reg);
    Wire.endTransmission();

    Wire.requestFrom(i2cAddr, num);
    uint8_t* data = new uint8_t[num];

    for(int i = 0; i < num; i++)
    {
        data[i] = Wire.read();
    }

    return data;
}

char* HT_Controller::getManufacturer()
{
    uint8_t* data = readMultiple(REGISTER_MFR, NUM_MFR_BYTES); //Read the bytes from the controller
    char* dataTerminated = new char[NUM_MFR_BYTES + 1]; //Our new array that will have a null char at the end
    memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array
    delete(data); //We're done with the original array, remove it from the heap
    dataTerminated[NUM_MFR_BYTES] = 0; //Add that null char. NB: we don't need to '+1' the index because arrays start at 0, not 1

    return dataTerminated;
}

And here's how it's used in the main sketch:
void loop()
{
    char* data = mc1->getManufacturer();
    Serial.println(data);
    delete(data);
    delay(500);
}

Hint#1: Check the parameter order for memcpy(), http://www.cplusplus.com/reference/cstring/memcpy/. And try writing code without all the heap usage (new/delete).

@MikaelPatel how can I avoid heap usage, keeping in mind this is for a library?

Hint#2: Use the stack and pass return values by reference. e.g. "char dataTerminated[NUM_MFR_BYTES + 1]; readMultiple(REGISTER_MFR, NUM_MFR_BYTES, dataTerminated);"

@MikaelPatel wait but isn't returning a pointer to a local array a no-no?

Oh I think I see what you mean now

@MikaelPatel hmm so that's all well and good for readMultiple(), but in order to apply that to getManufacturer() the user would need to know that the array they pass in to be outputed to needs to be 9 chars big...

Your memcpy is backwards.
SYNOPSIS
   #include <string.h>

   void *memcpy(void *dest, const void *src, size_t n);

So the line:
memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

should be:
memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array


text:
Storing hash values from SHA256
I am using this code and I can not save the output of the hash function to an array of char. Can you help me how to do that?
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{

}

instead of printing it, put it in an array of char - you'll need an array 64 long of course

hello jaromanda,thank u for ur suggestion,i can not copy from the output of printhash function

This is the code that worked for me:
#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}

this is the code that worked for me

Save to a character vector (64 characters + NULL):
void copyHash(char* buf, uint8_t* hash) {
  int i, j = 0;
  for (i = 0; i < 32; i++) {
    buf[j++] = "0123456789abcdef"[hash[i]>>4];
    buf[j++] = "0123456789abcdef"[hash[i]&0xf];
  }
  buf[j] = 0;
}

void setup()
{
  String FinalStr="1234567890";
  Sha256.init();
  Sha256.print(FinalStr);
  char buf[65];
  copyHash(buf, Sha256.result());
}

Cheers!

hello mikael,thank u 4 ur help,i will try and tell u the results,deeply appreciated

I have tried and got different outputs
"c775e7b757ede630cd0aa1113bd102661ab38829ca52a6422ab782862f268646
2f64612d9642afc666117f4d4fc87c17dba06ad091e1ce611f70020f2278337e"


text:
Recommendations for 24V to 5V AC/DC converter
I'm working on an ESP8266 thermostat that should be powered by the 24V AC from the furnace. I'm looking for a converter to 5V DC that would be small enough to fit in a smaller enclosure and not dissipate too much heat. Not fully sure about the current, but I'm planning for up to 500 mA for short periods of time. I found on ebay this, but it accepts input from 85V upwards. What would happen if I would feed 24V AC to it? Would it still work. Or alternatively doesn anyone have a link for something similar that would work with 24V?

Search for "24vac to 5vdc converter" or "24v ac/dc 5v converter". Don't buy a cheap converter from ebay, that might damage your project.

Transformers for furnaces are typically Class 2 transformers, energy limited. Unloaded, or lightly loaded, they produce a significantly higher output voltage than the rated output voltage, 24 volts in this case. 28 volts is typical, and it may be higher during high line situation. The 24 volt rating is a loaded voltage, with a resistive load.
28rms x 1.4 = 39.2 volts
You should be using a regulator with a voltage rating of at least 40 volts, and that is really marginal.
https://www.aliexpress.com/item/1pcs-2018-new-dc-dc-converter-12V-24V-36V-48V-60V-72V-to-5V-0-5A/32922897633.html
The AC-DC converter you linked to would not work. It has a low voltage cutout. It also would not be able to provide the power if it was able to work at the lower voltage. The input current would be much higher than the normal input current at a normal line voltage.

24VAC rectified with a full diode bridge rectifier (4 diodes) becomes 36VDC when smoothed with a cap, the datasheet indicates this part would be okay with that. You'd probably be okay as you're planning <500mA output most of the time.
https://www.digikey.com/product-detail/en/murata-power-solutions-inc/OKI-78SR-5-1.5-W36-C/811-2196-5-ND/2259781

How does 24VAC become 36 VDC when rectified?

VDC = VAC * sqrt(2)  or 1.41 under no load. 24*1,41 = 33.84V, so not quite 36V.  The explanation behind it is here.

You say "here" but did not provide a link. I gather your talking about peak-to-peak voltage vs RMS voltage? Won't the voltage drop to 24 under any meaningful load?

Lost the original link. Read this one  http://www.bristolwatch.com/ele/basic_ac_rectification.htm  Even with a drop, there will be plenty to make 5V unless you're really loading it down.  Much better explanation here  http://www.circuitstoday.com/full-wave-bridge-rectifier


text:
Digital I/O threshold voltages for ATmega32u4
What are the voltages on a ATmega32u4 (eg Arduino Leonardo) such that a HIGH or LOW is read?
I want to ensure that I'm reading the chip reference manual correctly, where Table 29-1 says:

VIL: Input Low Voltage, Except XTAL1 and Reset pin

Min: -0.5
Max: 0.2VCC-0.1V (LVTTL)

VIH: Input High Voltage, Except XTAL1 and RESET pins

Min: 0.2VCC+0.9V (LVTTL)
Max: VCC + 0.5V

My questions:

What is LVTTL?
How do I interpret the VIL Max and VIH Min?
Is the input undefined between those two values?

LVTTL is Low Voltage Transistor-Transistor Logic. In general, the
term "TTL" is used for a digital signal.
The "Low Voltage" part is special,
the ATmega32U4 switches from low to high (and vice versa)
at low voltages.
Just as it is written. For example, when the ATmega32U4 runs at 5V,
then:
VILmax = 0.2 * 5 - 0.1 = 0.9 V.
VIHmin = 0.2 * 5 + 0.9 = 1.9 V.
Between those values the input signal is seen as low or high,
but the exact voltage when it switches from low to high may
vary.
When the microcontroller is running at 5.0 V and is used
within the specifications of the datasheet, then a voltage
below 0.9 V is always seen as low and
a voltage above 1.9 V is always seen as high (guaranteed).
Those voltages is what a electronics designer must consider.

In the datasheet of the ATmega32U4 at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

(Thanks to Edgar Bonet for the correction/addition)

Re “it switches from low to high at an average of 1.4 V”: the average threshold voltages are not specified. The datasheet, however, provides graphs with the typical thresholds as a function of temperature and Vcc. Both VIH and VIL are typically between 1.5 and 1.6 V at 25 °C and Vcc = 5 V.

@EdgarBonet, thanks! I found the graphs and I will add it to my answer.


text:
NodeMCU Ping working on one but not another
Update 2:
Have tested by pinging various devices on different subnets / vlans
and did a pcap on the wifi AP
I can see the icmp requests going through for each request except for ones on the 4.x subnet, almost like the arduino doesnt like that IP address and refuses to send those packets?
Update 1:
Have tested the following
Turned on logging on firewall and noticed the following actions:

Ping router from Arduino - See logs in firewall, arduino gets response. (Red line)
Send external web request from arduino - See logs in firewall, arduino gets response. (Orange Line)
Send web request to internal server - Arduino queries internal DNS and gets IP of web server, but no request send (Nothing in firewall logs) (Yellow and Blue)
Send ping to internal server - Arduino queries same dns server, gets ip, but no request sent (Firewall logs again) (Yellow and Green)

however, sending the ping and web request from desktop, shows both the firewall log blocking the ping request, and the rule allowing the web request.(Brown Purple Pink)
Have attached diagram again to help visualize whats going onAnd can attach router logs or rules if required
https://imgur.com/a/g4TipmZ
Also have set a windows PC with the same IP address, and can ping the web server, so I know it's something wrong with the arduino's requests to the web server in particular, and not the firewall?
End Update
I have two Node MCUs which I'm using for a project.
A while ago they were working fine, but i recently changed some network settings on my home network and found that it broke the script I had running on them.
I finally figured out where it went wrong and fixed it, but now I have another interesting problem.
One of my nodes runs this script fine, where as the other gets stuck on the ping stage.
I have uploaded the same script to both nodes and swapped over the IP address assigned and it follows the device not the IP.
So I know its not a networking issue.
I know the WiFi is working on the funny node, as it gets a IP address.
but it doesn't go any further
Any ideas?
Script attached below:
    #include <DHT.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include <ESP8266Ping.h>

    // WiFi credentials.
    const char* WIFI_SSID = "SSID";
    const char* WIFI_PASS = "******";
    WiFiClientSecure wifiClient;
    bool connection = false;
    WiFiClient client;
    const char* dbServer = "webaddress";

    void setup() {
      //Open Serial
      Serial.begin(9600);
      Serial.setTimeout(2000);

    //Connect to Wifi
      bool pingtest = false;
      Serial.print("Connecting to WiFi");
      WiFi.begin(WIFI_SSID, WIFI_PASS);
      //Wait for connection
      int wificount = 0;
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      if (WiFi.status() == WL_CONNECTED) {
        connection = true;
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        while(!pingtest){
          Serial.println("Pinging Server");
          if(Ping.ping(dbServer) == true){
            pingtest = true;
          }else{
            Serial.print(".");
            delay(1000);
          }
        }
      }

    }

void loop() {
  Serial.println("Hello");
  delay(2000);
}

Update (Cross posted from another forum):
I have an Arduino which pings a server on a different VLAN / subnet as part of its code.
It was working a while ago, but I changed some settings on my firewall to restrict stuff down, and that broke the Arduino code.
I found it was because I was blocking ICMP across VLANs.
So I created a rule to allow ping requests between the two VLANs
tested on my desktop (on same net as Arduino) and works fine.
Went to test on Arduino and wasn't getting any response.
So I put the router IP in and tested it on the Arduino, works fine. I can even ping the Arduino from my desktop, and ping my desktop from the Arduino
So I figured I must have some other firewall rule allowing my desktop to have special access. (not that I could find it)
so gave the arduino the same Ip address and no luck, yet can still ping the router
I have attached a crude drawing here. Hopefully it helps to visualize my problem.

try to erase the flash memory with esptool to clear old RF settings, then upload the sketch and wait a couple of minutes until RF settings calibrate

That didn't work
Erased the flash on both devices and now they are both failing to ping, or to do my web request later in the code.

ok, not sure if its a routing issue or a arduino issue as im getting some odd test results.
Will update original posting with new findings

did you let it time to calibrate the RF part?

Yes, have updated the original posting with more information

If a ping doesn't work over a routed connection it could be.

Default gateway on the Arduino device, add a Serial.println(WiFi.gatewayIP().toString()); to print the default gateway.
DNS issue, I presume that the const char* dbServer = "webaddress"; indicate a FQDN.
Firewall is blocking the ICMP on either the inbound or outbound path.

Have done alot of testing on another forum, and have come to the conclusion its the arduino not wanting to send requests to a very specific IP range.
For testing I have the following setup
Desktop PC: 192.168.1.100, arduino 192.168.1.222 (Vlan 10)
Server 1: 192.168.99.40 (Vlan 99)
Server 2: 192.168.4.200 (Vlan 40)
I can ping both servers fine from my desktop pc.
I can ping google, the router, and server 1 from the arduino, but not server 2.
I did a packet capture on the WiFi access point, and can see the ICMP packets for the other pings going though, but not when pinging server 2

I have also set a laptop to have the same IP address as the arduino (After turning the arduino off to avoid conflicts) and the ping goes though fine.
I have also confirmed that the gateway ip and netmask are set correctly on the arduino.
and I have removed any domains from the scripts for testing, using just IP addresses to try remove DNS issues

Add a sniffer to vlan 10 and have a look at whet the Arduino is sending. And check what the firewall log is saying/blocking.

Not to come across as rude.
Just I have already mentioned this twice. Did a pcap on the wifi AP and dont see any requests from the arduino when pinging the 4.x range, but i do with the other ping requests. And the firewall shows the same, logs for all my ping tests except 4.x range


text:
Arduino UNO WIFI Rev 2 - MySQL trouble
I'm using an Arduno UNO WiFi Rev 2 and trying to connect to a database, but it does not connect nor shows any errors.
The arduino connects successfully to WiFi and pinging google works fine.
But when I add the part to connect to database, on line: 65, the script just stops at "DB Connecting..." on the line above.
Inside Arduino IDE you can see a difference between the includes, the MySQL ones are not luminated:
https://i.stack.imgur.com/ERD0N.png
This is how the code looks like:
#include <SPI.h>
#include <WiFiNINA.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

// MySQL Information
IPAddress server_addr(111,222,333,4);
char user[] = "arduino"; // MySql username
char password[] = "qwerty"; // MySql password

WiFiClient client;
MySQL_Connection conn((Client *)&client);

// WiFi Information
char ssid[] = "Router-SSID";        // your network SSID (name)
char pass[] = "router-pw";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

// Specify IP address or hostname
String hostName = "www.google.com";
int pingResult;
int pingWorks = 0;

void setup() {
  pinMode(hallPin, INPUT);
  pinMode(LED, OUTPUT);

  Serial.begin(115200);

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }

  // you're connected now, so print out the data:
  Serial.println("You're connected to the network");

  printCurrentNet();
  printWiFiData();

  delay(2000);
  Serial.println(server_addr);
  Serial.println(user);
  Serial.println(password);
  // Connected to the WiFi lets continue..
  Serial.println("DB - Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(500);
    Serial.print ( "." );
  } else {
    Serial.println("Failed to connect..");
  }
  Serial.println("Connected.");
}

void loop() {
  runWifi();
}

void runWifi() {
  if (pingWorks == 0) {
    Serial.print("Pinging ");
    Serial.print(hostName);
    Serial.print(": ");

    pingResult = WiFi.ping(hostName);

    if (pingResult >= 0) {
      Serial.print("SUCCESS! RTT = ");
      Serial.print(pingResult);
      Serial.println(" ms");
      pingWorks = 1;
    } else {
      Serial.print("FAILED! Error code: ");
      Serial.println(pingResult);
      pingWorks = 2;
    }
  } else {
    Serial.println("Ping on google works..");
  }
  delay(200);
}

void printWiFiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP address : ");
  Serial.println(ip);

  Serial.print("Subnet mask: ");
  Serial.println((IPAddress)WiFi.subnetMask());

  Serial.print("Gateway IP : ");
  Serial.println((IPAddress)WiFi.gatewayIP());

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:
  byte bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI): ");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type: ");
  Serial.println(encryption, HEX);
  Serial.println();
}

void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}

What can be the problem?
No working libs for WiFi uno rev 2?

can you connect to your mysql server from other computer?

Yes, that works.