text:
How to power multiple LEDs with a microcontroller
I currently have a "tiny" setup and want to put a few (~20-30) 0402 LEDs on a 1:87 scale car. My current setup is an ATtiny85 USB Mini Dev Board powered by a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger:
To my bitter disappointment one cannot connect the leds in series. I've read about charlieplexing which was a little mind boggling for me to comprehend.
I was going to break down the leds and pins as follows:

P0 - headlights (2x white 0402 LEDs) +  tail lights (2x red 0402 LEDs) - in series - in parrallel
P1 - blinkers (4x amber 0402 LEDs) - in series - in parrallel
P2 - siren (12x amber 0402 LEDs) - in series - in parrallel
P3 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P4 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P5 - beacon (2x blue 0402 LEDs) - in series - in parrallel

Question:

With space being limited inside the model car how would I be able to
drive 20-30 LEDs with the above set up?
I am in doubt that the models in the video use charlieplexing and use a similar microcontroller, how would they be doing this?
Would it be better for me use something like a Pro Micro ATmega32U4 5V 16MHz and spread the LEDs across the 16 pins (ie 2 LEDs per pin = total of 32 LEDs)?

No, you will never want to put the LEDs in series. You will have to put them in parallel. Some LEDs have a forward voltage of about 3V if you put them in series you will have to provide 6V to turn them on. You can't do that with just 5V.

I see no reason why you would not be able to light 30 LEDs.
ATtiny85 only has 5 pins for use (unless you want to use the reset pin as well in which case hell will cover you). So with charlieplexing you are going to be able to address 20 endpoints. (where each endpoint might consist of multiple LEDs)
But beware. You CAN address 20 endpoints but you CANNOT light every combination simultaneouly. You will have to work out if there is a constellation that allows you to light all lights you want in the same time or you will have to use one of the timers to toggle between different lights. I don't know how well it works thou.
I have managed to use a timer on an 8MHz device to drive 4 LEDs at 400Hz directly without charlieplexing and not using PWM. So I assume it will be possible but might be flickering.
It would definitively be easier. I always recommend to stick to things that are well known and widely used. That would fit your ATmega32U4.

Make sure you layout your LEDs and think how you want to address them and if it makes sense to join multiple LEDs to one pin and toggle them at once.

so 2x 0402 leds per pin on a Pro Micro ATmega32U4 5V 16MHz would work well? Would the Pro Micro be able to supply enough voltage & current for 2 0402 leds?

Yes, the pin will usually provide enough current for two LEDs in parallel. You will have to limit the current by using a current limiting resistor. BUT you will have to worry about the current of all pins together. From the datasheet p.383 states you can draw at most 40mA per pin and 200mA in total. Those are absolute maximum before it will blast. Usually you aim to never exceed half of it. You will have to look up the current of your LEDs to see if you can drive them directly or have to use a transistor.

half of 200mA is 100 mA; @ 20mA per 0402 LED I can only run 5 LEDs at any given instance?

@3kstc you probably don't want to run those leds at 20mA or your model car will be to bright to look at. Using transistors will bypass this issue. This could be a good option for the headlights, as you want to run those at max output. PS the red leds you might be able to run in series.

@Gerben - I can maybe PWM them so that they aren't too bright? Would the brightness of a LED and current drawn be in a linear relationship - (ie 20mA = 255PWM, 127PWM = 10mA?)

Yes, you can do that but this is the average power output. You still have periods of 20mA and 0mA. The peaks do count if it comes to the absolute limits. ATmega32u4 seems to have enough PWM channels.


text:
Avrdude & micro clone
I am trying to program a Pro Micro clone (black PCB, 5v), using this command
avrdude.exe -p atmega32u4 -c avr109 -U flash:w:pro_micro_ISP_B6_10.hex:i -P COM3

but this is the (obviously incorrect) output I get:
Connecting to programmer: .
Found programmer: Id = "╞ ("; type = b
    Software Version =  . ; Hardware Version =  .
avrdude.exe: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

It has never been flashed before. All three lights are illuminated when I plug it in. I am pretty sure COM3 is the right port.
What's going on here? Is my USB cable bad or something? I actually had this problem on two separate units, so I know the board itself is fine.

can you upload from Arduino IDE?

I actually had this problem on two separate units, so I know the board itself is fine ..... that conclusion makes no sense .... maybe you have two bad units

source: Stack Exchange

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

sort: votes


text:
Interpreting pull-up values Rp and Rpu in AM3202 (DHT22) datasheet
In the AM2302 datasheet at page 3, table 4, it gives min, typ and max values for Rpu (that the pull-up resistor as it says verbatim) being 30K, 45K and 60K ohm respectively.
Elsewhere in the same table it gives figures for Rp (no u) < 25K ohm.
What is the difference between Rpu and Rp here, and how should the two rows be interpreted?

The datasheet is as inaccurate as the sensor itself and it is even worse than you think!
In that datasheet is also written: "usually require an external about 5.1kΩ pull-up resistor".
In the datasheet is also mentioned that the output signal can go up to 8 mA for a high output and minimal 10 µA low output. The 10 µA means that the pullup resistor should be 500k or more. That is not correct.
In this datasheet is a picture with 1k.
In this Chinese datasheet is a picture with 5k.
I ran that Chinese datasheet through Google Translate, but that did not help.
Conclusion: The datasheet is not reliable.
You can do as everyone else: use a 10k resistor for short wires, and try 4k7 for longer wires.
That is not the only problem. Some DHT libraries create a shortcut on the data signal.
The AM3202 is not accurate for measuring the humidity. If you want to avoid trouble, then use a better sensor.
A sensor from Bosch is a good choice (for example the BME280 or BME680). Bosch makes datasheets that are reliable. Those sensors from Bosch operate at 3.3V, if you are going to connect that to a 5V Arduino board, then you need level shifters for the signals.

Thanks @Jot. Any idea on the accuracy on the figure of 2s between reads?
Instead of the "default" Adafruit library, I've looked at this and this which have much cleaner code for my project which is not accuracy critical.

Any reason not to use INPUT_PULLUP instead in this case? Actually, I asked this as a separate question: Using a pull-up resistor vs INPUT_PULLUP / OUTPUT_PULLUP

@TomHale Those sensors are not getting better with more than 2 seconds in between. You should ignore everything that is written in the datasheet about accuracy, it is a bunch of nonsense. It is the sensing element that is unreliable. As far as I can tell, both of the libraries that you mention do not put the data line as output and high (that creates a shortcut). So both are okay. The internal pullup resistor of the arduino is between 30k and 50k, that value is too high to be reliable, and the value is different for different arduino boards. You can use it for a test, it will probably work.

Cheers. FYI, the datasheet says 20K-50K, as shown the pull-up question.

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


text:
Motors triggering Interrupt
I am using a 4wd robotic car to measure straight distances. I have attached two encoders on the front two wheels to measure the distance and I am using the back two wheels to adjust the car and keep it driving straight by using a compass as a reference. The Problem is that when my program is executing the section that drives the back wheels this somehow triggers the interrupt and increments the number of ticks. What is causing this issue?
volatile unsigned long enc_l = 0;
volatile unsigned long enc_r = 0;

void driveStraight(float drive_distance, int motor_power)
{
  Serial.print("\n");
  Serial.println("num_tick_l \t num_tick_r \t diff_l \t diff_r \t enc_1_prev \t enc_r_prev \t Power_l \t Power_r \t Power_a \t Power_b ");

  unsigned long num_ticks_l;
  unsigned long num_ticks_r;

  // Set initial motor power
  int power_l = motor_power;
  int power_r = motor_power;

  // Used to determine which way to turn to adjust
  unsigned long diff_l;
  unsigned long diff_r;

  // Reset encoder counts
  enc_l = 0;
  enc_r = 0;

  // Remember previous encoder counts
  unsigned long enc_l_prev = enc_l;
  unsigned long enc_r_prev = enc_r;

  // Calculate targer number of ticks
  float num_rev = (drive_distance * 10) / wheel_c;   // Convert to mm
  unsigned long target_count =  29; //num_rev * counts_per_rev;

  /*
    // Debug
    Serial.print("Driving for ");
    Serial.print(drive_distance);
    Serial.print(" cm(");
    Serial.print(target_count);
    Serial.print(" ticks) at ");
    Serial.print(motor_power);
    Serial.println(" Motor Power");
  */

  //Drive until on of the encoders reaches desired count
  while ((enc_l < target_count) && (enc_r < target_count))
  {

    bluetooth();                                // if new bluetooth value received break from loop
    if (blueToothVal == 5) {
      break;                                    // If a 'Stop' Bluetooth command is received then break from the Loop
    }

    // Sample number of encoder ticks
    num_ticks_l = enc_l;
    num_ticks_r = enc_r;

    // Sample out current number of ticks
    Serial.print(num_ticks_l);
    Serial.print("  \t\t");
    Serial.print(num_ticks_r);

    // Drive
    drive(power_l, power_r);

    // Number of ticks counted since last time
    const int StraightDriveOffset = 1;                    // Increase this or even make it a negatie number to tweak the

    diff_l = num_ticks_l - enc_l_prev;                    // + StraightDriveOffset;
    diff_r = num_ticks_r - enc_r_prev;

    Serial.print("  \t\t");
    Serial.print(diff_l);
    Serial.print(" \t \t");
    Serial.print(diff_r);

    // Store current ticks counter for next time
    enc_l_prev = num_ticks_l;
    enc_r_prev = num_ticks_r;

    Serial.print("   \t \t");
    Serial.print(enc_l_prev);
    Serial.print(" \t \t");
    Serial.print(enc_r_prev);

    // If left is faster, slow it down and speed up right
    if ( diff_l > diff_r) {
      power_l -= motor_offset;
      power_r += motor_offset;
    }

    // If right is faster, slow it down and speed up right
    if ( diff_l < diff_r) {
      power_l += motor_offset;
      power_r -= motor_offset;
    }

    // Debugging
    Serial.print(" \t\t");
    Serial.print(power_l);
    Serial.print(" \t\t");
    Serial.println(power_r);

    // Brif pause to let motors respond
    delay(20);
  }

  StopCar();
  //Buzzer();
}

