text:
esp8266 + octocoupler relay: WDT reset when using AC current
I'm trying to switch on bulb via 4 channel 5V optocoupler relay controller from ESP8266 using WIFI Access point. All my connections looking fine and i can able to connect WIFI SoftAP and send signal to ESP8266 01. Even i can able to switch the Relay from NO to NC or other way around. Only when a connect 240V AC current to relay for powering the bulb, i'm getting following error from ESP
21:11:34.312 ->  ets Jan  8 2013,rst cause:4, boot mode:(1,7)
21:11:34.312 ->
21:11:34.312 -> wdt reset

If i use 12V DC power to light the led via relay its working fine. if again use 240V power to relay to light bulb i'm get same error again.
I have already tried using ceramic capacitor for decoupling to avoid noise from AC. Still no luck. Please advice. I'm very new and naive at handling electronics.
Adding the circuit as well.

Update: After further testing, I can see following behaviour,
If i connect AC bulb to relay and turn it on. Then by provide a long gap before turning it off makes the ESP stable for longer time.
Even better, if i turn off/on my mobile wifi between each time i turn on or off the AC bulb then ESP is always stable.
Adding my code as well.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* Set these to your desired credentials. */
const char *ssid = "*****";
const char *password = "*********";

ESP8266WebServer server(80);

const int led = 2;  //GPIO2

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
 * connected to this access point to see it.
 */
void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"\

Status: Light ON

\

Turn ON

\

\

Turn OFF

\
  \
  ",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );

}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");

    /* You can remove the password parameter if you want the AP to be open. */
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);

  pinMode(led, OUTPUT);
  digitalWrite ( led, HIGH );

  //URLs available to query
    server.on("/", handleRoot);
  server.on ( "/on", turnON );
  server.on ( "/off", turnOFF );
    server.begin();
    Serial.println("HTTP server started");

}

void turnON(){

  digitalWrite ( led, HIGH );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"

Turn OFF

",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void turnOFF(){

  digitalWrite ( led, LOW );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"

Turn ON

",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void loop() {
    server.handleClient();
}

I know this question is more than 5 years old, but since nobody has mentioned it: are you trying to produce 5 V from a 5 V input using a linear regulator? That will not work. Also, if the regulator is an LM317T, it's wired incorrectly and would need a pair of resistors to set the output voltage.

Before running to dark magic of EMI problems - let's try isolate all our parameters that can cause or affect (and perhaps is is not only one):

make a test code as simple as possible for switching a relay periodically on/off. At start make a 5 second delay between changing states, and down to 500 millis- This way you check both EMI interference and power issues inside you circuit (sometimes the relay consumes power more that the MCU can give, and that can cause resets. Problem can be MCU's power issue or Relay, mechanical or electrical issues).
Components - try to replace with others, especially MCUs, and relays, to make sure it is not a malfunctioned or degraded components. For example - a Wemos mini with is Relay shield can easily isolate any "EMI"- related issue.
From you diagram (and in contrast to your question's title) - an Uno is used for switching ? and not the ESP-01' right? did you make sure that the relay's vcc is correct for its MCU? (you said 5v relay, which is not correct for ESP8266).
Load - make sure to choose a simple resistive load (AC light bulb), rather that an AC motor (which cause a massive EMI interference).
EMI - if all above did not help (I doubt) or it solved for that "bulb case" only, EMI affect are distance related. Try to use a long AC wires that will take you MCUs and relay far from that source. 1m will be enough.

To sum up, I will be very surprised to know that it is EMI (and I dealt with AC motors with WEMOS and a dual relay module successfully).
Please update.
Guy


text:
the code and the actual output didn't match
i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.
  int hasil
  int reado;
  int z;
  int baca;
  bool en = false;
  void setup() {
  // put your setup code here, to run once:

  TCCR1A = 0b00100010;
  TCCR1B = 0b00011001;
  TCCR0A = 0; TCCR0B = 0;
  ICR1 = 100000;//disable millis, delay and mciroseconds function
  //disable millis, delay and mciroseconds function

   // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(A2, INPUT); pinMode(A3, INPUT);
  pinMode(9,OUTPUT); pinMode(10,OUTPUT);
  }

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

 hasil = analogRead(A2);
 baca = digitalRead(A3);
 for (z=0; z<=hasil; z++)
 reado = map (hasil, 0, 255, 0, ICR1);
 if (hasil > 30 && baca == HIGH)
 {analogWrite(9,hasil); analogWrite(10,0);}
 else if (hasil >30 && baca == LOW)
 {analogWrite(9,0); analogWrite(10,hasil);}
 else if (hasil<30)
 {analogWrite(9, 0);
 analogWrite(10, 0);}}

analogWrite starts the PWM signal. you don't let it run and start it again and again. so instead of |_|_|_ you get ||||||

so how to do pwm properly sir @Juraj

analogWrite will start PWM signal. and then call analogWrite again only if you want to change it or stop it

Re “bool en = false;”: Yes, we did figure out that your variable names are not in English, no need to write it explicitly.

You wrote:

when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's
doing exactly what you asked for: a PWM output that switches between two
different output pins. The program should work as expected, with only a
few caveats. Let me comment it in some detail:
ICR1 = 100000;

Here you are setting ICR1 to 34464 (i.e. 100000 modulo
216). This is likely not what you mean...
Serial.begin(115200);

There is no point in initializing the serial interface if you are not
going to use it.
for (z = 0; z <= hasil; z++)
    reado = map(hasil, 0, 255, 0, ICR1);

There is no point in calculating many times the exact same value.
Actually, there is no point in calculating it even a single time, since
you are not using the result anywhere in your program.
analogWrite(9, hasil);

Here you are setting the duty cycle to some number between 31 and 1023.
Given that the top value of the timer is 34464, the actual duty cycle
will always be less than 3%. This is the reason why it looks like a
series of narrow spikes on the virtual scope.
But maybe what you really meant is
reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
analogWrite(9, reado);

I would not recommend using analogWrite() with a non-standard top
counter value. There is a special case handled in analogWrite() where,
if the argument happens to be 255, you get instead a
digitalWrite(pin, HIGH). This is most likely not what you want. Now
that you started controlling the timer with raw IO access, you should
continue this way.
else if (hasil < 30)

Did you consider what the program should do if hasil happens to be
exactly 30? None of the if/else cases would then match. You probably
meant
else if (hasil <= 30)

but, as suggested by user11249082's answer, a plain else is the best
way to ensure you did cover all possible cases.

very brief explanation sir, but still don't know how to make the output the same as analog input, would you like to teach me how to do it?

@johncaren: Fix the issues I showed you, then try again.

The problem as i can see exist in the if else statements . You use multiple else if statements but in the end you must end it with else statement .
Use the “if/else if” if you need to choose either one or none of a series of options. You could write the above program using separate if statements such as show below but the if/else if approach is cleaner and better indicates that the program should choose either one or none of the options
Here how you do it
If (){}....
Else if (){}.....
Else if(){} ......
Else{}
here this can help you enter link description here

thnaks sir, i'll try it

source: Stack Exchange

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

sort: votes


text:
Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno?
I was wondering if I can use a GPS (in my case a U-BLOX) and a hc-05 at the same time connected to a arduino uno without a breadboard? I have tried my GPS on the arduino uno alone and it works very good. Now my question is, can I add a hc-05 on the board directly and put the VCC on the empty 5v?
I put together a schematic of what I had in mind below:

Would this schematic work or would I need a breadboard?

Are you expecting to use them both at once? Note of caution: you cannot reliably use two SoftwareSerial objects at once.

I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.
Note that some male-female header might get handy.
I'm not sure that the HC05 can handle 5V though. You migh want to check.

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


text:
ESP8266 ESP-07 does not respond to commands
I just bought an ESP8266 ESP-07 V1.0 Serial Wifi Transceiver. Similiar to this: https://www.ebay.com/itm/ESP8266-Serial-Wifi-Transceiver-Module-for-Arduino-ESP-07-V1-0-New-/331868488091
I have connect the RX and TX pins to the RX and TX pin of the Arduino (RX to TX and TX to RX), VCC is connected to 3.3V and GND is connected to Arduino ground.
I have used the following code and writing commands to the module using the serial monitor:
#include <SoftwareSerial.h>

int RX_PIN = 3;
int TX_PIN = 4;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

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

    while (!Serial){
    ;
  }

    while (!mySerial){
    ;
  }
  Serial.println("Ready");
}
void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( mySerial.available() )   {  Serial.write( mySerial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  mySerial.write( Serial.read() );  }
}

Whatever I type (for example AT+GMR) in the serial monitor at 9600 baud I don't get any response. What could be the reason? Both NL and CR is added to the command.
When pressing reset on the ESP-module I get this in the Serial monitoring:

Thanks for any help!

pin 1 is TX of hardware Serial. and the esp8266 should be on SoftwareSerial RX/TX pins, not on RX/TX labeled pins

@Juraj Thanks for your reply. I have now updated the code. But still no luck :-/

and the wiring?

@Juraj  Arduino RX (pin 3) => ESP TX, Arduino TX (pin 4) => ESP RX, Arduino 3.3V => ESP VCC, Arduino GND => ESP GND

you changed the baud rate. the AT firmware's default is 115200 baud, but SoftwareSerial can't receive reliably at 115200

@Juraj Is there anyway to fix that then?

the output after reset is bootlog at different baud rate. did you try to send AT after "Ready"?

@Juraj Yes, if I do that I don't get any response. But reading around I see I might need to put a resistor between the TX from Arduino (pin 4) to ESP8266 RX pin since it operates at 3V not 5V? Which means the ESP8266 RX pin might be broken? 100 ohm resistor should be enough if I have calculated correctly.

the esp8266 has no pronlem with  5 V Serial

set the baud rates to 74800 to see the boot log