void drive(int power_a, int power_b)
{
  getCompass();                                                     // Update Compass Heading
  bluetooth();                                                      // Check to see if any Bluetooth commands have been sent

  if (blueToothVal == 5) {
    break; // If a Stop Bluetooth command ('5') is received then break from the Loop
  }

  // Constrain power to between -255 and 255
  power_a = constrain(power_a, -255, 255);
  power_b = constrain(power_b, -255, 255);

  if ( abs(desired_heading - compass_heading) <= compass_dev )      // If the Desired Heading and the Compass Heading are within the compass deviation, X degrees of each other then Go Forward
    // otherwise find the shortest turn radius and turn left or right
  {
    // Left motor direction
    if ( power_a < 0)
    {
      motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
      motor2.run(BACKWARD);

    }
    else
    {
      motor2.setSpeed(abs(power_a));       // Motor is the front left wheel
      motor2.run(FORWARD);

    }

    // Right Motor direction
    if ( power_b < 0)
    {
      motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
      motor4.run(BACKWARD);

    }
    else
    {
      motor4.setSpeed(abs(power_b));       // Motor is the front left wheel
      motor4.run(FORWARD);

    }

  }

  else
  {
    int x = (desired_heading - 359);                          // x = the GPS desired heading - 360
    int y = (compass_heading - (x));                          // y = the Compass heading - x
    int z = (y - 360);                                        // z = y - 360

    if ((z <= 180) && (z >= 0))                               // if z is less than 180 and not a negative value then turn left
    { // otherwise turn right
      motor1.setSpeed(190);
      motor3.setSpeed(190);
      motor1.run(BACKWARD);
      motor3.run(FORWARD);
    }
    else
    {
      motor1.setSpeed(190);
      motor3.setSpeed(190);
      motor1.run(FORWARD);
      motor3.run(BACKWARD);

    }
  }
}

void countLeft()
{
  enc_l ++;
}

void countRight()
{
  enc_r ++;
}

and this is what is on the setup function
const int enc_l_pin = 18;
const int enc_r_pin = 19;

void setup()
    {
      Serial.begin(115200);                                            // Serial 0 is for communication with the computer
      Serial3.begin(9600);                                             // Serial 1 is for Bluetooth communication - DO NOT MODIFY - JY-MCU HC-06 v1.40

      Wire.begin();                                                    // Join I2C bus used for the HMC5883L compass
      compass.begin();                                                 // initialize the compass (HMC5883L)
      compass.setRange(HMC5883L_RANGE_1_3GA);                          // Set measurement range
      compass.setMeasurementMode(HMC5883L_CONTINOUS);                  // Set measurement mode
      compass.setDataRate(HMC5883L_DATARATE_30HZ);                     // Set data rate
      compass.setSamples(HMC5883L_SAMPLES_8);                          // Set number of samples averaged
      compass.setOffset(118, 473);                                      // Set calibration offset

      // Buzzer
      pinMode(Buzzer_pin, OUTPUT);

      // Set up pins
      pinMode(enc_l_pin, INPUT);
      pinMode(enc_r_pin, INPUT);

      // Set up interrupts
      attachInterrupt(digitalPinToInterrupt(enc_l_pin), countLeft, CHANGE);
      attachInterrupt(digitalPinToInterrupt(enc_r_pin), countRight, CHANGE);

I don't see any interrupt code. Please provide a complete (!) working minimal example code, that shows your problem.

Yes, sorry I just added them in

Do you have a pullup or pulldown resistor? If not, the pin will be floating.

When I try to put a pull up resistor accross the +vcc and output pin of the hall effect sensor as shown in the picture the voltage stays constant

What type of hall sensor do you use exactly?

UGN3503UA Hall Effect Sensor    https://www.jaycar.com.au/medias/sys_master/images/9168322953246/ZD1902-dataSheetMain.pdf

I think you have 2 problems:

The used Hall sensor is an analog device, not a digital one. This means it will not output either Vcc or 0V, but instead an analog (continuous) voltage depending on the magnetic field. With zero magnetic field, it will output about half the supply voltage (in this case 2.5V, since Vcc is 5V for you). For analog signals pullups or pulldowns do not make sense. Digital pins have a hysteris, which means, that they will detect a LOW between 0V and 1.67V and a HIGH between 3.33V and 5V (see this answer). This is also called a Schmitt trigger. I assume, that you just want to measure, that the magnet comes near the sensor (so only one polarity matters). This means, that the voltage will stay - let's say - above 2.5V (depending on polarity) and only going from 2.5V to 5V and back. In this condition the pin state will stay high, since it is set high, but never reaches voltage low enough for setting it to low. No interrupt will be triggered. Depending on what you want and the next problem, you can instead use a comparator (which is a special peripheral of the microcontroller) to trigger the incrementation, when a specified threshold voltage is reached (this also mean it would trigger due to small changes around the threshold), or you can buy or build an external Schmitt trigger, where you can change the threshold voltages for LOW and HIGH changes.
Motors send out quite a bunch of electromagnetic noise, which can distort analog Signals nearby. Most likely the noise from the motors is high enough to falsely trigger a state change at the pin. Maybe you should look at the analog signal with an oscilloscope, which can show you, how much noise do you really have in this situation. There are many ways to reduce noise on an analog signal. One is to add a low pass filter to cancel out the mostly higher frequency noise. This only works, if the frequency of your signal is considerably lower (so that you can trim the low pass filter to let your signal pass).

From the picture I cannot see, how the magnets and the sensors are moving in the car. Be sure to measure the different voltages in the different states (magnet near sensor, magnet for away). If the sensor is too sensitive or your magnet too strong, you might end up with an even smaller voltage range, than the 2.5V, that you already have.

Thanks for the valuable information. I will work on designing the schmitt trigger and let you know how I go.

I built a non-inverting Schmitt Trigger. The circuit diagram can be seen in the post. The issue I am having is that once I connect the output pin of the hall effect sensor to the input of the schmitt trigger the input stays 3.3V and the output reads about 4.22V.


text:
How to program the Robotdyn Mega 2560 PRO MINI?
I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.
How do I connect the pins to an FTDI?
Which setting do I have to use in the Arduino IDE?

Connect the Arduino to the FTDI in the following way:

FTDI - Arduino
VCC - VCC
GND - GND
RX - TXD
TX - RXD
DTR - 100nf capacitor - RST
CTS is not connected

Use the following settings in the Arduino IDE

Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

The image shows the Arduino with colored connectors and with 4 extra rows of connectors. These are not part of the original Arduino. I added them to make it easy to connect lots of I2C devices for testing.


text:
Run code once after programming
I'm using EEPROM to store project settings non-volatile.
After reuploading the sketch to my board (over SPI via ArduinoISP), the EEPROM is reset to full 0xFFs and I have to manually do a "software reset" with a second switch, which initializes the EEPROM with its default values.
Is it possible to run a segment of code once, and only once, after booting up the first time after being programmed?
I'm working around it by checking whether a piece of EEPROM is 1 at startup when it would always be 0 after the initialization and during usage, but surely there's a cleaner alternative than checking for an EEPROM bit each time.

Personally I think your way is very clean, program an EEPROM bit, set it, and change it after doing a one time initialization. It's also very flexible, in case you want to do it multiple times (just use a counter in EEPROM for example). Or in case the initialization is not done correctly, you can omit resetting the bit.

change the high fuse setting in boards.txt to preserve the EEPROM content at ISP

@Juraj The solution with the fuse has worked, although I had to flash it manually through avrdude (D6 instead of DE).
Is it normal that changing it in the boards.txt would not update it when flashing (/ flashing using ArduinoISP)?

The fuses are only written when you select the "burn bootloader" option in the Arduino IDE. PS You can also use AVRdude to write to the EEPROM directly.

see the EEPROM library's eeprom_crc example

This is a X->Y problem. Here is a solution for X:
Bit 3 of high fuse of the ATmega328p controls if EEPROM memory is preserved through the chip erase. You can change the high fuse setting in boards.txt. Restart the IDE to apply the new setting.
The fuses are written when you select the "burn bootloader" option in the Arduino IDE.

I feel like editing the boards.txt file is a bit less "portable" than I'd prefer. I believe checking whether an EEPROM that's guaranteed to be 0 after initialization is 1 (after flashing) is cleaner.

portable? someone else will flash it over ISP?

Yes, unfortunately. I've described how to wire the ArduinoISP up to the project board and how to flash it using the IDE, but editing the file seems a bit too much.

I've actually done some tinkering with this sort of thing, or alternatively how to ensure previous EEPROM (or similar) settings are formatted on upload of a new sketch.
There are two values (C macros, in this case) that are baked into a program when it is compiled (for Arduino, the program is recompiled on each upload) that can be used to tell if the programming is "fresh."
The values you'd want are __DATE__ and __TIME__. They are converted to char arrays (strings, basically) at the time the compiler is run. You can store them directly to EEPROM, or use some sort of hash to convert it to a convenient number to store instead. Then, whenever the code boots, compare the stored value with the one computed from the values coded into the program. If they differ, overwrite the stored value with the new one and execute the run-once code.
Something along the lines of
byte i=0;
char checkVal[]=__TIME__ __DATE__;
for (int j=0; j<strlen(checkVal); j++){
  i+=(byte)checkVal[j];//Creates a modulo 256 sum of the ASCII values of the chars (really poor hash)
}
if(EEPROM.read(26)!=i){//stored EEPROM location (arbitrary) -- feel free to use wear leveling, though, or some other method
  //DO RUN-ONCE CODE HERE
  EEPROM.write(26,i);//store the new value to stop it running again
}


text:
I cannot compile the Arduino sketch when I remove the void loop function?
#include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_64KHZ);

void movefor ();

void moveback();

    void setup()

    {

    Serial.begin(9600);

    Serial.println("Motor test!");` `motor.setSpeed(200);

    movefor ();
    moveback ();
    }

        void movefor( ){
        motor.run(FORWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

    void moveback( ) {
      motor.run(BACKWARD);
    delay(1000);
    motor.run(RELEASE);
     delay(100);
    }

While trying to compile this the error message is error compiling for board Arduino Uno
I want the functions outside loop so removed it.
Even if I keep void loop and leave it blank then my motors will like run forward, backward and forward afterwards continuously .

you get an linker error because the main function in core main.c calls the loop() function. it must exist.

Error is " cannot compile for the board Arduino Uno"

turn on verbose mode in Preferences

You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.
Just make your loop function look like this:
void loop() {
    movefor ();
    moveback ();
}

Your motor will move forward, then move backwards, forever.
Note that you should read up on how to avoid using the delay function. You really need to use millis() to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.

There must be something wrong within the motor, circuit or the motor class.
What happens is when you use a setup and loop is the following:
setup();
while (1) { loop(); }

So the loop function is executed forever, if it is empty, nothing will happen. If you say that the motor runs forward, it is probably because of a wrong implementation of the motor class.
Arduino IDE dictates there is always a loop, and having an empty loop is the same as having no loop at all.
What you can try is:

In the setup, only execute movefor() and check what happens
Than only execute moveback() and check what happens
Than make combinations and see if the problem is inside movefor or moveback

For the first steps you can add a delay to easier see if there is a side effect.

I have tried what you said and code is working good  . I want forward motion then backward.   After this I want the same to be continuously moving forward and backward. But the problem that occurs is that it will always move forward after 1 forward and backward motion.  I think the loop is being continuously called and that is disturbing that's why I want to remove the loop. Maybe the  problem is in header file but how can I check this file?

you should get what you want when adding in setup: while(1) { movefor(); moveback(); } but I doubt that will work either. The header file can be found where you installed the library, you always can do a file search on your PC (crude way but it works; I don't know by head where the libraries are stored).

I have the AFMotor library in Documents-Arduino-libraries-AFMotor , everything looks fine here


text:
Latest datasheet for Leonardo's ATmega32U4
What is the authoritative source(s) for the ATmega32U4 (or any Arduino chip for that matter) datasheet?

the manufacturer is Microchip. https://www.microchip.com/wwwproducts/en/ATmega32u4

4/2016 does appear to be the latest datasheet for the Atmega32U4. If you go here www.microchip.com and select Design, then Documentation, then Datasheets, then Search by Products, you can enter a part number. Entering Atmega328P brings up the complete datasheet dated 1 Nov 2018. You can check that to see if there is more characterization data.
(question was originally about characerization of ADC for '32U4 and other sources of info on same, hence the '328P reference here).


text:
Use 2 DHT22 AND PASS THE DATA TO SD Error File data does not exsist
anyone can help me please to fix this error when I try to compilate says File does not exsist. It would be great if anyone can post the entirely code.
Link of code below if anyone can help me please:
https://create.arduino.cc/editor/Jawad2001/5ea57339-7ca1-4f8d-ab00-f4f1aa639209/preview
error: expected')' before 'f'
Sorry I'm new at this sorry for the annoyances.
Thanks For all your Help.

#include <SD.h>;

I don't know why but says expected initializer  before "." token

sorry, without ;. it should be #include <SD.h>

I know but i did it without ;

i don't know why but the program says the error is in Filedata2.txt

this line is defining a variable File data.txt;  (it is actually an object) .... you cannot have a period . in a variable name, maybe use an underline instead. File data_txt;

It helped but now i have other problem in void get data

data_file was not declared in this scope i publicated the new errors

@jawadbouhali, i formatted the error printout so that it was readable and you messed it up again ...... please use the {} to format the error printout

data_file was not declared in this scope ..... are you saying that you declared the variable name data_file?   ..... where did you declare it? ....... please look at the errors one at a time and try to figure out why they are being presented ....... do not look at all of the errors at the same time, that leads to confusion

The code needs to be inside the post, not behind a link.

Here are several things I can see from your code that cause most of the error messages.
1) You declare
File data_txt;
File data2_txt;

but you later use data_file and data_file2. This is why you see the "not declared in this scope" errors.
2) You do not properly define the functions getData() and getData2(). You start with the definition of getData2() inside the function getData().
First finish the function getData() by closing all brackets you opened and then define the function getData2(), like this:
void getData() {
//the code of getData() goes here....
}

void getData2() {
//the code of getData2() goes here....
}

3) I assume you want to write to data_file in getData() and to data_file2 in getData2()?! Nevertheless, you also use data_file in getData2().
Update after your edit:
Regarding the compilation error, you do not open a curly bracket
{
after getData2().
However, there are several other issues that will lead to problems, even if it finally does compile without problems.


text:
Stuck Arduino Relay?
I am looking for a relay that stays on (NC=Normally Closed), and when I send a new signal switches to off (NO=Normally Open).
So the relay doesn't consume any power while being in a specific position.
Do you guys know any type?
Thanks :)

google latching relay ..... two different types available

Finally, I found it!
Google Image:
https://www.google.com/search?biw=1974&bih=1050&tbm=isch&sxsrf=ACYBGNSImNFTI2vRTPD5bbjE-eRkJUzdow%3A1571311366907&sa=1&ei=Bk-oXcSJN5K78gKG4brgCw&q=HFD2%2F005&oq=HFD2%2F005&gs_l=img.3..0j0i24l6.1135292.1138931..1139132...0.0..0.80.289.4......0....1..gws-wiz-img.......0i5i30j0i30.yfdL1Ivd0sU&ved=0ahUKEwjEpOz-lqPlAhWSnVwKHYawDrwQ4dUDCAc&uact=5
Aliexpress:
https://www.aliexpress.com/item/32988578668.html?spm=2114.13010708.0.0.57a64c4dkzjFcM

Digikey.com & Mouser.com also offers a wide range of latching relays with same day shipping available.


text:
Do I have to use Arduino IRRemote libraries?
I have seen some tutorials to build your own IR Remote. But all of them use a library that contains the IR code. The question is, could I just skip, injecting a library and make the Arduino output a IR signal?

Sure. If you really want to spend the time needed to both understand the IR protocol and write the code to generate the right signals.

it is fairly simple if you only want to emulate one remote control and only a few buttons ...... have you researched the TV remote control IR protocol? .... do you have any experience with an Arduino?

I dont even have a single Arduino. I thought it would be easier, but the libraries include the ir codes? Because I need ALL Power off ir codes.

google tv-b-gone   .... https://github.com/shirriff/Arduino-TV-B-Gone


text:
How to initialize digital output pin as low
I need to define a pin as output for relay module but when i do it in setup section, relay is activated (low - 0) automatically then i deactivated immediately with coding digitalWrite(pin, 1) but this issue results the relay is activated then deactivated within miliseconds. But I want to know that is it possible to define a pin as output but low in default.
void setup(){
  pinMode(pin,OUTPUT);
  digitalWrite(pin,1);
}

void loop(){
  if(start_relay){
    digitalWrite(pin, 0);
  }
}

you have a relay module which disconnects if signal is HIGH. the AVR MCU starts with pins in INPUT mode so the relay is not controlled by Arduino until setup()

You mean you want OUTPUT HIGH without an OUTPUT LOW transient?

There are two solutions:

Use the pin as a open-collector pin as in the answer of VE7JRO.
Switch the pin between input (high) and output with low. I prefer
to use the INPUT_PULLUP.
Write the output value before setting the pinMode.

All the microcontrollers of the AVR family (ATtiny and ATmega chips) allow to set the output value before setting the pin as output. This will enable the pullup resistor, but when it is done in the right order, that is fine.
Because this is a common way to use the microcontrollers and processors, the Arduino libraries allow to use that. The Arduino libraries for the SAMD processors (Arduino Zero, M0 and MKR) are written to allow that as well.
void setup() {
  digitalWrite(pin,HIGH);     // pre-set output value to HIGH
  pinMode(pin,OUTPUT);        // set to output, it will be HIGH
}

void loop() {
  digitalWrite(pin,LOW);
  delay(1000);
  digitalWrite(pin,HIGH);
  delay(1000);
}

When the relay module has floating inputs (as far as I know they do not) then you need extra hardware to pull the signal high with a pullup resistor to keep the relays disabled during reset.

If you have a relay that is activated by a LOW or ground path, and is deactivated
by an open circuit or HIGH signal applied, then you could try switching the pinMode
to act as the HIGH or open circuit.
const byte pin = 2;

void setup(){

  // Define the pin as INPUT_PULLUP until you are ready to use it.
  pinMode(pin, INPUT_PULLUP);

}

void loop(){

  delay(1000);

  // Activate the relay. Supplying a low impedance
  // path to ground turns the relay on.
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);

  delay(1000);

  // Deactivate the relay.
  pinMode(pin, INPUT_PULLUP);

  // Using digitalWrite(pin, HIGH); is an alternative to using
  // pinMode(pin, INPUT_PULLUP); If your relay module is the
  // same as the one shown below, then it doesn't matter which
  // method you choose.

}

I'm not sure which relay module you are using, but if it is the same as this type, using INPUT_PULLUP will work.

As Edgar Bonet mentions in his comment to kot's answer, using pinMode(pin, INPUT_PULLUP); is clearer than using digitalWrite(pin, HIGH);.
This code does 2 things:
digitalWrite(pin,HIGH);
pinMode(pin,OUTPUT);