@Juraj Sweet, that gave me "ets Jan  8 2013,rst cause:2, boot mode:(3,6)". Is it only boot log that works at 74880?

yes only boot log. is it possible that the esp8266 is without AT firmware? even with SoftwareSerial at 115200 you should see "ready" from AT firmware and get some response to AT commands

@Juraj I have asked the seller about the firmware since the information does not say anything about it. As far as I can see there is no way for me to install/update the firmware using the Arduino Uno.

why not? it is simple. https://forum.arduino.cc/index.php?topic=634684.0

@Juraj This is totally new to me. But I tried it out now. Downloaded NodeMCU and wired it up. But get the following when clicking on "flash"Note:Serial port connected.
Note:Begin find ESP8266.
Note:ESP8266 ACK success.
Error:Read ESP8266 register timeout.

NodeMcu? there is nothing about nodemcu in that link. did you set the switch to flashing mode and reset?

@Juraj Got it working now. But a little bit unsure which files I actually need to upload/update. I have used esp_init_data_default_v05.bin and blank.bin

For anyone still confused (like I was), the code should still say Serial.begin(115200) but the Arduino log monitor should be set to 74880 baud.

@Juraj Got it working now thanks to the forum link. So I will accept it as answer if you make one :)

with AT firmware 1.7 you can use my WiFiEspAT library in UNO. the library is in library manager

The esp8266 is without AT firmware. Even with SoftwareSerial at 115200 baud you should see "ready" from AT firmware and get some response to AT commands.
This esp8266 module adapter is simple to flash. It makes the 5 V to 3.3 V conversion for power and RX pin and has a program switch (io 0) and a reset button to put the esp8266 into flashing mode.
Use an USB-to-TTL-Serial adapter or an Arduino with USB chip to connect the adapter to PC. Then switch to "program" and reset it and it will be in flashing mode.
You can download the AT firmware here. I recommend ESP8266 NonOS AT Bin V1.7.1. Don't try 2.0, it is very different (ESP32 AT firmware build for esp8266).
To flash it, use esptool
The command to flash the AT firmware binaries to any module with at least 1 MB flash memory is:
esptool.py write_flash --flash_size 2MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin

don't wonder about the 2MB-c1 setting and don't change it. The AT binaries are build for 2MB-c1 partitioning. On 1 MB flash it will not support AT firmware OTA update.
If you want to use the Espressif Flash Download Tool, use the same settings as on esptool command line.

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


text:
Can I program a factory fresh Atmega328P through UART pins without burning a bootloader?
Can I program a factory fresh ATMega328P using the UART pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins in the schematic below. They are not the ISP/SPI pins 10-13.
Arduino Pro Mini schematic
For example, if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer, you're not connected to the ISP pins (basically the SPI interface: MOSI, MISO, SCLK, SS), but rather to the serial i/o and reset pins.
My understanding is that a bootloader is required if you want to program through these pins, because the Arduino bootloader looks for UART traffic at these pins upon startup and hands off operation to the user's code if no attempt at programming happens during this time.
That said, I also understand burning a bootloader is done through the ISP/SPI pins, and my PCB is already manufactured, which makes burning a boatloader somewhat of a hassle. So...
Can I program an ATMega328P through the UART pins fresh off the reel, or will I need rig up a way to burn a bootloader through the ISP pins first?

"... using the ICSP pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins ... They are not the ISP/SPI pins ..." - ICSP is commonly used as a synonym of ISP, so for the 328P, that means through the SPI pins. Yes, you can do this to a factory-fresh 328P, but not through the pins you have in mind.

"if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer," no, for Mini Pro you need an USB to TTL Serial adapter for programming over UART and bootloader

No, the ATmega's ISP does not operate over the UART pins but only the ISP pins.
To program it via a UART, you need to first load a bootloader, unless your chip was pre-programmed by the vendor, something some offer as a value-added service (or even as an essential stock item, with an Arduino type bootloader)


text:
Is it possible to send a float Array over I2c
I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?
Cheers.

It is possible. You gave to send both bytes of the float and put them back together correctly after it. Please include your code into the question, so that we can help you

Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.
Master Writer Sketch
#include <Wire.h>

const int DEVICE = 8;

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

void loop() {
  const int VEC_MAX = 6;
  float vec[VEC_MAX];
  uint8_t* vp = (uint8_t*) vec;

  Wire.requestFrom(DEVICE, sizeof(vec));
  while (Wire.available()) {
    *vp++ = Wire.read();
  }

  for (int i = 0; i < VEC_MAX; i++) {
    Serial.println(vec[i]);
  }

  delay(500);
}

Slave Receiver Sketch
#include <Wire.h>

const int DEVICE = 8;
const int VEC_MAX = 6;
float vec[VEC_MAX] = { ... };

void setup() {
  Wire.begin(DEVICE);
  Wire.onRequest(requestEvent);
}

void loop() {
  delay(100);
}

void requestEvent() {
  Wire.write((uint8_t*) vec, sizeof(vec));
}

Is it possible to send a float Array over I2c

So I would answer - Yes.


text:
ESP32 bluetooth discovery parse names
I'm running a sample code from ESP32 examples and I'm scanning available BLE devices. I can see device MAC address etc. But for few devices I can't see their names.I am using ESP-WROOM-32 with hardware support checked out directly from their github (some bugs were fixed earlier on github than via lib manager)When I use LightBlue app for discovery of BLE Devices I can see names for more devices that ESP. What can I change to see the names correctly? OR Can how can I parse device name from the data I'm receiving?
This callback code
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
      Serial.print(" RSSI: ");
      Serial.println(advertisedDevice.getRSSI());
    }
};

produces this output:
Advertised Device: Name: , Address: 1d:0c:c7:3a:fb:c6, manufacturer data: 4c0009060378c0a81f12, payload: 1073609632
 RSSI: -75

Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.
You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