First it sets the pin to INPUT_PULLUP, then it sets it to VCC (for lack of a better term). If you connect a modern LED with a 1k ohm resistor to pin 2, and use this sketch, you can see the LED "dimly" lit for 5 seconds, then it is "brightly" lit.
const byte pin = 2;

void setup() {

  // pre-set output value to HIGH
  // The internal pull up resistor is now connected to the pin.
  digitalWrite(pin,HIGH);

  // Wait for 5 seconds.
  delay(5000);

  // set to output, it will be HIGH
  // The pin is now connected to VCC (for lack of a better term).
  pinMode(pin,OUTPUT);

}

void loop(){}

As fas as I know, by default digital pins are set as inputs. Arduino has internally only pull-up resistors, which you can use in that way:
digitalWrite(pinOut[i], HIGH);

in first setup() line (without pinMode(pinOut[i], OUTPUT);).
If you need LOW state on start-up (pull-down resistors), you have to use an external resistor.

If you want to activate the internal pull-up, pinMode(pin, INPUT_PULLUP); is clearer (because more explicit) than digitalWrite(pin, HIGH);.


text:
Arduino Uno - temperature sensor DS18B20 not responding
I try to use a new DS18B20+ temperature sensor (sealed water proof version).
It doesn't work. My own code doesn't work, examples from DallasTemperature Library don't work, example from OneWire library doesn't work.
For example function sensors.getDeviceCount(); (DallasTemperature library) returns '0'.
Function tempSensor.getTempCByIndex(0); returns 65409 (int variable). !ds.search(addr) (OneWire library) also always return '0'. Then I am sure, Arduino code is alright.
I am sure DS18B20 is connected correctly:

white wire (onewire data) - onewire Arduino pin (tested with pin 2 and pin 13)
red wire (+V) - 5V Arduino pin
black wire (GND) - GND Arduinp pin
between 5V and DATA there is a 4k7 resistor

I have measured resistances between the temperature sensor's wires:

'+V' to 'data': 4,7 kOhm
'GND' to 'data': ~3 Ohm

I think between the GND and DATA sensor wires resistance should be much higher - am I right? Below you can see a block diagram copied from the sensor datasheet (https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf):

Maybe black and white wires are +V and GND (which one is +V?), red is data? Or it's broken? Or something else?
I have bought it here - https://botland.com.pl/pl/czujniki-temperatury/10936-sonda-wodoodporna-z-czujnikiem-temperatury-ds18b20-5m-brazowy-silikon.html?search_query=sonda+temperatury&results=43 (language: polish). it is written:

VCC - red
GND - black or green
data 1-wire - white or yellow

between 5V and GND there is a 4k7 resistor the diagram tells you to pullup the data line (DQ) to V_PU (5V), not between 5V and ground. That is just a power dissipator.

Yes, sorry, it was a typo. 4k7 is between the data and +V.

Can you verify the meaning of the wire colors according to the package information of the datasheet? All the "DS18B20+" I see on e.g. digikey don't have color-coded wires on them. Do you have a link to where you bought them?

First post edited (added a link where I bought it)

Did you try to use the code in https://botland.com.pl/pl/content/134-arduino-w-polaczeniu-z-czujnikiem-temperatury-ds18b20? Did you, for the fun of it, remove the 4k7 resistor between DQ and VCC and see if that works?

It's a code copied from OneWire library example ('DS18x20_Temperature' example). I have tested it. I havn't removed pull-up resistor, it's a OneWire interface, I think it won't work without pull-upped data line. Is 'GND' to 'data': ~3 Ohm resistance normal? Look, between GND and DATA is a capacitor (DS18B20 block diagram).

If you measure 3 Ohms then there is a short between the wires. The sensor is bad.

When you test the sensor with nothing connected, is the resistance between the red and white wire the same in both directions? Does it change when the temperature changes? Perhaps there is an other temperature sensor inside. But it is probably a shortcut as @Rudy wrote.

Jot, no, it does not. I think thermistor would have higher resistance than 3 Ohm (~23oC).

Yes, thermistors have much higher resistance. Have you measured the resistance in the correct direction? A protection diode might produce a missleading measurement. Otherwise I'd say, your sensor is broke


text:
How to power an Arduino Nano without mini-B USB port?
I'm new to Arduino. I want to power my Arduino Nano with an external DC source, not with already attached mini USB port. I tried, but fail. Please help me to understand it. Thank you.

So what exactly did you try? What power source at what voltage did you connect at which pins?

I want to give 5V and I tried with pins 5v + GND and also with Vin + GND but no success

Should have worked if voltage, polarity and max current draw was correct. Read https://www.open-electronics.org/the-power-of-arduino-this-unknown/ Vin is the input to the 6-12V -> 5V voltage regulator. 5V is just the direct 5V net. Does the Arduino Nano still work when powered via USB or is it destroyed?

and I also tried with 12V on Vin + GND pins but no sign of power on nano

@MaximilianGerhardt Yes, Board is working with USB. LED is lighten up and I have uploaded code also in it

Do you have a multimeter to measure that a voltage is actually applied between the pins? Both methods for powering (Vin + 5V) should work (with the USB unplugged)

Sorry, I don't have multimeter :(

Just a thought in my mind, can it be damaged with static charge? I mean, some of the pins? : \

If it still works now when plugging it in via USB, it's still alive. If your USB port throws the device out, it's dead.

Duplicate of https://electronics.stackexchange.com/questions/60199/powering-arduino-nano-12volts

Thank you @MaximilianGerhardt and MatsK for being so sure and I figured out that it was my mistake to soldering wires loosly (Vin + GND) Sorry and thank you. :P


text:
attiny85 reset itself instead of wakeup procedure
I have a digispark attiny85, and I am using SLEEP_MODE_PWR_DOWN to sleep, and wake-up with external interrupt on pin2. I am trying to count number of interrupts received with the code below.
Problem is on every LOW signal on pin2, attiny85 reset (restart) itself instead of processor wake-up and continue where it left. I can identify this by seeing led blink 3 times(as in setup()) on every LOW signal.
Is there a limitation on this hardware? How can I only wake-up from sleep and not reset? I appreciate if you direct me an example.
#include <avr/interrupt.h>
#include <avr/sleep.h>

//modified from http://playground.arduino.cc/Learning/arduinoSleepCode

int ledPin = 0;            // LED connected to digital pin 0
int interruptPin = 1;      // LED to show the action of a interrupt
int wakePin = 2;            // active LOW, ground this pin momentary to wake up
unsigned int counter = 0;

void setup(){
  pinMode(ledPin, OUTPUT);         // sets the digital pin as output
  pinMode(interruptPin, OUTPUT);   // sets the digital pin as output
  pinMode(wakePin, INPUT_PULLUP);        // sets the digital pin as input
  digitalWrite(wakePin, HIGH);
  counter = 0;
  //do some blinks so we can identify boot & loop
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
}

void sleepNow(){

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                          // enables the sleep bit in the mcucr register so sleep is possible
    attachInterrupt(0, wakeUpNow, LOW);     // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    digitalWrite(interruptPin, LOW);

    sleep_mode();                          // here the device is actually put to sleep!!

    sleep_disable();                       // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);                    // disables interrupton pin 3 so the wakeUpNow code will not be executed during normal running time.
    delay(250);                           // wait 2 sec. so humans can notice the interrupt LED to show the interrupt is handled
    digitalWrite (interruptPin, HIGH);       // turn off the interrupt LED

}

void wakeUpNow(){        // here the interrupt is handled after wakeup

  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
 digitalWrite(interruptPin, HIGH);
}

void loop(){
   digitalWrite(interruptPin, HIGH);
  //digitalWrite(ledPin, HIGH);            // sets the LED on
  counter++;
  delay(5000);                           // waits for a second
  sleepNow();                      // sleep function called here
}

Just a thought, shouldn't the detachInterrupt logic be in wakeUpNow method?

I don't think so Filip, in most example in internet, you can see, wakeUpNow() is optional to use. most people use it empty function.

I found this, I can confirm it is working. on digispark attiny85.
void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}

credits should go
https://www.instructables.com/id/3-Minute-Game-Timer/


text:
How to use one button with interrupt to enable and disable sleep mode?
I have written a program for a kitchen timer. The timer uses just one single rotary encoder with a push button on its axis. It has modes for counting up and for counting down. After counting down it switches into alarm state. When I then push the button the alarm stops and the device goes into sleep mode.
To wake it up I need to either push the button again or twist the encoder.
The problem: When I push the button during alarm the device does go into sleep mode but since that very same button is used to wake it up again, the timer switches into the wrong state and freezes in sleep mode. At least that is my interpretation of the problem:
Pushing the button during alarm triggers sleep mode ( goToSleep() ). During goToSleep I attach to that very button the interrupt that wakes the device.
The solution must be simple, I just can't see it. I just need to ignore any button input beween calling goToSleep() and sleepcpi();. Right?
How can I make this work?
#include <avr/sleep.h>
#include <Rotary.h>
#include <Bounce2.h>

unsigned long timerSeconds = 0;   // Remaining countdown time in seconds. An unsigned int would be enough for more than 18 HOURS!
unsigned long alarmTime = 0;      // The absolute point in time of the alarm

// Variables for updates
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long currCountMillis = 0;
unsigned long prevCountMillis = 0;

// Setup Pins & Variables
Rotary rotary = Rotary(3, 4);     // Needs to be pin 2 or 3 in order to use as interrupt
const byte encBtnPin = 2;         // Needs to be pin 2 or 3 in order to use as interrupt
const byte beepPin = 5;

byte encBtnState;
byte prevEncBtnState;
bool encBtnPushed = false;
Bounce debouncer = Bounce();

// Setup state machine
typedef enum { NONE, SETTING, COUNTING_DOWN, COUNTING_UP, WAS_COUNTING, ALARM } states;
states state = NONE;