text:
Sketch for 5 randomly fading leds not working as expected; what could be wrong?
I'm working on a project with a starry sky, based on fiberoptics and 5 leds.
The code should work this way:
Start on average brightness, then go up or down according to a set of randomly chosen preset values. (min, max, wait time etc) and switch direction after the wait period on either its min/max is completed. When it reaches the average again, a new set of preset values should be assigned.
The updating of the leds should be done every set interval, so the change speed can be adjusted.
The leds go on, but nothing seems to change after that. Have I done something wrong? No errors given in the Arduino IDE.
(it's my first coding project, there will probably be some beginner mistakes or workarounds)

// Declare pins
int LED01           = 3;
int LED02           = 5;
int LED03           = 6;
int LED04           = 9;
int LED05           = 11;

// Time variables
unsigned long currentTime;
unsigned long waitingTime[5];
unsigned long lastRound;

// LED Variables
int brightMin [5]   =       { 0,    0,    0,    0,      0     };    // Minimum brightness
int brightAvg [5]   =       { 200,  230,  210,  210,    235   };    // Average brightness
int brightMax[5]    =       { 0,    0,    0,    0,      0     };    // Maximum brightness
int timeWaitLow[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int timeWaitAvg[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int timeWaitMax[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int increment[5]    =       { 0,    0,    0,    0,      0     };    // Increment in brightness
int currentBright[5]=       { 200,  230,  210,  210,    235   };    // Current brightness

// LED Variables Possibilities
int brightMinPos[5] =       { 0,   20,    40,   0,      20    };    // Minimum brightness possibilities
int brightMaxPos[5] =       { 240,  250,  230,  225,    250   };    // Maximum brightness possibilities
int timeLowPos[5]   =       { 3000, 5000, 4000, 40000,  20000 };    // Waiting time on low brightness possibilities
int timeHighPos[5]  =       { 3000, 1000, 500,  2000,   4000  };    // Waiting time on high brightness possibilities
int timeAvgPos[5]   =       { 3000, 5000, 4000, 40000,  20000 };    // Waiting time on average brightness possibilities
int incrementPos[5] =       { 10,    20,    30,    40,      20     };    // increment in brightness possibilities

// Variables
bool needsUpdate[5]  =       { true, true, true, true,   true    };  // Does the led need a settings update?
bool reachedAvg[5]   =       { true, true, true, true,   true    };  // Has it reached the middle brightness?
bool reachedLow[5]   =       { false, false, false, false,  false};  // Has it reached the Lowest brightness?
bool reachedMax[5]   =       { false, false, false, false,  false};  // Has it reached the Highest brightness?
bool waitingAvg[5]   =       { false, false, false, false,  false};  // Is it waiting at the middle brightness?
bool waitingLow[5]   =       { false, false, false, false,  false};  // Is it waiting at the lowest brightness?
bool waitingMax[5]   =       { false, false, false, false,  false};  // Is it waiting at the Highest brightness?

// Directional variables
bool directionLED[5];

// Random variables
long randomNumber;                                                  //  Long to store random number

// counters
int i=0;

void setup() {
  Serial.begin (9600);                                              //  Start serial
  randomSeed(analogRead(A0));                                       //  Set randomseed
  lastRound = millis();

// Declare outputs
  pinMode (LED01, OUTPUT);
  pinMode (LED02, OUTPUT);
  pinMode (LED03, OUTPUT);
  pinMode (LED04, OUTPUT);
  pinMode (LED05, OUTPUT);
}

// Check if it should stop at bottom, middle or top
void checkStopPoint(){
  for (i=0;i<5;i++){
    if (currentBright[i] <= brightMin[i] && reachedLow == false) {                         // is it at the lowest brightness?
      reachedLow[i] = true;
      waitingTime[i] = millis();
    }else if (currentBright[i] == brightAvg[i] && reachedAvg == false) {                   // is it at the average brightness?
      reachedAvg[i] = true;
      waitingTime[i] = millis();
    }else if (currentBright[i] >= brightMax[i] && reachedMax == false) {                   // is it at the highest brightness?
      reachedMax[i] = true;
      waitingTime[i] = millis();
    }
  }
  i=0;
}

void checkResetPoint(){
  for (i=0;i<5;i++){
    if (reachedLow[i] == true && currentTime-waitingTime[i] >= timeWaitLow){
      reachedLow[i] = false;
      directionLED[i] = true;
    }else if( reachedMax[i] == true && currentTime-waitingTime[i] >= timeWaitMax){
      reachedMax[i] = false;
      directionLED[i] = false;
    }else if ( reachedAvg[i] == true && currentTime-waitingTime[i] >= timeWaitAvg){
      reachedAvg[i] = false;
      needsUpdate[i] = true;
    }
  }
  i=0;
}

// update LED variables
void updateLEDVariables(){
  for (i=0; i>=5; i++){
    if (needsUpdate[i] == true){
      randomNumber      = random(5);
      brightMin[i]      = brightMinPos[randomNumber];                   // Set random value for minimum brightness
      randomNumber      = random(5);
      brightMax[i]      = brightMaxPos[randomNumber];                   // Set random value for maximum brightness
      randomNumber      = random(5);
      timeWaitLow[i]    = timeLowPos[randomNumber];                     // Set random value for low waiting time
      randomNumber      = random(5);
      timeWaitMax[i]    = timeHighPos[randomNumber];                    // Set random value for high waiting time
      randomNumber      = random(5);
      timeWaitAvg[i]    = timeAvgPos[randomNumber];                     // Set random value for average waiting time
      randomNumber      = random(5);
      increment[i]      = incrementPos[randomNumber];                   // Set random value for increment value
      randomNumber      = random(2);
      if (randomNumber == 1){
        directionLED[i] = true;
      }else{
        directionLED[i] = false;
      }
      needsUpdate[i]    = false;
      reachedAvg[i]     = false;
    }
  }
  i=0;
}

void writeToLED(){
  analogWrite(LED01, currentBright[0]);
  analogWrite(LED02, currentBright[1]);
  analogWrite(LED03, currentBright[2]);
  analogWrite(LED04, currentBright[3]);
  analogWrite(LED05, currentBright[4]);
}

void loop() {
  currentTime = millis();
  updateLEDVariables();
  checkStopPoint();
  checkResetPoint();

  if (currentTime - lastRound >= 1){

    for (i=0;i<5;i++){
      if (directionLED[i] == true && !reachedLow && !reachedAvg[i] && !reachedMax[i] && !needsUpdate[i]){
        currentBright[i] = currentBright[i]+increment[i];                         // Go 1 value up
      }else if (directionLED[i] == false && !reachedLow[i] && !reachedAvg[i] && !reachedMax[i] && !needsUpdate[i]){
        currentBright[i] = currentBright[i]-increment[i];                         // Go 1 value down
      }
    }
  i=0;
  writeToLED();
  lastRound = millis();
  }
}

Add print statements in  your code, to know where the program is, and what values certain variables are. (you can increase times to easier see what is happening).

to make it easier, start with ONE LED - since you'll be outputting debug statements very quickly

You have three of these: "currentTime-waitingTime[i] >= timeWaitLow", but "timeWaitLow" and the others are an array. You use "!reachedLow", but again, that is an array. After fixing those, the problem remains. In the settings, enable more compiler output and set the level of compiler warnings higher. Compile the sketch, and scroll up to see a few problems. Which arduino board do you use? A value of 40000 does not fit in a integer for an arduino uno. I would update the leds between 20 and 50Hz (a fixed value), and the rest is math. Can you show a schematic or tell how the leds are connected?

upvote for properly formatted code

tip: if( reachedMax[i] == true) is the same as if( true == true) .................. so all you need is if( reachedMax[i]) ..... the converse is if( !reachedMax[i])


text:
Converting Client input char to int
I'm trying to print out the temperature from a DS18B20 sensor to my app via a tpc connection. Because I have two sensors connected I will need to call the one needed by an Index. This index comes from my app and is a char value which I need to convert it to an int for comparision later. The problem I have is the conversion from to input char value to int.
My code:

void loop() {
  //setting default sensor to 0
  sensorindex = 0;
  //starting server
  WiFiClient client = wifiServer.available();

  if (client) {
  Serial.write("Client connected");
          client.println("connected");
    while (client.connected()) {
      while (client.available()>0) {

        //instream from client/mobile device
        char c = client.read();
        //converting char c to int
        sensorindex = String(c).toInt() ;
        Serial.println(sensorindex);
      }

      //comparing client input to DS18B20 sensor index
      sensors.requestTemperatures();
      if(sensorindex == 1){
           client.println(sensors.getTempCByIndex(1));
           Serial.println("Index 1");
      }
      if(sensorindex == 0){
           client.println(sensors.getTempCByIndex(0));
             Serial.println("Index 0");
      }

      delay(50);
    }

    client.stop();
    Serial.println("Client disconnected");
  }
}

The serial output:
Client connectedIndex 0
Index 0
Index 0
Index 0
Index 0
Index 0
1
0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Index 0
Client disconnected

When I type in 1 from my android app it shows
1
0

in the output. What am I doing wrong?

why do you present a sketch with WiFi if you ask about Serial input conversion?

@Juraj It's the same in the end because I'm I will get a char value in both cases which I need to convert to an integer. And I've never asked directly for a serial input conversion but rather the wifi input, which is basically the same

so while client is connected you print the output based on the last sensorindex value. why?

So it refreshed the app every 50ms to show the current temp of the sensor which is chosen by the index value, which is based on the input which came from the app

so the only thing that bothers you is the 0 after the 1?

Yep because it should only return one line with the given integer but instead prints out two lines. And I can't use this integer or whatever it is to compare it because it this int hasn't got the exact value which came from the app, there must be a way to smoothly convert a char to int. Or at least a digit of a char.

do you send it as println? then the '\n' would be the second char

Oh yeah makes sense but why does it convert a 1 into a 10 in the first place?

1 is 1 and \n doesn't convert at all so toInt returns 0. you convert single chars - digits of the sent number (what could be done as c - 48).

@Juraj When I use sensorindex = c-48; it just prints out 1-38 or 0-38. How can I get rid of the second char digit? I tried using atoi but that just gave me an error cuz it isnt a const char

all c < 32 are nonprintable. but if you want to read the number, not only the digits, then use client.parseInt()

Tried client.parseInt() but it just printed out the digit I want, then waits and prints out a zero. Looks like a timeout which retuns a 0 if no other digit is transmitted.


text:
Where this function is defined?
This is the code for timer example in esp8266..(got from a website)
My doubt is where the function   timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE)  is defined ??
I am look in Ticker.cpp, but not found.

#include < ESP8266WiFi.h>
#include < Ticker.h >

Ticker blinker;

#define LED 2  //On board LED

//=======================================================================
void ICACHE_RAM_ATTR onTimerISR(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
    timer1_write(600000);//12us
}

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

    pinMode(LED,OUTPUT);

    //Initialize Ticker every 0.5s
    timer1_attachInterrupt(onTimerISR);
    timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
    timer1_write(600000); //120000 us
}

void loop()
{
}

Found your example code here. Please always provide a link, when you ask questions about a code from the web.

Also note that in C++, trivial functions are sometimes fully implemented in the .h file, so a search of the .cpp file might not reveal any code. This is especially common for access functions ("setters" and "getters"), where a function definition takes no more space (or very little more) than a declaration would.

Those functions have nothing to do with the Ticker library. Those functions are defined in the ESP8266 core.
The example you cite has this at the top of it:

Hardware Timer0 is used by WiFi Functions. We can use only Timer1. Use of timer instead of Ticker gives advantage of precision timing and You can get timer interrupt in micro seconds.

Note the use of "instead of Ticker" there. That says that the code below has nothing to do with Ticker.


text:
I need help makeing a light flash while a stepper is constantly moving
The starter code.
#include <Stepper.h>

const int stepsPerRevolution = 120;  // change this to fit the number
// for your motor of steps per revolution

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
int LEDPin = 13;
void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LEDPin,OUTPUT);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount=456);
  stepCount++;
  delay(35);
}

I want a light to flash in 15 sec increments while my stepper keeps moving. I basically want to combine that code with this one:
int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  digitalWrite(LEDPin,HIGH);
  delay(6000);
  digitalWrite(LEDPin,LOW);
  delay(6000);
}

do you have a question? ............ note: delay(6000); causes the arduino to stop for 6 seconds ..... examine the code of the BlinkWithoutDelay example sketch

In your loop() function, call two new functions. Let's call those maybeStep() and maybeBlink(). Each one of those reads the time, millis(), and subtracts the saved time when it last performed its action (stepping or toggling the LED). If that difference is >= the interval for that action, do the action and update the saved time to the current time.
Remember to make the saved times 'static' (or global) so they won't get over-written when these function return.
The BlinkWithoutDelay example program gives the general idea of how to read the clock instead of calling delay(), to decide when to perform each action.
Update:

new at Arduino and don't quite know what you mean?

Your loop function would something like this:
void loop(){
   maybeStep();
   maybeBlink();
}

Notice that loop now does nothing but call your action functions. Here's an outline of one of the action functions:
void maybeStep(){
   if the time_now > than the time_we_last_stepped by 35 millisec, then
      step again and store the new time_we_last_stepped;

   return;
}

Notice that this function may or may not take a step! It decides whether to step by reading the time and comparing it to the time of the previous step. But either way - step, or no step - it returns quickly. The maybeBlink() function will work exactly the same way: compare the time it last toggled the LED on or off to the amount of time it should wait between toggles. Then either toggle it (and save the time and on/off state) or not, and in any case, return to the loop.
Done this way, your loop() function will call those action function very frequently - way more often than the actions need to take place. Most of those times, nothing will happen. But every once in a while (a "tiny while" in human terms), one of those functions will take a step or switch the LED. If you write your code this way, loop() could call dozens or hundreds of such functions and all of those actions could still take place on time.
The key to this programming technique - called non-blocking programming - is that the action functions be very brief . They must decide quickly whether something needs to be done, and either do it or not, then return immediately.