void setup() {
  Serial.begin(9600); //remove after testing

  pinMode(encBtnPin, INPUT_PULLUP);
  debouncer.attach(encBtnPin);
  debouncer.interval(10);
  pinMode(beepPin, OUTPUT);

  // Turn off ADC
  ADCSRA = 0;
}

void loop() {
            Serial.println("Top of loop"); // Remove after testing
            Serial.print("State: "); // Remove after testing
            Serial.println(state); // Remove after testing
  switch (state) {
    case NONE:
      goToSleep();
      break;
    case SETTING:
      setCountdown();
      break;
    case COUNTING_DOWN:
      startCountdown();
      break;
    case COUNTING_UP:
      startCounter();
      break;
    case ALARM:
      alarm();
      break;
  }
}

void readEncButton() {
  encBtnState = digitalRead(encBtnPin);     // Check if button state has changed
  if (encBtnState != prevEncBtnState) {
    if (encBtnState == LOW) {
      encBtnPushed = true;
      beep();
    }
  }
  prevEncBtnState = encBtnState;

  if (encBtnPushed) {                     // If Button has been pushed ...
    encBtnPushed = false;                 // ... reset button and do one of the following ...
    switch (state) {                      // Core state machine (state changes)
      case NONE:
        break;
      case SETTING:
        if (timerSeconds != 0) {          // Start countdown only if timer is not = 0 ...
          state = COUNTING_DOWN;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        else {                            // If timer = 0, go to sleep
          state = NONE;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        break;
      case COUNTING_DOWN:
        timerSeconds = (timerSeconds / 10) * 10;        // Set last digit to zero ...
        state = SETTING;                                // ... then go back to setting time
        break;
      case COUNTING_UP:
        timerSeconds = 0;
        state = SETTING;
        break;
      case ALARM:
        state = NONE;
        break;
    }
  }
}

void setCountdown() {
  // Read rotary encoder input
  unsigned long timeOut = millis();
  while (state == SETTING) {
    unsigned char result = rotary.process();
    if (result == DIR_CW) {
      timerSeconds += 10L;
      timeOut = millis();
      writeDisplay();
    }
    else if (result == DIR_CCW) {
      timerSeconds -= 10L;
      timeOut = millis();
      writeDisplay();
    }
    if ( millis() >= timeOut + 30000L ) {         // Go to sleep after 30 seconds idle
      state = NONE;
    }
    // Read rotary encoder button
    readEncButton();
  }
}

void startCountdown() {
  alarmTime = millis() + (timerSeconds * 1000L);  // Determine absolute alarm point in time in milliseconds (only once on countdown start)
  while (state == COUNTING_DOWN) {
    updateDisplay();
    timerSeconds = ( alarmTime - millis() ) / 1000L;            // Calculate new remaining number-of-seconds
    readEncButton();
  }
}

void startCounter() {
  while (state == COUNTING_UP) {
    currCountMillis = millis();
    updateDisplay();
    if (currCountMillis - prevCountMillis > 999) {              // Update counter once per second
      prevCountMillis = currCountMillis;
      timerSeconds ++;
    }
    readEncButton();
  }
}

void updateDisplay () {
  currentMillis = millis();

  // Only once every 1000ms ...
  if (currentMillis - previousMillis > 999) {
    previousMillis = currentMillis;                           // Reset the timer for display updates
    writeDisplay();
  }
}

void writeDisplay() {
  int cHours = timerSeconds / 3600L;                        // Update variables to display
  int cMinutes = timerSeconds % 3600L / 60;
  int cSeconds = timerSeconds % 3600L % 60;
  // Format and print display data
  if (cHours == 0 || cHours < 10) {Serial.print("0");}      // Add leading "0" if necessary
  Serial.print(cHours);
  Serial.print(":");
  if (cHours == 0 || cMinutes < 10) {Serial.print("0");}    // Add leading "0" if necessary
  Serial.print(cMinutes);
  Serial.print(":");
  if (cSeconds == 0 || cSeconds < 10) {Serial.print("0");}  // Add leading "0" if necessary
  Serial.println(cSeconds);
  // Alarm trigger follows here since alarm is supposed to sound AFTER the nillth second has been displayed
  if (state == COUNTING_DOWN && timerSeconds == 0) {
    state = ALARM;
  }
}

void beep() {
  tone(beepPin, 1000, 120);
}

void alarm() {
  int alarmRep = 0;
  attachInterrupt(digitalPinToInterrupt(encBtnPin), endAlarm, LOW);
  while (state == ALARM && alarmRep < 30) {
    for (int i = 0; i < 4; i ++) {
      tone(beepPin, 2000, 100);
      delay(120);
    }
    delay(500);
    alarmRep ++;
  }
  goToSleep();          // Go to sleep after alarm (state is changed to NONE in sleepmode-setup)
  //state = NONE;       // Need condition to prevent state = NONE in case previous while-loop was left due to state change
}

void endAlarm() {
  detachInterrupt(digitalPinToInterrupt(encBtnPin));
  state = NONE;
}

/* Sleep mode and stuff *
************************/

void wakeToSet() {
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  state = SETTING;
}

void wakeToCount() {
  sleep_disable();
  Serial.println("Detaching interrupts ...");         // Remove after testing
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  beep();
  Serial.println("Waking up to count ...");           // Remove after testing
  state = COUNTING_UP;
}

void goToSleep() {
  Serial.println("Starting goToSleep()");             // Remove after testing
  timerSeconds = 0;                                   // Reset everything
  alarmTime = 0;
  state = NONE;
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(3), wakeToSet, LOW);             // Hard-coded to pin 3
  attachInterrupt(digitalPinToInterrupt(encBtnPin), wakeToCount, LOW);   // Encoder button can wake up machine
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  Serial.print("State: "); // Remove after testing
  Serial.println(state); // Remove after testing
  Serial.println("Going to sleep now..."); // Remove after testing
  delay(250);
  sleep_cpu();
}

You need to change to the NONE state on button release, instead of press. Of have the goToSleep function wait till the button is released (while(dititalRead(encBtnPin)==LOW){delay(10);}). I used a PRE-SLEEP state in one of my projects. Then when the button is released and you are in the PRE-SLEEP state, move to the SLEEP (NONE) state.

Thank you. That one line (delay) fixed the whole thing. Thanks. I'll keep the PRE-SLEEP state in mind for future projects.

couple of thoughts: a fritzing Diagram of your Connections may help. as far as i can tell you connect the (?data?) lines of the Encoder to the Interrupt lines? do you want to trigger an Interrupt on Input value Change? like from 4 minutes to 5minutes? did you Thing of debouncing your switches? (just saw you do it in Software... consider a simple RC lowpass instead. Maybe the debouncing uses a timer and then collides with the remaining logic...) do you really Need to now the previous Button state? another Thing i see is you just have an awful lot of Code. consider taking out a piece of paper and draft a state Diagram for the statemachine your About to realise. and then share it here (makes life a lot easier!)

Thank you for your time looking into this. To reply to your questions in order: 1) Trigger an interrupt on input value change? Yes. 2) No. Only during sleep mode. 3) yes but this solution seems easier to implement. 4) Yes, I really need to know. state diagram: I'll do it next time it is necessary (I hope not). Thank you.


text:
Servo Motors PWM pins, Arduino Uno
I wanted to understand how people are connecting a servo motor to pins without PWM, so I went searching and I read that the Servo library uses the timer1 of pin 9 and pin 10 to be able to use other pins.
I would like to ask some questions about this.

Could I connect a servo motor on pin 12 by emulation of the library, and another servo on pin 9, another on pin 10 and another on pin 11 at the same time?
Or using the Servo library the PWM in pin 9 and 10 stops working?
I could then through library emulation connect one servo on pin 7, another on 8, another on 12 and another on 13 ?
4 emulations at the same time?

How are you planning to emulate this? Afaik the servo lib uses hardware pwm but one can still use the timer interrupts to toggle any pin. This way, the resulting pwm is still triggered by hardware and therefore is still much more accurate than a pure soft pwm. The pwm on the oc pins can still be used then...

The library only uses the timer1 interrupt part, not the timer1-pwm part.

Have you read the Servo library page?
The library support upto 12 servos outputs. You can use any pin you want.
The library disables analogWrite() (PWM) functionality on pins 9 and 10.

For those looking for more information on PWM in arduino, a must see page is this one:
http://www.righto.com/2009/07/secrets-of-arduino-pwm.html. Once you read it you may undestand, what is software and hardware PWM and which are the limitations.
To do the software PWM the servo library takes over one of the three arduino's timers. So pin 9,10 are not available to analoWrite() anymore, resting Timer0 (pins 5,6) and Timer2 (pins 11,3).
Note that internally arduino must use Timer0 to its timing functions (such as delay(), milis(), etc).
So to answer your question:
1) Yes, you can since the library is managing your timers it may allocate fine (as software emulation though).
2) Yes and No. It works for the library itself but may be not at disposal for other libraries or for your code. Example: if you want use it along with RH_ASK (radio frequency library) you have an conflict of timer usage and may be needed to change the config of one of them to move to another Timer.
3) Yes.
4) Yes (you can get all 20 pins working as PWM if you want. SoftPWM library does that).
Best regards,
gl


text:
Set Low Power Level or Enable Pin of stepper driver, so stepper does not get hot
I am using the code below with this stepper shield:
https://www.dfrobot.com/wiki/index.php/Stepper_Motor_Shield_For_Arduino(DRV8825)_SKU:DRI0023
Everything works, but tends to get hot (62.3 Celsius) while holding in idle position. What I understood so far, to reduce the temperature I can:

Set enable pin only when I need to turn the motor, but loose my position.
I can use what the driver manual describes as low level. Which I did not entirely understand.

If I set the enable pin to low by doing digitalWrite(M1en,LOW); do I put the stepper in low power mode or do I switch off the power to the stepper ?

I could only enable the stepper (if by setting it to LOW or HIGH I enable, disable) when I need it. Which would be the best as I understood it.

Where in my code below would I have to add the digitalWrite LOW,HIGH to achieve this ? Or do I need to just set it LOW (for low power mode).

Or is there a much better way I don't know about.

Code:
const int dirPin = 4;
const int stepPin = 5;
const int M1en = 12;

int speed = 200;    // desired speed in steps per second
int steps = 0;      // the number of steps to make

void setup()
{
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(M1en,LOW);// Low Level Enable
  Serial.begin(9600);
}

void loop()
{
  if ( Serial.available()) {
    char ch = Serial.read();

    if(isDigit(ch)){             // is ch a number?
      steps = steps * 10 + ch - '0';        // yes, accumulate the value
    }
    else if(ch == '+'){
      step(steps);
      steps = 0;
    }
    else if(ch == '-'){
      step(-steps);
      steps = 0;
    }
    else if(ch == 's'){
      speed = steps;
      Serial.print("Setting speed to ");
      Serial.println(steps);
      steps = 0;
    }
  }
}

void step(int steps)
{
  int stepDelay = 1000 / speed;  //delay in ms for speed given as steps per sec
  int stepsLeft;

  // determine direction based on whether steps_to_mode is + or -
  if (steps > 0)
  {
    digitalWrite(dirPin, HIGH);
    stepsLeft = steps;
  }
  if (steps < 0)
  {
    digitalWrite(dirPin, LOW);
    stepsLeft = -steps;
  }
  // decrement the number of steps, moving one step each time
  while(stepsLeft > 0)
  {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(1);
    digitalWrite(stepPin,LOW);
    delay(stepDelay);
    stepsLeft--;      // decrement the steps left
  }
}

The product page you gave has a link to the DRV8825 datasheet.
Reading this, it is clear that the enable pin(s) comlpetely disable the H-Bridge that drives the motor coils. This is low power mode. It'd doesn't mean low, but non-zero holding current. The driver only supports enabled and disabled.
If your steppers are getting hot, perhaps the current being supplied by the driver is too high. The maximum drive current is set by the current-sense resistors attached to the driver chip. These may not be easy to change. To decrease the maximum current, you increase the current-sense resistor.
The product page notes that the shield has the current set at 1.6A per coil.


text:
Arduino Python to Serial command
I am trying to send commands via serial from Python to Arduino with the code below.
If I save this code in a dedicated python file "Stepper.py" (Python2.7 on Mac OSX) , the code runs successfully but nothing happens (the code does not trigger a motor connected to Arduino).
If I start terminal and run the same code from the interactive shell it works as expected.
How can I run it via a dedicated file ?
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
ser.write("200+")
time.sleep(1)
print ser.read()

You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands.

You are the man !!! Awesome works. Thank you so much

Majenkos comment (above) solved the problem:
"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
time.sleep(1)
ser.write("200+")
print ser.read()


text:
Arduino button and led
Program below is my program for my button and LED, but it's not functioning the way I want it too. The LED is supposed to light up before I press switch 9, but it is lighting up immediately.
const int sw9=9;
const int sw10=10;
const int sw11=11;
const int sw12=12;
const int sw13=13;
int timer=250;
int s=0;
void setup()
{
  for (int opin=1;opin<=8;opin++)
{
  pinMode(opin,OUTPUT);
  pinMode(sw9,INPUT_PULLUP);
  pinMode(sw10,INPUT);
  pinMode(sw11,INPUT);
  pinMode(sw12,INPUT);
  pinMode(sw13,INPUT);
}
}
void loop(){
{
while (s==0)

for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,HIGH);
delay(timer);
digitalWrite(opin,LOW);
if(digitalRead(sw9)==LOW);
}

{
s=1;
delay(timer);
}
}
while(s==1)
for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,LOW);
if(digitalRead(sw9)==HIGH);
}
}

"LED is supposed to light up before i press switch 9 but it is lighting up immediately. " so before. I recommend to take a coding course

The only way you can more or less implement that requirement, is to use an ultrasonic distance sensor (e.g. HC-SR04), and measure the distance from the button to something coming towards it ... which hopefully presses the button and does not move away before pressed.

You will wind up in trouble later on if you don't do some kind of formatting. It becomes very difficult to read or edit code if everything starts from far left with no tabs or spaces. You can select everything and hit Control+T to autoformat your code. I agree with @Juraj, benefit yourself and take a basic coding class. YouTube is your friend.

if(digitalRead(sw9)==LOW);

if(digitalRead(sw9)==HIGH);

Both of these have the effect of "read the switch and then do nothing"
Change them to
if(digitalRead(sw9)==HIGH){
// do intended action
}


text:
Why does a delay make my stepper stop? And why does the break command raise an error?
I am using a stepper motor for a project that I want it to stop. I tried for loops, while, and an if statement. All of these were placed inside the void loop, because it raised an error.
My code with the if loop:
//This program does about 1 rotation or 4100 steps. The program should be able to stop the stepper motor after it does one rotation.
int Pin1 = 8;
int Pin2 = 9;
int Pin3 = 10;
int Pin4 = 11;
int _step = 0;
int _on = 4100;
int _switches = 0;
boolean direct = false;
void setup() {
  pinMode (Pin1, OUTPUT);
  pinMode (Pin2, OUTPUT);
  pinMode (Pin3, OUTPUT);
  pinMode (Pin4, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (_on > 0) {
    switch(_step)
    {
      case 0:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 1:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, HIGH);
      break;
      case 2:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 3:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 4:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 5:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 6:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 7:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 8:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
    }

    if(direct == false) {
      _step++;
      _switches++;
      direct = false;
    }else{
      _step--;
      _switches--;
      direct = true;
    }

    Serial.println(_switches);

    if(_step>7) {
      _step=0;
    }

    if(_step<0) {
      _step=7;
    }
    _on--;
    delay(1); // This solves it.
  }
  break; //This raises an error when used with for loop.
}

Can anyone help on why the delay makes it stop? And why the break command raises and error?
Arduino UNO. 5 wire stepper.

I'm not sure if print statements can keep up the speed, but you can try it (print out the relevant variables, so you can see where it is going wrong), for this you can temporarily comment out the digitalWrites. Also a tip, to give your variables a good name (like _on, I would expect it is a boolean).

@michel keijzers. I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

Ok good to hear :-)

... why the break command raises and error?

Because you are using it wrong! break will end a loop, and is used in the switch...case statements. Read the documentation for break if you need to know more

I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

You haven't really fixed it if you don't know why. It seems that you are trying to directly control a 5 wire stepper, i assume your pins must drive a transistor or something as the arduino pins themselves will not work.
The reason it works is because the stepper takes time to energize and move, if you don't wait long enough it won't work, your serial.print must be long enough, as the delay(1) should produce a 1ms delay which is too short.
You are driving your stepper wrong, you have the code setup for a half-step control, but you have 9 states, state 8 in not needed.
you are duplicating effort you don't need with both _steps and _switches, they always have the same value.
you can do better on your code as well:
int dir = 1
int c = 0

// in loop
c += dir

if (c > max)
{
  dir *= -1
  c = max
}

if (c < min)
{
  dir *= -1
  c = min
}

With this you don't have to check the direction to modify your variables.

Just for clarity, the stepper doesn't stop because it needs a delay to calculate what to do next? Also, the break should break the main loop void loop(). And, lastly, this is my first time using Arduino and C. I don't know how to work with the code as well as many of you guys.

@12944qwerty void loop() is a function, you return from functions, you break from loops; naming a function loop doesn't make it a loop; its called loop() because the main Arduino library calls loop() in a loop!

@12944qwerty the stepper motor needs a delay to PHYSICALLY move; it takes time for the coils to energize and build up a magnetic field, then the motor will move to the next step.