thank you, but I am new at Arduino and don't quite know what you mean?

The delay() function causes the Arduino program to stop in it's tracks and "count to 100". While it's doing that, it's not doing anything else.
Therefore delay is not an option when you're trying to do more than one thing at a time.
you need to rewrite your code to use the millis() function to tell if your desired amount of time has passed. something like this:
unsigned long nextLEDTime = 0;
bool ledState = false;
#define delay 6000

int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  if (millis() >= nextLEDTime) //if it's time to toggle the LED
   {
     ledState = ! ledState;  //Invert the LED state
     digitalWrite(LEDPin, ledState);
     nextLEDTime = millis() + delay;  //Set nextLEDTime to the next time we need to do something
   }
}

Then you need to do the same thing with your stepper motor code, creating a separate variable to track the next time you want to do something with the stepper motor.
Put all your code in a single loop function that checks bot the nextLEDTime and the nextStepperMotorTime and takes appropriate action at the correct time for each thing you want to handle.


text:
pubsubclient won't compile in Arduino and VSCode IDEs
I've compiled successfully a year ago in Arduino IDE, but lately I'm getting fatal errors:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp: At global scope:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:473:8: error: redefinition of 'size_t PubSubClient::write(uint8_t)'
size_t PubSubClient::write(uint8_t data) {
^

In file included from /Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:7:0:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:160:19: error: 'virtual size_t PubSubClient::write(uint8_t)' previously defined here
virtual size_t write(uint8_t) {};
^

I've tried using VSCode. I've tried opening an issue on GitHub.
Thanks for any thoughts.

thanks. I'm having difficulty previewing.

reinstall the library

@Juraj - That works. Why?

The library is somehow modified. There should be no {} in virtual size_t write(uint8_t) {}; or the whole line shouldn't be in this .h.
Reinstall the library.


text:
Need help with buttonstate
I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.
Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?
code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int buttonyellow = 3;
int buttonred = 4;
int buttongreen = 5;
int buttonblue = 6;

int C,D,E,F;
int buzz = 7;

int buttonstate;

void setup()
{
  lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(buttonyellow,INPUT);
  pinMode(buttonred,INPUT);
  pinMode(buttongreen,INPUT);
  pinMode(buttonblue,INPUT);
}

void loop()
{
  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(buttonyellow);
  D = digitalRead(buttonred);
  E = digitalRead(buttongreen);
  F = digitalRead(buttonblue);

  buttonstate = digitalRead(C);
  if(buttonstate == HIGH){
    tone(buzz,523);
  }  else if ( buttonstate == LOW) {
    tone(buzz,1000);
  }else{
   noTone(buzz);
  }
  delay(50);
}

what is buttonstate = digitalRead(C);? if (C == HIGH){  was the plan?

have a really good look at your if-else block ..... what value of buttonstate will allow noTone(buzz); to run?

As jsotola has pointed out, there is a mistake in your code. Remove the line
buttonstate = digitalRead(C)

and replace
if(buttonstate == HIGH)

with
if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button


text:
İs that possible to a function return String OR Int depends on address
Well, I'm trying to use a HMI display and this HMI storing datas in separeta addreses. Such as integers addr. is between 0x80000 to 0x9ffff and also for string's addr is between 0 to 0x1ffff.
At this point I want to make function which is return integer if addr is a integer addr OR it will return string if addr is String addr. is that possible to make two kind of return type for a method.
I will detect integer or string from addr value like this:
????    HMT_SendCMD_ReadVPN16(INT32U Addr)

if((Addr > 0x00080000) || (Addr < 0x0009FFFF))
    {
        return int (); // at here it call a fonction and it will return integer
    }

else if(Addr < 0x0001FFFF)
    {
         return String (); // at here it call a fonction and it will return String
    }

There are ways of doing it using objects, but it's really messy and convoluted and really not worth the effort. Simpler to just have two functions, one for each type.

Move your logic to a new function that works with either. Then define 2 different functions with the same name and different arguments as needed. they can be auto-magically called and C++ will detect which one you need. You then call your logic from inside each of the wrappers, so that you don't have to code the full logic twice.

is that possible to make two kind of return type for a method

No. Functions are declared with a single return type. What is the point anyway of returning a blank string?
You need to redesign.

What is the point anyway of returning a blank string? - well there would be normal fuction like String abc();  I have add symbolic . anyway, if god of arduino, says no, it's over. thanks a lot :)

If the task were to store something different at the given address,
or if you would want to return a String representation of the integer,
you might be able to do so, but Majenko's comment and Nick's response, suggesting a different approach, are better.


text:
Why I cant get sizeof a pointer Array
well I am trying to get array size  to convert hex value to int value. but if I try to get size of array it returns every time 2. Actually .I dont understand. how to get array size, can you help me?
this is my code
unsigned long w;

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

  uint8_t * packet = read_packet();
  Serial.println(sizeof(packet)); // PROMLEM IS HERE, IT RETURNS EVERYTIME "2"

  for (int i = 0; i < 4; i++)
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }

  /*
    for (byte i = 0; i < sizeof packet; i++) {
      w = w + ((long)(packet[sizeof packet - (i + 1)]) << (i * 8));
    }

  */
}

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

}

uint8_t *read_packet() {
  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  Serial.println(sizeof buffer);
  return buffer;
}

if I print the packet array, all 4 elements are there 0,50,50,50. but size of array returns every time "2". even if I increase the array size.
maybe you can think why am I using pointers? because of my previous question answer is using this method. Read serial with header and end marker

sizeof is a compile-time item reporting the bytes something takes.  In this case that means the bytes that the numeric value of pointer itself uses.  If you allocate memory yourself, you'll have to store that separately.  Consider using a c++ vector.

@Abel There's no such thing as a C++ vector on Arduino - the STL is lacking.

there are implementations that should work well enough.
https://www.arduino.cc/reference/en/libraries/vector/

@mehmet Please see my answer to a previous question: http://arduino.stackexchange.com/a/25317/22924

A pointer is just a pointer. It's not an array. On 8 bit Arduinos the memory address range is a 16 bit value, so a pointer will always be 2 bytes.
You need to return two values from your function - the buffer pointer and the length of the buffer. This is usually done by passing an extra integer pointer parameter:
unsigned long w;

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

  uint8_t plen;
  uint8_t * packet = read_packet(&plen); // Pass the pointer to the plen variable to store the length in

  Serial.println(plen); // This now prints "4"

  for (int i = 0; i < plen; i++) // You can now use `plen` here
  {
    Serial.println(packet[i]); //if i print the packet array all elements are here
  }
}

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

}

uint8_t *read_packet(uint8_t *len) {

  static uint8_t buffer[4];

  buffer[0] = 0x00;
  buffer[1] = 0x32;
  buffer[2] = 0x32;
  buffer[3] = 0x32;

  if (len != NULL) *len = 4; // Store 4 in the length variable if provided

  return buffer;
}

just a quick add: since arduino uses C++, it is possible to use reference to array uint8_t (&buffer)[4] to pass actual array and have sizeof working properly, and template to automatically have non-fixed size array, and maintain compile-time check for size and sizeof-like functions working properly, even with static_assert. Extremely powerful to control what size of array a function can process all at compile time

@Lesto Sure. But that implies some level of knowledge on the part of the programmer to even know what a reference or a template is... And this is Arduino...

Majenko's answer explains things and shows how to fix your code, but the solution with static buffer inside the function is not common.
Common is to have int readBuffer(unit8_t* buffer, size_t size).
The parameters are the buffer provided by the caller and the size of that buffer. The return value is the count of bytes written by the function into the buffer.
Real example:
int WiFiEspAtBuffStream::read(uint8_t* data, size_t size) {
  if (size == 0 || !available())
    return 0;

  size_t l = rxBufferLength - rxBufferIndex;
  if (l == 0 && size > rxBufferSize) // internal buffer is empty and provided buffer is large
    return EspAtDrv.recvData(linkId, data, size); // fill the large provided buffer directly

  // copy from internal buffer
  fillRXbuffer();
  for (size_t i = 0; i < l && i < size; i++) {
    data[i] = rxBuffer[rxBufferIndex++];
  }
  if (size <= l) // provided buffer was filled
    return size;
  return l + read(data + l, size - l); // handle the rest of provided buffer
}


text:
Is SPI a good way to connect two rfid modules on separate arduino boards?
RFID access control
I have two separate rfid projects on separate arduino, the first project requires 2 minutes of contact between the tag and the reader after which it turns the LED on. the second project is a simple rfid access control, but on this access can only be granted if the conditions on the first tag were met. I am trying to use SPI for this but do not know if it would work, any suggestions on any other way of communication between two arduino boards?

You can use SIMPLE GPIO for this. If set GPIO in ARDUINO1 when condition is matched and MONITOR its level on ARDUINO2 to grant access.

is it possible that you have some sort of an example since I am a beginner

why two Arduinos for a so simple task?

Sure it is possible. Have you tried it? If yes, you can ask a question about it and include the code, so that we can help you. With this question the answer is simply: yes, it is possible. But this will not help you implementing it

Its very easy.

Set one PIN of ARDUINO as ouput pin. You will write that PIN HIGH when your conditions are matched in ARDUINO1 then SET LOW after 1 mS.
Connect that PIN of ARDUINO1 to external Interrupt PIN of ARDUINO2.
Write a CODE for ARDUINO2 such that when EXTERNAL INTERRUPT OCCURS it will set variable high indicating that Conditions is Matched in ARDUINO1.
While providing access to on ARDUNO2 check that variable status if it is HIGH grant access and SET it LOW.