In simple terms: break() literally breaks out of the immediate loop it is in. Since you were in no loop [void loop() is not your usual loop functions, it's just Arduino-for keep repeating whatever is inside infinitely. You could use a for/while loop in setup() for how many ever times you want it to run and then use break().] delay(time in ms), as the name says just pauses the Arduino like a brainfart for how much ever time you put as the parameter. You could check out this link in the future for information of inbuilt functions and other language-related doubts.


text:
Voltage to keep my board safe
I have recently made a home automation system using node mcu and relay module and i am powering both together using my 5V ,2A dc adapter and i am scared that if I'll keep using it for very long hours and that too daily my node mcu board would disrupt soon. So i wanted to ask that what to keep the minimum voltage. So to keep the board safe

to which pin on the NodeMcu is the 5 V input wired?

@Juraj it is the 3v3 pin

and it doesn't smoke?

@Juraj no it doesn't and i kept it running for 1 hr.

@Juraj i just wanna ask... should i lower the voltage or change the pin to keep my board safe...for longer hrs of running

@Juraj yes it has a vin pin..

https://github.com/nodemcu/nodemcu-devkit-v1.0/issues/15

@Juraj sir if i connect it to vin at 5v can keep it running daily for at least 11 to 10 hrs.?

it has a regulator on Vin. it can run 24/7 then

I'm not sure I'd trust it, after given it 5V instead of 3.3V for over an hour.

@Juraj how to check if it has a regulator

if it is a NodeMcu it has it


text:
How to subtract the current analog value from previous one
I pretty new to the Arduino. I am working on project that find the power by reading your

Why would you want to subtract it? Do you maybe want to sum / integrate it over time to get total energy consumption?

I have this fourmal S=(V2-V1)/(P2-P1)

I have no idea what S is supposed to express here. But in the code you can take two measurements in predifened interval and then compute S.

S means the voltage sensitivity. Can you express what you said in code?

you do it by coding the sketch.

The formula should read P= U x I, V is for velocity and U is for voltage.

I think you need something like the following :
int lastTime;

void loop(){
  int thisTime = analogRead(A1);
  int diff = thisTime - lastTime;
  lastTime = thisTime;
  Serial.println(diff);
}


text:
Arduino max power supply limit
What is the maximum current that can be supplied to an Arduino Mega board before frying/breaking?
Basically i have several components connected to my board which draw a total current of 1.6A (which i calculated through a table), and thinking of using a 9V 2A power supply. I know that the arduino voltage limit is 7-12V but just wondering about the current as I can't find it on the datasheets?
Thanks in advance!

I think you mean "supplied from"; you can supply infinite amps to it. If you components can use vin, then you're not really limited, other than to the pins/traces.

yes sorry i meant i will have an external 9V 2A power supply to power the arduino and my components. as i will be connecting this through the japan socket, the max current input limit would be 1A as suggested by @CrossRoads? Or is this also infinite? Thanks!

1A coming in thru the barrel jack connecor, then you risk blowing the 1A rated reverse polarity protection diode. The 5V regulator will overheat at high currents above 7.5V. The chip itself can have 800mA put thru if if properly cooled and the IO limits of current per port are respected.
So 1.6A, no way.

thanks for the info! so im assuming the max current that can be provided through the japan jack is 1A?

Thru the barrel jack, yes ,1A.  Thru the USB jack, 0.5A.

From the ATmega328P datasheet.

One should specify that these are the limits of the MCU unit. But the current does not have to go through the MCU. For a 5V pin the limit comes from the power supply, 500 mA for USB and 1000 mA for the linear voltage regulator (barrel jack). In both cases one must subtract the power consumption of the board. Also note that USB power is disconnected as soon as you put voltage through the regulator: they have no chance to work concurrently.

Your question isn't clear. Are you talking about drawing regulated 5V from the Arduino power supply? I believe the built-in regulator has a hard limit if 1A total output, but how much you can draw from it will depend on various factors (mostly how much waste heat it generates. If you drive it from 9V it will generate quite a bit of heat, since a linear regulator simply dissipates the excess voltage as heat. Better to use a 7V supply)
You won't be able to draw 1.6A of 5V from the Arduino. You should probably get a separate 2A 5V regulated power supply for your external components. Again though, your question isn't very clear so I'm not sure I'm answering what you're asking.

Thanks for your reply. So the idea is to have an external power supply to power the arduino board along with its components. I re-did my calculations, and the total current and power dissipated by the components and arduino board would be 3.8W and 0.6A. Do you reckon this power supply would be enough https://www.amazon.co.uk/gp/product/B00HG9PT4K/ref=ox_sc_act_title_1?smid=A337BOQBCQBMQG&psc=1 ? It's rated at 9V/650mA and says its for the arduino. The alternative solution would be to have a 9V/2A if this is pushing on the limit

Is that what your external components need? 9V? Most solid state components need regulated 5V.  If your external components need 9V then you might get away with driving them from the 9V supply and also powering the Arduino into it's barrel connector using the same 9V supply. The Arduino regulator should handle fluctuations in input voltage as long as you don't draw so much current from the 9V supply that its voltage drops below 7V or so.

I have 2 8V stepper motors, a 3V LED  light and HC05 bluetooth module

You should not cut it that close. A 2A supply would be a much better choice. You'd be better off using a separate low power 5V regulated supply for the Arduino. Keeping the power supplies separate will avoid big swings in voltage as your power components (motor and bluetooth module) turn on and off.


text:
ESP8266 MQTT periodically disconnecting
I use an MQTT to communicate with an ESP8266. I'm using cloudmqtt.com and PubSubClient. Sometimes the ESP disconnects from the MQTT and reconnects.
I checked the log from cloud and I got this data
2019-02-18 20:11:18: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:22: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:35: New connection from 89.64.15.184 on port 18127.

2019-02-18 20:11:35: New client connected from 89.64.15.184 as ESP8266Client-80:7D:3A:69:6C:2E (c1, k15, u'userName').

2019-02-18 20:11:53: Client <unknown> has exceeded timeout, disconnecting.

2019-02-18 20:11:53: Socket error on client <unknown>, disconnecting.

2019-02-18 20:11:56: Saving in-memory database to /var/lib/mosquitto/18127/db.

2019-02-18 20:11:58: Client ESP8266Client-80:7D:3A:69:6C:2E has exceeded timeout, disconnecting.

in setup I have this method:
void setupMQTT() {

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    String clientId = "ESP8266Client-";
    clientId += WiFi.macAddress();
    if (client.connect(clientId.c_str(), mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }
  client.publish("esp/blind/out", "hello world");
  client.subscribe("esp/blind/in");
}

and in loop I have
client.loop();

without any delay.
I think that the ESP id in MQTT cloud is unique, because I use the MAC address.

which version of arduino/esp8266 are you using - I ask, because I had to put in a delay(10) or so in loop for some ESP chips when using the latest (2.5.0dev) branch

I use wemos D1 mini with ESP-12F and about month ago I update firmware because I wanted to try micropython

but your code isn't written in micropython .... it looks like typical arduino (i.e. C/C++) ... which version of the esp8266 arduino core are you using? Actually, nevermind, try adding a delay(10) in your main loop or even a yield()

no it isn't written in micropython it's written in c++, adding delay(10) do nothing. How can I check a esp8266 arduino core version ?

you downloaded it and installed it ... what did you download and install ... another possibility is the router you connect to- which make model? (e.g I have a linksys wrt32x - and ESP's have lots of issues staying connected to it)\

I have version 2.5 updated from 2.5 beta 2. I connect esp to airport from apple

try setting a lower "keep alive" ... e.g. #define MQTT_KEEPALIVE 10 before #iclude <pubSubClient.h>

It works, thank you very much for helping

I have the same problem again, I added #define MQTT_KEEPALIVE 10 and delay(50)


text:
NodeMCU display temperature and control LED from an autorefresh web page
I'm totaly new to Arduino, I'm using ESP2866 NodeMCU and dht22 to display temperature and humidity in a web page, it is autorefresh (using AJAX) and it works perfectly, I wanted to add 2 buttons to it so I can control 2 Leds but when I tried that I couldn't control them and even the values of temperature and humidity stopped refreshing. Can you tell me what is wrong in the code ? here it is :
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "DHT.h"
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

 /*Put your SSID & Password*/
 const char* ssid = "xxx";  // Enter SSID here
 const char* password = "xxx";  //Enter Password here

  ESP8266WebServer server(80);

 // DHT Sensor
 uint8_t DHTPin = D6;

  // Initialize DHT sensor.
  DHT dht(DHTPin, DHTTYPE);

  float Temperature;
  float Humidity;
  float reading;
  float percentage;
  // Auxiliar variables to store the current output state
  String output5State = "off";
  String output4State = "off";

 // Assign output variables to GPIO pins
 const int output5 = 5;
 const int output4 = 4;
 void setup() {
 Serial.begin(115200);
 delay(100);

 pinMode(DHTPin, INPUT);
 dht.begin();

// Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
 pinMode(output4, OUTPUT);
 // Set outputs to LOW
 digitalWrite(output5, LOW);
 digitalWrite(output4, LOW);
 Serial.println("Connecting to ");
 Serial.println(ssid);

//connect to your local wi-fi network
WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);

server.begin();
Serial.println("HTTP server started");

}
void loop() {

server.handleClient();
}

void handle_OnConnect() {

Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity

//Serial.println(reading);
String header=SendHTML( Temperature,Humidity,percentage);

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

      }

   void handle_NotFound(){
   server.send(404, "text/plain", "Not found");
    }

   String SendHTML(float TempCstat,float Humiditystat, float  percentage){
    String ptr = "<!DOCTYPE html> \n";
    ptr +="<meta name=\"viewport\" content=\"width=device-width,
    initial-scale=1.0, user-scalable=no\">\n";
    // ptr +="<meta http-equiv=\"refresh\" content=\"2\" >\n";
   ptr +="<link href=\"https://fonts.googleapis.com/css?
    family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";
    ptr +="<title>ESP8266 Weather Report</title>\n";
    ptr +="\n";
     ptr +="\n";

     ptr +="\n";
     ptr +="\n";

     ptr +="
\n";

     ptr +="
ESP8266 Weather Report
\n";
     ptr +="
\n";
     ptr +="
\n";
     ptr +="<svg version=\"1.1\" id=\"Layer_1\"
     xmlns=\"http://www.w3.org/2000/svg\"
     xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n";
     ptr +="width=\"9.915px\" height=\"22px\" viewBox=\"0 0 9.915 22\"
     enable-background=\"new 0 0 9.915 22\" xml:space=\"preserve\">\n";
      ptr +="<path fill=\"#FFFFFF\" d=\"M3.498,0.53c0.377-0.331,0.877-
      0.501,1.374-0.527C5.697-0.04,6.522,0.421,6.924,1.142\n";
      ptr+=
       "c0.237,0.399,0.315,0.871,0.311,1.33C7.229,5.856,7.245,9.24,7.227,
        12.625c1.019,0.539,1.855,1.424,2.301,2.491\n";
      ptr +="c0.491,1.163,0.518,2.514,0.062,3.693c-0.414,1.102-1.24,2.038-
      2.276,2.594c-1.056,0.583-2.331,0.743-3.501,0.463\n";
      ptr +="c-1.417-0.323-2.659-1.314-3.3-2.617C0.014,18.26-
      0.115,17.104,0.1,16.022c0.296-1.443,1.274-2.717,2.58-3.394\n";
      ptr +="c0.013-3.44,0-6.881,0.007-
      10.322C2.674,1.634,2.974,0.955,3.498,0.53z\"/>\n";
      ptr +="</svg>\n";
      ptr +="
\n";
      ptr +="
Temperature
\n";
      ptr +="
";
      ptr +=(int)TempCstat;
      ptr +="°C
\n";
      ptr +="
\n";
      ptr +="
\n";
      ptr +="
\n";
      ptr +="<svg version=\"1.1\" id=\"Layer_2\"
      xmlns=\"http://www.w3.org/2000/svg\"
      xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\";
      width=\"12px\" height=\"17.955px\" viewBox=\"0 0 13 17.955\" enable-
      background=\"new 0 0 13 17.955\" xml:space=\"preserve\">\n";
      ptr +="<path fill=\"#FFFFFF\"
     d=\"M1.819,6.217C3.139,4.064,6.5,0,6.5,0s3.363,4.064,4.681,6.217c1.793,
      2.926,2.133,5.05,1.571,7.057\n";
     ptr +="c-0.438,1.574-2.264,4.681-6.252,4.681c-3.988,0-5.813-3.107-
     6.252-4.681C-0.313,11.267,0.026,9.143,1.819,6.217\"></path>\n";
     ptr +="</svg>\n";
     ptr +="
\n";
     ptr +="
Humidity
\n";
     ptr +="
";
     ptr +=(int)Humiditystat;
     ptr +="%
\n";
     ptr +="
\n";

    //Buttons

     ptr +="
\n";
     ptr +="
Button
\n";
     ptr +="
";
     ptr +="
<button class=\"button\">ON</button>

";
     // If the output5State is off, it displays the ON button
        if (output5State=="off") {
          ptr +="
<button class=\"button\">ON</button>

";
        } else {
          ptr +="
<button class=\"button
        button2\">OFF</button>
";
        }
         // If the output4State is off, it displays the ON button
        if (output4State=="off") {
          ptr +="
<button class=\"button\">ON</button>

";
        } else {
          ptr +="
<button class=\"button
          button2\">OFF</button>
";
          }
           ptr +="%
\n";
           ptr +="
\n";
           ptr +="
\n";
           ptr +="\n";
           ptr +="\n";
           return ptr;
          }

Why are you searching for request parameters inside your generated response HTML?

Where shoulf I search !

@AlMa, did you read the answer?

Write handlers for different URLs
server.on("/5/on", led5On);
server.on("/5/off", led5off);

do you get the concept?
or you could write one handler server.on("/setLED", setLED);, if you would send "/setLED?num=5&state=on". and then in setLED function get the parameters values as
String num = sever.arg("num");
String state = sever.arg("state");

see the SimpleAuthentication example


text:
Sending char arry via nRF24L01
I am trying to send a char array using Arduino Uno board and nRF24L01 modules
Here is the code for both transmitter and receiver:
 #include <SPI.h> //~ #include <TMRh20nRF24L01.h> //~ #include <TMRh20RF24.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type //
 These are the IDs of each of the slaves const uint64_t slaveID[2] =
 {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

 RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

 char
> dataToSend[64]="e7665072be018b6b58ea9e40cf38553d6dc293cda4c9d94cda6e91ca61b3a073";

 unsigned long currentMillis; unsigned long prevMillis; unsigned long
> txIntervalMillis = 1000; int txVal = 0; float ackMessg[2]={1,2}; byte
 ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints
 that will be recieved

 void setup() {

    Serial.begin(9600);
     Serial.println("Track Control Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.enableAckPayload();
     radio.setRetries(3,5); // delay, count }

 //====================

 void loop() {

     currentMillis = millis();
     if (currentMillis - prevMillis >= txIntervalMillis) {

     radio.openWritingPipe(slaveID[0]); // calls the first slave
                                         // there could be a FOR loop to call several slaves in turn

     bool rslt;
     rslt = radio.write( dataToSend, sizeof(dataToSend) );
     Serial.print("\nRSLT (1 = success) ");
     Serial.println(rslt);
     Serial.print("Data Sent ");
     Serial.print(dataToSend[0]);
     Serial.print("  ");
     Serial.println(dataToSend[1]);
     if ( radio.isAckPayloadAvailable() ) {
         radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);

 #include <SPI.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type

 const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave

int valChange = 1;

 RF24 radio(CE_PIN, CSN_PIN);

 char  dataReceived[64];
 int ackData[2] = {12,23};

 void setup() {

     Serial.begin(9600);
     delay(1000);
     Serial.println("Hand Controller Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.openReadingPipe(1,deviceID);
     radio.enableAckPayload();
     radio.writeAckPayload(1, ackData, sizeof(ackData));
     radio.startListening();
 }

 void loop() {

     if ( radio.available() ) {
         radio.read( dataReceived, sizeof(dataReceived) );
          for (int x = 0; x <64; x++) {
       //if (dataReceived[x] < 16) {
       //  Serial.write('0');
     // }
       Serial.print(dataReceived[x]);}
       Serial.println();
         radio.writeAckPayload(1, ackData, sizeof(ackData));

         ackData[0] += valChange; // this just increments so you can see that new data is being sent
     }
}

And here is the output that I get

Hand Controller Starting
e7665072be018b6b58ea9e40cf38553d

you get what you send. continue reading

yes i know that i got what i sent,my question was how to get the full char array as its size is more than payload size

To send a larger package you will need to split the data into a sequence of packages of PAYLOAD_MAX(32) size at the sender. And then reassemble the data at the receiver.

I would expect that the library sends the input in parts even if send in one function call. But I don't know this library. But the receiving must be coded expecting chunks of data.

yes i am trying to find a way to split big payload into chunks

Why send 64 characters in hex decimal notation when you can send 32 bytes with the same data?

how can i do that ?

byte dataToSend[32] = { 0xe7, 0x66, 0x50, 0x72, ..., 0x61, 0xb3, 0xa0, 0x73}; or write a function that translates from character string to byte vector as above.

thank u very much,but the array is generated from a hash function in sha256 library,i just simplified the code here to discuss the concept

Yes, the SHA256_BLOCK_SIZE is 32 which happens to be the RF24_PAYLOAD_MAX. The vector size (64) is your example is the textual (ASCII character) hex decimal representation of the block. Double the size as a byte (8-bits) is represented as two ASCII characters (0..15 mapped to '0'..'9', 'A'..'F').

so can i send the unencoded output from the hash function then map it at the receiver side?

TX code
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID = 0xE8E8F0F0E1L  ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
int ackMessg[6];
byte ackMessgLen = 4;

uint8_t* hash;
uint8_t copy[32];
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]);
      copy[i]=hash[i];
  }
  Serial.println();
}

void setup() {
  printf_begin();

  uint32_t a;
  unsigned long ms;

  Serial.begin(9600);

  radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.enableAckPayload();
    radio.setRetries(3,5); // delay, count

  // SHA tests
  Serial.println("Test: FIPS 180-2 B.1");
  Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  Serial.print("Result:");
  ms = micros();
  Sha256.init();
  Sha256.print("abc");
  printHash(Sha256.result());
  Serial.println();
  for(int x=0;x<32;x++)
        {   Serial.print(copy[x]);
            Serial.print(" ");
                                  }
            Serial.println();

  Serial.print(" Hash took : ");
  Serial.print((micros() - ms));
  Serial.println(" micros");
  Serial.println();

  }

void loop() {

  currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID);
    bool rslt,rsltt;
    rslt = radio.write( copy, 32 );

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }

}

Rx code
// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);
RF24 radioo(CE_PIN, CSN_PIN);
uint8_t  dataReceived[32];

int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.openReadingPipe(1,deviceID[1]);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();

}

void loop() {

 unsigned long startTimer = millis();

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        Serial.println();
        //Serial.println(startTimer);
        Serial.println();
        for(int x=0;x<32;x++)
        {Serial.print(dataReceived[x]);
        Serial.print(" ");}}
        ackData[0] += valChange; // this just increments so you can see that new data is being sent

    }