This is the basic Structure you can follow using interrrupt.

how would it know that is the same card?

Yeah in that case you can have UART for sending the CARD ID to ARDUINO2 also. But in that case there no need of using two ARDUINO Setup. If you are scanning and matching in ONE SETUP, then why you are SCANNING and Matching it Again in another setup. Else if SETUP1 is used to store the CARD ID In database and  SETUP2 is used to provide access to that CARD ID based on that database.

how can I connect 2 rfid modules on one Arduino board

Why you need two RFID Modules?

also once I have them on the same board do i have to do only GPIO connections or GPIO and UART

If you want to know the card number then you need the UART as well.

@Ayat.H Of Course you can use SPI or I2C on separae boards, i think you just need to define a Master board and a Slave board to access control.


text:
Pro Micro board not responding to anything
I just got a couple of Arduino Pro Micros for a custom keyboard build. Before testing them with the Arduino IDE, I tried to test them with qmk by shorting RST to GND to try and flash it. After a few seconds of holding RST, I got a single blink and nothing else, and qmk didn't seem to have detected the reset.
I've tried setting "Board" to "Arduino Micro" and "Arduino Pro or Pro Mini". I'm on Arch Linux and no matter which USB port is plugged in, the IDE only shows /dev/ttyS0). I tried uploading the "Blink" example, as well as "Burn Bootloader", but only got programmer is not responding like so:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

If RESET is connected to GND then the Arduino is going to do nothing. Nothing at all. Nada. It'll be like it's not even there. ttyS0 is the internal UART of your PC (it may not even have a connector...).

activate the bootloader with a double reset. Micro is not Mini. for "burn bootloader" you need a programmer hardware

It turns out I had to use the port ttyACM0 (and not ttyS0) which wasn't found at the time. The port was there the next day and I have no idea why it wasn't there before.
Also, I thought I had to press and hold RST for a couple of seconds to reset the Pro Micro, but I actually have to press it twice in a row.
I've managed to flash the firmware for my keyboard by double-pressing RST.

the sketch handles the usb, without working sketch there is no USB and the bootloader must be activated to handle USB


text:
Memory problem? dtostr() and strcat()
I've been dealing with this for quite a while now and searching all over for answers.. I'm trying to put together two floats into a char*. Separated by a ",".
This is the code I'm working with.

#include <DHT.h>
#include <RH_ASK.h>
#include <SPI.h>

#define DHT_pin 10
#define DHT_type DHT11

DHT dht(DHT_pin, DHT_type);
RH_ASK rf_driver;

float temp;
float hum;

char ch_temp[6];
char ch_hum[6];
char msg_out[12] = "";

void setup() {
  Serial.begin (115200);
  dht.begin();
  if (rf_driver.init()) {
    Serial.println("Radio transmitter initiated..");
  }
  else {
    Serial.println("Radio transmitter failed to initiate..");
    delay(1000);
  }
}
void loop() {
  temp = dht.readTemperature();
  hum = dht.readHumidity();

  dtostrf(temp, 5, 2, ch_temp);
  dtostrf(hum, 5, 2, ch_hum);
  strcat(msg_out, ch_temp);
  strcat(msg_out, ",");
  strcat(msg_out, ch_hum);

  Serial.println(msg_out);
  rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
  rf_driver.waitPacketSent();
  Serial.print("data sent, package size: ");
  Serial.println(strlen(msg_out));
  delay(1000);

}

I have tried using different sizes of the char arrays, but it just goes crazy.
This is the console output:
Radio transmitter initiated..
22.00,34.00
data sent, package size: 11
⸮⸮Radio transmitter initiated..
22.00,34.00
data sent, package size: 11