it is fully working now with both outputs on the same size


text:
Atmega 32U4 doesn't show on device manager after fuse bits reset
I am finally ready to try setting fuse bits on my ATMega32u4-AU custom board (8Mhz Ceramic Resonators, 3.3V), however, after I set the fuse bits and plug my board to computer, the device manager appears nothing (seems there is no device been connected). I am not sure which step I did wrong, so I’d like to post the details, please kindly point out my mistake, thanks a lot!

I used Fuse High Byte: 1001 1001 (0x99) Fuse Low Byte: 0101 1110 (0x5E) Extended Fuse Byte: 1111 0011 (0XF3)
This is the command I entered into avrdude: avrdude –b 19200 –c usbasp –p m32u4 –v –e –U efuse:w:0XF3:m –U hfuse:w:0x99:m –U lfuse:w:0x5E:m
I am able to see the result from command
But after setting the fuse, when I read the fuse in avrdude, I dont know what the reason is but I got different efuse data

After all of these steps, I connected my board to windows 10 computer, the computer shows nothing...
Someone online told me that it could because the clock divider get changed. So, I added a step of setting lock bit to 0x2C through typing “avrdude –b 19200 –c usbasp –p m32u4 –v –e –U lock:w:0X2C:m” But it didn't fix the preblem.
Later, I was thinking maybe I set the low fuse wrong, because the bit0..3 (1110) in lfuse means "Low Power Crystal Oscillator"; So, I set bit0..3 to (1010) and CKDIV8 to 1, which means "Low Frequency Crystal Oscillator" and "unprogrammed divide clock".
All of these didn't fix the problem, please kindly point out which step I did wrong, your help would be greatly appreciated.

Do you have software installed on the chip that even tries to be a USB device? The chip isn't magically a USB device until you program it to be a USB device.

C3 and F3 are the same, as only the last 4 bits in the e-fuse are actually used, and those are both 3. I'd try re-programming the bootloader. Perhaps changing the fuses, erased the flash.

Thanks for answer. I don't have the software installed on the chip to make it be a USB device... So, which softeare do you recommend?