So on its way through the second loop it fails, restarts and then on its third way through it just gives up... What am I doing wrong? :( Really sad over this.

Your sketch is running on borrowed memory.
Every time the loop function runs, the new text is concatenated with strcat() and the buffer msg_out is never reset.
The first time 12 bytes are used, the second time 23 bytes, the third time 34, and so on.
The solution in the answer by @VE7JRO will fix that, but I prefer not to use dtostrf() and transmit binary data.
I see a few other problems as well:

Why do you want to transmit readable ASCII text? Use binary data.
Either float numbers or integers. For example an integer in 1/100 degrees.
The RadioHead library uses a lot of memory. You can not use an other
library that uses also a lot of memory.
The value of '5' for dtostrf is the minimal width,
so you better make those arrays for example 20 bytes.
I prefer to put those arrays temporarily on the stack.
The DHT11 is not accurate. If you upgrade to a better sensor with I2C,
then you need more libraries (the Wire library and a sensor library),
and you might run out of sram memory.
When using the RadioHead library in default mode, it uses three
pins (rxPin=11, txPin=12, pttPin=10). You better add a comment
section to your sketch to explain that you should not use those pins.
You have already a
conflict at pin 10 for the DHT sensor and the pttPin.

The old and no longer supported VirtualWire library has some bugs, but it uses less memory than the RadioHead library. The RadioHead library is not optimized for Arduino boards like the Uno, Nano, Leonardo, and others. It even requires to #include <SPI.h> because that is often used with transceivers, even if the SPI bus is not used in RH_ASK mode (thanks to @VE7JRO for explaining this in the comment below).

The easiest way to transmit more than one value is with an array.
float myData[2];
myData[0] = 23.456;
myData[1] = 68.0;
rf_driver.send((uint8_t *)myData, sizeof(myData));

The sizeof() is not a real function, it tells the compiler to fill in the size of that variable. Since a float is 4 bytes, you may also fill in the number 8 for the second parameter.
There are a number of solutions for the receiver. I like to use a pointer to the buffer, but perhaps it is easier to copy them to variables with memcpy().
float myData[2];
if (driver.recv(buf, &buflen)) {
  if (buflen == sizeof(myData) {  // extra check
    memcpy((uint_8 *)myData, buf, sizeof(myData));
    Serial.println(myData[0]);
    Serial.println(myData[1]);
  }
}

When the receiver is also an Arduino board, then there should be no problem. When the receiver is something else, you might have to check if the byte-order is the same. The float variable of a Arduino is 100% IEEE compatible, but sometimes it is easier to use only integers.
The most common way is to use a struct. A struct is a package that can hold all sorts of data (integers, bytes, arrays, and so on). The receiver and the sender should have exactly the same definition for the struct of course.

The OP may not be using SPI. If you remove the include from the sketch, it won't compile. There is a sketch called ask_transmitter.pde that comes with the library. It has a comment beside the SPI include that says: "Not actually used but needed to compile". I am new to Arduino, so I do not understand this comment. If none of the RadioHead files use any functions, etc. in the SPI library, why won't it compile with out it? I second your recommendation to get rid of the "low quality" sensor the OP is using. For $1.28USD, you can get a decent I2C Bosch sensor like a BMP280 at Aliexpress.com.

@VE7JRO right, I knew it but forgot about it.

Thank you for this thorough answer! Really appriciate it!

@Jot Thank you for this thorough answer! Really appriciate it!! The reason i convert into Char* is to put it together, so i can send it in one package and then later on an other MCU easily take it apart and display seperatly. How would i go about putting to floats together and being able to seperate them later?
I've tried VirtualWire, but in this case this is alll this MCU is supposed to do. But I will keep this in mind in the future! Thanks!
This project is for a school assignment, but i've noticed the DHT11 is not very reliable..
Thanks for pointing out the PIN conflict!!

@Love.Berg I have added an extra section to transmit an array. It is transmitted as binary data and received as binary data, so all you have to do is to take the binary data from the float variables, transmit them and in the receiver put the binary data back into float variables.

If you remove the RF and sensor code, the sketch seems to work correctly when printing to the serial monitor. The first time you call rf_driver.send() in the loop, it works. The second time through the loop, and every time there after, it starts printing corrupted data. I don't have a definitive answer why this is happening, but I do have a way to "fix" it (or a "hack", if you prefer to call it that).
Using memset() to set the msg_out char array to all 0's before you use it seems to fix the problem. Here is a test sketch which is very similar to yours. I'm using some hard coded values for the sensor data because I don't have one of those sensors.
#include <RH_ASK.h>
#include <SPI.h>
RH_ASK rf_driver;

float temp;
float hum;

char ch_temp[6];
char ch_hum[6];
char msg_out[12] = "";

void setup() {
  Serial.begin (9600);
  if (rf_driver.init()) {
    Serial.println("Radio transmitter initiated..");
  }
  else {
    Serial.println("Radio transmitter failed to initiate..");
    delay(1000);
  }
}
void loop() {

  // Set the buffer contents to all 0's
  memset(msg_out, 0, sizeof(msg_out));

  temp = 12.345;
  hum = 67.890;

  dtostrf(temp, 5, 2, ch_temp);
  dtostrf(hum, 5, 2, ch_hum);
  strcat(msg_out, ch_temp);
  strcat(msg_out, ",");
  strcat(msg_out, ch_hum);

  Serial.println(msg_out);
  rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
  rf_driver.waitPacketSent();
  Serial.print("data sent, package size: ");
  Serial.println(strlen(msg_out));
  delay(1000);
}

I'm late to the party, but here goes:
msg_out[] is a global but it doesn't need to be. Move it's definition and initialization into loop(), the only function that uses it. Then it gets initialized at every entry to loop() rather than just once at program initialization. There's no need to clear the array; just zeroing the zero-th element of it initializes it for character-string use, and that is what your initializer now does (but only once).


text:
Arduino RGB LED not working all the time?
I was creating an RGB LED System with one 1 RGB LED controlled by an IR Remote. I wanted to assign a button to trigger a mood-light which cycles through the rainbow, and that works fine. But when I try to make a mode where you can change RGB Values directly, it doesn't work properly. I assigned numbers on the remote to switch the colour that you are changing (e.g 1 is red, 2 is green etc.), and the volume controls how much light is coming but when I have two colors with positive values it only displays one. I have no idea why because the moodlight works fine and even transitions smoothly.
//www.elegoo.com
//2016.12.9

#include "IRremote.h"

// Define Pins
int BLUE = 3;
int GREEN = 5;
int RED = 6;

int addValue = 10;

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

int blueValue = 0;
int greenValue = 0;
int redValue = 0;

bool isMoodLightOn = false;
bool isBlueModeOn = false;
bool isGreenModeOn = false;
bool isRedModeOn = true;

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{

  switch(results.value)

  {
  case 0xFFA25D: Serial.println("POWER"); break;
  case 0xFFE21D: Serial.println("FUNC/STOP"); break;
  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK"); break;
  case 0xFF02FD: Serial.println("PLAY/PAUSE");
                 isMoodLightOn = !isMoodLightOn;
                 if (isMoodLightOn == false) {
                  isBlueModeOn = true;
                  isGreenModeOn = false;
                  isRedModeOn = false;

                  setColor(redValue, greenValue, blueValue);
                 } else {
                  isBlueModeOn = false;
                  isGreenModeOn = false;
                  isRedModeOn = false;
                 }
                 break;
  case 0xFFC23D: Serial.println("FAST FORWARD"); break;
  case 0xFFE01F: Serial.println("DOWN");
                 if (isBlueModeOn) {
                  if (blueValue > 0) {
                    blueValue = blueValue - addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 if (isGreenModeOn) {
                  if (greenValue > 0) {
                    greenValue = greenValue - addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 if (isRedModeOn) {
                  if (redValue > 0) {
                    redValue = redValue - addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 break;
  case 0xFFA857: Serial.println("VOL-"); break;
  case 0xFF906F: Serial.println("UP");
                 if (isBlueModeOn) {
                  if (blueValue < 100) {
                    blueValue = blueValue + addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 if (isGreenModeOn) {
                  if (greenValue < 100) {
                    greenValue = greenValue + addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 if (isRedModeOn) {
                  if (redValue < 100) {
                    redValue = redValue + addValue;
                    Serial.println("Red: " + String(redValue) + "Green: " + String(greenValue) + "Blue: " + String(blueValue));
                    setColor(redValue, greenValue, blueValue);
                  }
                 }
                 break;
  case 0xFF9867: Serial.println("EQ"); break;
  case 0xFFB04F: Serial.println("ST/REPT"); break;
  case 0xFF6897: Serial.println("0"); break;
  case 0xFF30CF: Serial.println("1"); isRedModeOn = true; isGreenModeOn = false; isBlueModeOn = false; break;
  case 0xFF18E7: Serial.println("2"); isRedModeOn = false; isGreenModeOn = true; isBlueModeOn = false; break;
  case 0xFF7A85: Serial.println("3"); isRedModeOn = false; isGreenModeOn = false; isBlueModeOn = true; break;
  case 0xFF10EF: Serial.println("4"); break;
  case 0xFF38C7: Serial.println("5"); break;
  case 0xFF5AA5: Serial.println("6"); break;
  case 0xFF42BD: Serial.println("7"); break;
  case 0xFF4AB5: Serial.println("8"); break;
  case 0xFF52AD: Serial.println("9"); break;
  case 0xFFFFFFFF: Serial.println("REPEAT"); break;

  default:
    Serial.println(" other button   ");

  }// End Case

  delay(500); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");

  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

  setColor(redValue, greenValue, blueValue);

  isBlueModeOn = true;
  isGreenModeOn = false;
  isRedModeOn = false;

  irrecv.enableIRIn(); // Start the receiver

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  setColor(redValue, greenValue, blueValue);

  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }

  setColor(redValue, greenValue, blueValue);

  if (isMoodLightOn == true) {
      int delayTime = 10; // fading time between colors

      redValue = 255; // choose a value between 1 and 255 to change the color.
      greenValue = 0;
      blueValue = 0;

      // this is unnecessary as we've either turned on RED in SETUP
      // or in the previous loop ... regardless, this turns RED off
      // analogWrite(RED, 0);
      // delay(1000);

      for(int i = 0; i < 255; i += 1) // fades out red bring green full when i=255
      {
        redValue -= 1;
        greenValue += 1;
        // The following was reversed, counting in the wrong directions
        // analogWrite(RED, 255 - redValue);
        // analogWrite(GREEN, 255 - greenValue);
        setColor(redValue, greenValue, blueValue);
        delay(delayTime);
      }

      redValue = 0;
      greenValue = 255;
      blueValue = 0;

      for(int i = 0; i < 255; i += 1) // fades out green bring blue full when i=255
      {
        greenValue -= 1;
        blueValue += 1;
        // The following was reversed, counting in the wrong directions
        // analogWrite(GREEN, 255 - greenValue);
        // analogWrite(BLUE, 255 - blueValue);
        setColor(redValue, greenValue, blueValue);
        delay(delayTime);
      }

      redValue = 0;
      greenValue = 0;
      blueValue = 255;

      for(int i = 0; i < 255; i += 1) // fades out blue bring red full when i=255
      {
        // The following code has been rearranged to match the other two similar sections
        blueValue -= 1;
        redValue += 1;
        // The following was reversed, counting in the wrong directions
        // analogWrite(BLUE, 255 - blueValue);
        // analogWrite(RED, 255 - redValue);
        setColor(redValue, greenValue, blueValue);
        delay(delayTime);
      }
  }
  setColor(redValue, greenValue, blueValue);
}/* --(end main loop )-- */

void setColor(int red, int green, int blue) {
  analogWrite(BLUE, blue);
  analogWrite(GREEN, green);
  analogWrite(RED, red);
}

You are using setColor() twice inside your loop function outside of the moodlight code. When not in moodlight mode, this functions repeats rapidly, doing many analogWrites in a short time. This resets the PWM hardware everytime, effectively distorting the signal. Try to remove those 2 lines (you don't need them, since you are already setting the colors within translateIR() ). And you may want the code to be more responsive when in moodlight mode. Then you should restructure your code to be non-blocking, like in the BlinkWithoutDelay example of the Arduino IDE.

I will formulate my comment as a longer answer.
Inside your loop() function, you use setColor() twice, directly in the lowest level. When you are not in the moodlight mode, the whole if statement after it will not be executed, so there isn't much happening inside one iteration of the function and it will cycle through very fast, setting the colors again and again.
THe setColor() function only consists of calls to analogWrite(). It configures the Atmegas hardware, so that a PWM signal will be generated at the pin. For doing so, the corresponding hardware registers (for one of the timers). This also let's the PWM wave start again. If you are doing this very fast (meaning in the range of the PWM signal itself or faster), you will destroy the complete PWM waveform by starting over and over again. Image it as if you wait press the replay button on your music player again and again very fast. You would be able to recognize the music, as it is chopped up due to the replaying.
The aforementioned two lines are not necessary either, since the output of the PWM wave is done by hardware and does not require any code after it has been turned on by analogWrite(). So you can simply delete those two lines.


text:
Can I use arduino to generate 8mhz frequency ultrasonic pulses in piezo discs?
void setup()
{
    pinMode(freqOutputPin, OUTPUT);
    Serial.begin(9600);

    // Set Timer 2 CTC mode with no prescaling.  OC2A toggles on compare match
    //
    // WGM22:0 = 010: CTC Mode, toggle OC
    // WGM2 bits 1 and 0 are in TCCR2A,
    // WGM2 bit 2 is in TCCR2B
    // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
    //
    TCCR2A = ((1 << WGM21) | (1 << COM2A0));

    // Set Timer 2  No prescaling  (i.e. prescale division = 1)
    //
    // CS22:0 = 001: Use CPU clock with no prescaling
    // CS2 bits 2:0 are all in TCCR2B
    TCCR2B = (1 << CS20);

    // Make sure Compare-match register A interrupt for timer2 is disabled
    TIMSK2 = 0;
    // This value determines the output frequency
    OCR2A = ocr2aval;

    Serial.print("Period    = ");
    Serial.print(period);
    Serial.println(" microseconds");
    Serial.print("Frequency = ");
    Serial.print(freq);
    Serial.println(" Hz");
}

void loop(){}

I am working on a project where i need an ultrasonic pulse of 8Mhz every one second and emitter is piezo disc. Please help me with the code.

If you are using an AVR-based Arduino, read Timers and counters, by Nick Gammon.

That's an interesting article, but it seems to be about detecting pulses, not making them. Did I miss something?

actually i need both emission and detection but currently i am working on emitting the pulses using arduino and piezo discs but i am not so good with coding

what code have you tried so far?

ive embedded the code above

@Danish and why it does not work? What does it do? What do you expect it to do?

With 8 Mhz pulse, I assume you mean a pulse of 0.125 µs duration every second. "Frequency" may be misleading here.
Since the ATmega328 in the Arduino Uno is only clocked at 16 Mhz, you only have one extra cycle before having to turn it back off. Debugging and developing at this sort of speed absolutely requires a good oscilloscope.
I would attempt setting your output pin via register, and then turning it off again right after. Use cli() to prevent interrupts during your desired pulse.
void setup() {
  DDRC |= (1 << DDRC0);   //Set PC0 as output (Analog Pin 0)
}
void loop() {
  cli();                  //Disable interrupts
  PORTC = 0b00000001;     //Set Analog Pin 0 HIGH
  PORTC = 0b00000000;     //Set Analog Pin 0 LOW
  sei();                  //Enable interrupts again
  delay(1000);            //Delay for 1000ms until next pulse
}

Beware that this would also set all other pins on Port C (Analog Pins 1 through 5) LOW.
This
  PORTC |= (1 << PORTC0);     //Set Analog Pin 0 HIGH
  PORTC &= ~(1 << PORTC0);     //Set Analog Pin 0 LOW

would be cleaner and only affect Analog Pin 0, but it may take more than one clock cycle to execute.
Unfortunately, I don't have a quick enough oscilloscope to try this out.
If it is too fast (e.g., you get a pulse of duration 0.06125 µs, you may want to insert another PORTC = 0b00000001; before turning it off again. It is not unlikely that compiler optimization might just remove this when compiling, so you may have to set some other register to waste that one clock cycle.

Your second snippet is the way to go. It is almost guaranteed to generate the proper sbi and cbi instructions at any optimization level (save, maybe, level zero). These instructions execute in two clock cycles each, thus you get a pulse exactly two cycles wide.


text:
Servo Program Questions
Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).
My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.
So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.
example:
int sensor = 26;
int PUL = 23; //define Pulse pin
int DIR = 25; //define Direction pin

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(115200);
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
}

void loop() {
  int sen = digitalRead(sensor);
  if (sen == HIGH) {
    Serial.println("HIGH");
    delay(1000);
     for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
  } else if (sen == LOW) {
    Serial.println("LOW");
    delay(1000);
    } else {
    Serial.println("ERROR");
  }
}

EDIT
I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255
for (int i=0; i<500; i++) {
  for( int x=0; x<255; x++){
  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }
}

it is unclear what you have, how it is connected and what you are trying to do exactly

Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?
this should do what you want. i and x increase together until x reaches 255 then it wont increment.
int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}


text:
How do i fade a colorwipe from off to on in 1 color?
So I want to make the same effect as a colorwipe (like going around in a circle turning leds on till they all turn on) except that instead of going from off to 100% brightness immediately I need it to look more natural by making it fade from off to on gradually to a single color and the LEDS should stay on after the fade on is complete. This is my current code and i cant figure out how to make it fade. everything ive found on google is massively complex to do a simple thing. is it really that complex to accomplish this?
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUM_LEDS 24
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);

void setup() {
  strip.setBrightness(2);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  colorWipe(strip.Color(255, 255, 255, 255), 70); //white

}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(50);
  }
}

Do you want them to glow up one after the other or have the next one to start glowing while the previous one hasn't yet reached full brightness?

Note that the "wait" variable is not actually used in your colorwipe function.
The colorwipe function seems to turn them all on in succession. The only thing you need to do is add fading to it.
for(uint16_t i=0; i<strip.numPixels(); i++) {
    for(uint8_t brightness=0; brightness<maxBrightness; brightness++){
       strip.setPixelColor(i, strip.Color(brightness, brightness, brightness, brightness );
       strip.show();
       delay(wait);
  }

See my answer here.
Code from that answer:
/*
 *
 * NeoPixels demo - fades colours (in array) up and down
 *
 */

#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup()
  {
  ledsetup();
  } // end of setup

float patterns [] [3] = {
  { 1, 0, 0 },  // red
  { 0, 1, 0 },  // green
  { 0, 0, 1 },  // blue
  { 1, 1, 0 },  // yellow
  { 1, 0, 1 },  // magenta
  { 0, 1, 1 },  // cyan
  { 1, 1, 1 },  // white
  { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
  { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

};

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

void loop()
  {

  for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
    {
    // fade up
    for (byte m = 0; m < 100; m++)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for

    // fade down
    for (byte m = 100; m > 0; m--)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for
    } // end of for each array item

  } // end of loop

thanks! so i just copy and paste this whole thing in and it will work? or do i add it to my existing code? im very new to this.

Also just to clarify i need it to go around in a circle and fill up the neopixel circle. (think like a magic circle).

To use that exact code you need my library. Also the NeoPixels have to have their data pin connected to D11 (digital pin 11) on the Uno.

That particular code fades in the colours shown (red, green, blue etc.) in sequence.

ah i just need white.

ok so @nick gammon your program works but all it does it fade. the lights dont move around the circle at all. i dont know how to make them move in a circle.


text:
String and heap confusion
I hope you all well.
Recently after view unknown crashes I decided it can be related with me messing with "heap"
After reading few sources on heaps and how it works it kind of confusing. Some sources mention that you can F() everything and it will be fine and others mention reserving space for strings with "reserve()"
I am looking for suggestions how possibly eliminate or or control?
I will post snapshot of code below where the evil "String" is used few times.
////////sending data
    senddata(String(temp), String(hum), String(dis), String(flood), String(heaterstatus), String(humidifierstatus));
    //////////sending data

void senddata(String temp1, String hum1, String dis1, String flood1, String heater1, String humid1) {   /////sending all field values in one go
  //////////sending data
  String getData = "GET /update?api_key=" + API + "&field1=" + temp1 + "&field2=" + hum1 + "&field3=" + dis1 + "&field4=" + flood1 + "&field5=" + heater1 + "&field6=" + humid1;
  sendCommand("AT+CIPMUX=1", 5, "OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
  esp8266.println(getData); delay(1500); countTrueCommand++;
  sendCommand("AT+CIPCLOSE=0", 5, "OK");
}

Yes, you could make a global String for getData and reserve space and reuse it every time the function is called. But what with String(getData.length())?
And the parameters? You create a new String for every parameter. And the function senddata doesn't take a reference to the String (String&), but it makes a new copy of each String parameter. So you create 12 small Strings with every call to this function. This is the evil of String. It does everything no matter at what cost.
And your sendCommand takes String too. That is why you can do "AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT and "AT+CIPSEND=0," + String(getData.length() + 4) as parameter to it. So every call to sendCommand creates two small Strings. That is 8. And every + on String can trigger a reallocation on heap.
Use C strings
void senddata(int temp1, int hum1, int dis1, int flood1, int heater1, int humid1) {
  char getData[256];
  snprintf(getData, sizeof(getData), "GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d",
      API, temp1, hum1, dis1, flood1, heater1, humid1);
  sendCommand("AT+CIPMUX=1", 5, "OK");
  char buff[32];
  snprintf(buff, sizeof(buff), "AT+CIPSTART=0,\"TCP\",\"%s\",%d" , HOST, PORT);
  sendCommand(buff, 15, "OK");
  snprintf(buff, sizeof(buff), "AT+CIPSEND=0,%d" , strlen(getData) + 4);
  sendCommand(buff, 4, ">");
}

void sendCommand(const char* command, const int timeout, const char* find) {

F macro optimizes memory use, by using data stored in flash memory. The snprintf_P function is a version of snprintf for format string from flash.
snprintf_P(getData, sizeof(getData), (const char*) F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
  API, temp1, hum1, dis1, flood1, heater1, humid1);

One of the classes of my StreamLib is CStringBuilder. With it the code could be:
char getData[256];
CStringBuilder sb(getData, sizeof(getData));
sb.printf(F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
    API, temp1, hum1, dis1, flood1, heater1, humid1);
sendCommand("AT+CIPMUX=1", 5, "OK");
char buff[32];
CStringBuilder sb2(buff, sizeof(buff));
sb2.printf(F("AT+CIPSTART=0,\"TCP\",\"%s\",%d") , HOST, PORT);
sendCommand(buff, 15, "OK");
sb2.reset();
sb2.print(F("AT+CIPSEND=0,"));
sb2.print(sb.length() + 4);
sendCommand(buff, 4, ">");

Hello @Juraj and thanks for getting involved. The snprintf function seems to be very interesting and suitable. I had a good look for a good guide on the function, however, limited answers. What i would like to find out is what does it mean when you use %d and %s or how they are diffent?

printf is 50 years old. http://www.cplusplus.com/reference/cstdio/printf/

Thanks for that, its a great reference. Do you know if there are any limitations to where i can use it? It seems to be that any floats cant be used? Is there any common functions that may conflict?

using printf versions takes a little more of flash memory. float support can be enabled, but it takes even more program memory. Alternative is to use my CStringBuilder class, which builds a C string using the same simple functions like Serial


text:
Arduino Uno "WiFi Developer Edition" - How to disable WiFi?
I'm using Arduino Uno "Wifi Developer Edition". I made my Arduino to get connected with my local network based on http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi
Now I would like to disable it and work with USB serial communication to upload sketches. But now I'm unable to upload sketches even if I select the serial port. I'm getting an AVRDUDE : seropen() Access is disabled error. I could perfectly do uploading if I select the networked port of the same Arduino.
Can I know why ?

The serial should work regardless of the network. You could check the webinterface, but the problem seems to be on the serial side. Though I've never worked with the Arduino wifi

Have you installed al serial drivers and does it show in device manager? And try restarting your PC and running the Arduino IDE as administrator

You don't need to disable the Wi-Fi. The serial works with the Wi-Fi enabled.
You need to first install the driver and then select the Serial port on the Arduino IDE.

did you ever work with Arduino Uno WiFi Developer Edition?

The reason why "Arduino WiFi Dev Ed" USB upload sometimes doesn't work, is the esp8266 connected to UART of Atmega for the OTA upload. If esp8266 doesn't boot, it doesn't set pin 4 to disconnect from Atmega UART and the connection to UART stays and disturbs the upload from IDE.
The esp8266 hangs sometimes, because it has pin 2 floating on this board, but there is a trace and a soldering point on the bottom of the board for pin 2. If it is touched or otherwise grounded the esp8266 doesn't boot until the potential on the pin rises.
More about Uno WiFi Dev Ed hardware here.

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


text:
Programming Arduino Micro via RX/TX
I can't access my Arduino Micro's USB programming port when it's in my project. I want to reroute the RX and TX pins outside to a serial-to-usb adapter.
I have this on hand from a while ago. I found the RX and TX pins in the serial connector and I connected them to the RX and TX pins of the Arduino as well as GND but when I try and program the device nothing happens. I usually get an open port error or something like that but the programming LED on the adapter doesn't light up. Conversely if I try using the Basic Stamp software I at least get a programming LED to light up on the adapter.
Do I need an FTDI breakout instead? Or am I wiring something wrong?

Well, RS-232 signals are not compatible with 5V ttl logic of Arduino.

how is the device i mentioned any different than say and ftdi breakout except for a different connector?

Clearly, you need another decoder on the micro side to convert the RS-232 to normal ttl signal.

Is there any provision for RESET or you manually do it while uploading?

Yes I wired in the reset. The device actually resets and I see the programing led flash briefly but nothing happens. Its strange, because I can program the basic stamp just by connecting the rx and TX. I feel like your statements must hold water in that the arduino can't interface somehow.

Have a look at this link

first of all, the ATmega32u4 bootloader only listens on its native USB

RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. Read more
Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a simple converter.
Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".

I would say that an: ftdi->USB board, Bluetooth board or ICSP programmer is much easier than using yet another Arduino. (The Bluetooth one is tricky, but worth it if you don't like cables).

yes you can, use a FTDI 232 USB TO SERIAL  then set the Arduino IDE to the board you will be programing, and the serial port the FTDI RS232 Programmer is on.
connect the two rx to tx, and tx to rx, also the vcc of programmer to Arduino 5v pin.
then press and hold the reset button, and upload "regular".
The trick is to let go of RESET just after it finishes compiling, and it will get programed.
i think between 1-2 seconds after it finishes compiling and the compiling line just turned all green.
This is also how wireless programmer work using a Bluetooth module. I tried using the DTR pin to reset, but that did not work for me.

it is a Micro so ATmega32u4 with native USB. the bootloader doesn't listen on Serial1


text:
16 by 8 Keyboard matrix
I am working on a project, trying to construct an 80 button keypad. My problem is how to multiplex it so that i only feed the arduino with two sets of BCD or binary(whichever is easier) which are supposed to drive a 75 led display board simultaneously with a pair of 7 segments. The led display board is remote, which means i should drive the boards serially. The other 5 buttons remaining out of 80 are for other functions such as clear last number etc.
Please help!

Thank you very much guys. To answer FuaZe, it is 16*8 but will not use the whole 128 buttons. These extra buttons are for future expansion. The input should consist 16colums and 8 rows. The remote output board is a led matrix numbered from 1 to 75, arranged in a 15colums and 5rows. The same display board is to have a two digit 7seg display. The remote board is to be accessed serially so as to use few cables.
When I press a button on the matrix, say column 5 row 2 the number 20 should appear on the 7seg plus a correspondind diode on column 5 row 2 to light. In short if is a bingo board with numbers 1 to 75..

Why is the name of the question: "16 by 8 keyboard matrix", 16*8 does not equal 80 buttons?

Yes, 16x8 = 128 as either 16 outputs multiplexed by 8 inputs, or vice versa, and maybe multiplexing the 75+2x7 segments as another 10 by 7.  Seems like 16+8+10+7 =  41 pins it would fit easily on a 54 IO pin mega.  Maybe you want a 80 button multiplexed input, along with multiplexed 8x10 and 7x2 outputs?  Tell more about the remoteness requirement and the board vs boards requirements.

Ask your favorite internet finding service about "charlieplexing keys". This may help to connect more keys using less pins.

Another option would be using both shift registers and port expanders, like Adafruit's MCP23017 I2C Port Expander.
You can use that for the buttons, just get a few of them and hook them up on the I2C bus and you have over eighty pins for the price of 2! If you choose to use the previously stated expander, you will also benefit from Adafruit's library.
Then, use a shift register for your LEDs, using one of the pins that is not I2C.
Note: Pin expanders can handle input and output. Shift registers are only for output!
Good luck!

Actually there are shift registers for input as well - such as the CD4021B by Texas Instruments: https://www.ti.com/product/CD4021B. It's widely supported (for example arduino library: https://www.arduino.cc/en/tutorial/ShiftIn) and has a 16 bit version as well

Easiest would be to use 2 arduino's, which are connected in some way.
One of them should tell the other one what to do. I suggest you make the one reading the buttons the "master" and the other one it's "slave" device.
You could use 8 inputs, for each column and 10 outputs for each row.
Then you check all 8 inputs per column (pretty rapidly) and then you'll be able to read every button.
You could choose to either send changes or just every value to the slave device.
The slave device would have to do something similiar, but with 2 outputs, to address the right LED's/segments.
Alternatively you could use shift-registers.
There actually are a lot of tutorials on this to be found on the web.
You should check out "Arduino multiplexing" or "Arduino led cube" tutorials.


text:
ESP8266 - server.write() doesn't work
I have a few Arduinos with ESPs, one of which is set up to measure temperature, and I'd like to have it send commands to other connected Arduinos to perform various functions (open/close valves, etc.)
In other words, the only communication I need is for one server to hopefully broadcast to a few clients. I don't really need to discern which client is which.
I am struggling to make sense of some of the documentation, and this is new to me.
For starters, I'm just trying to get any communication at all functional before I do the next parts.
My server device is set up as a soft access point and a WiFiServer.
My server ESP code looks something like this:
#include <ESP8266WiFi.h>

const byte ON = 2;
const byte OFF = 1;
int message;

WiFiServer server(80);

void setup()
{
  Serial.begin(9600);
  WiFi.softAP("access", "point");
  server.begin();
}

void loop()
{
  server.write(ON);
  delay(1000);
  server.write(OFF);
  delay(1000);
}

My client code looks something like this:
#include <ESP8266WiFi.h>

const byte ON = 2;
const byte OFF = 1;
byte ip[] = {192, 168, 4, 1};
WiFiClient client;
int message;

void setup() {
  Serial.begin(9600);
  // connect to wifi.
  WiFi.mode(WIFI_STA);
  WiFi.begin("access", "point");

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

  // Now connect to server object
  if (client.connect(ip, 80) == 1) {
    Serial.println("Connected");
  } else {
    Serial.println("Not Connected");
  }
  delay(10000);
}

void loop() {
  if (client.connected()) {
    Serial.println("Waiting for Data");
    while(!client.available()) {}
    String message = client.read();
    Serial.println(message);
  }
}

The client code does connect to the server, and gets stuck at the "Waiting for Data" line, never getting out of the while (!client.available) loop, so it clearly isn't receiving anything.
I'm sure I must look super dumb here, can someone help me understand the proper way to do what I want to do? Stuff I have seen online is primarily client -> server communication. Do I HAVE to ping the server with something in order to receive something back?

In esp8266 Arduino before version 3, write was not implemented in WiFiServer.
In version 3 WiFiServer doesn't have write, but class ArduinoWiFiServer implements the print-to-all-clients functionality.
Documentation link: https://arduino-esp8266.readthedocs.io/en/3.1.2/esp8266wifi/server-class.html
I am the author of ArduinoWiFiServer class.


text:
Switch case inside a switch case with serial input
I'm trying to build a test program for some hardware. Basically I want to select the piece of hardware with the outer switch case then select the test with the inner switch case. I'm trying to accomplish this by using serial input in the Arduino IDE monitor.
I can't make it work whatever I do. I either end up stuck in the outer switch case or I never enter the inner switch case where I want to select the test.
I've got a bit of code below:
char select_addon;
char select_test;

void setup() {
  Serial.begin(9600);
  Serial.println("(1) PB1");
  Serial.println("(2) PB2");
  Serial.println("(3) PB3");
}

void loop() {
  if (Serial.available() > 0) {
    select_addon = Serial.read();
    switch (select_addon) {
      case '1':
        Serial.println("Test");
        if (Serial.available() > 0 ) {
          select_test = Serial.read();
          switch (select_test) {
            case '4':
              Serial.println(" Test 1.1");
              break;
            case '5':
              Serial.println(" Test 1.2");
              break;
            case '6':
              Serial.println(" Test 1.3");
              break;
          }
        }
        break;
      case '2':
        Serial.println("TEST 2");
        break;
      case '3':
        Serial.println("TEST 3");
        break;
    }
  }
}

Obviously this isn't the finished code, but it's the switch case structure I've been trying to implement. Any suggestions on how I can enter the inner switch case?

switch on ardunio seems to want numbers. your chars might be being compared as char-codes. try something like   int select_addon = String(Serial.read()).toInt(); and case 3, instead  case '3'

What happens of the if (Serial.available() > 0) call fails?  That's the problem, because when there isn't anything available it's skipping the second switch statement.
On a point of style it actually might be better to implement the inner switch as a separate function. Imagine what your code will look like with 5 cases in the outer switch, each with 5 cases in the inner switches.
Also it might be worth, for debugging purposes, to always have a default statement, at least then you will know what key it was that you pressed.

At 9600 baud the data comes in a byte per millisecond. The inner Serial.available does not see the next byte yet. Three solutions: (A) add a delay of about 5ms as soon as the outer Serial.available sees data. This is a bad solution, dont' do it. (B) Use the Arduino 'parse' functions https://www.arduino.cc/en/Reference/ParseInt . (C) Describe the serial data en describe that a linefeed at the end is mandatory. Read the data in a buffer until the linefeed is read or until the buffer is full, and then process the buffer. This is the best solution.

Yeah, I was going to put the inner switch case into functions as soon as I got them to work.
Is there anything I can do to get the program to wait for another input once I've chosen the outer function? Lets say I type '1' in serial input, can I get it stuck somehow in that case and wait for 4,5 or 6? Because when I do select '1' all it does is print "Test" and goes back to the outer case.

As I said in the answer the cause of you problem is if (Serial.available() > 0), if there is data in the serial buffer then execute the inner switch otherwise (i.e. there is no data in the couple of ms since you pressed one) do nothing.  The problem is you aren't typing fast enough for you  code.  You need to press 4 within 1000th of a second of releasing 1.  OR you could change you if statement to while (Serial.available() < 1);

Oh I understand now, that actually makes perfect sense. Thanks bud.