text:
PID control arduino
I am hooking up an accelerometer to an arduino uno and running it through this pid controller. However the output isnt going to my setpoint. When i move the accelerometer back and forth the data goes to 255 or 0. Any ideas?
Datasheet for accelerometer:
https://www.sparkfun.com/datasheets/Components/SMD/adxl335.pdf
I get 336 for the x direction, which is the only direction i'm using, when its set flat on the table, which is my setpoint/desired output.
Note: Is the output the value away from the setpoint or the actual acceleration it calculates through the controller?
#include <PID_v1.h>

#define PIN_INPUT A0

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  //initialize the variables we're linked to
Serial.begin(9600); //Start a serial session
int  xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale
int setPoint = 336;
Setpoint = map(setPoint, 0, 1024, 0, 255); //Change read scale to analog out
//turn the PID on
myPID.SetMode(AUTOMATIC);
}

void loop()
{
int xdata = analogRead(PIN_INPUT);
Input = map(xdata, 0, 1024, 0, 255); //Change read scale to analog out scale

double gap = abs(Setpoint-Input); //distance away from setpoint
if (gap < 10)
{  //we're close to setpoint, use conservative tuning parameters
 myPID.SetTunings(consKp, consKi, consKd);
}
else
{
  //we're far from setpoint, use aggressive tuning parameters
  myPID.SetTunings(aggKp, aggKi, aggKd);
}

myPID.Compute();

Serial.print("Setpoint = ");
Serial.print(Setpoint);
Serial.print(" Input = ");
Serial.print(Input);
Serial.print(" Output = ");
Serial.print(Output);
Serial.print("\n");
// analogWrite(PIN_OUTPUT, Output);
}

OUTPUT:
Setpoint = 83.00 Input = 87.00 Output = 0.00
Setpoint = 83.00 Input = 81.00 Output = 0.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 68.00 Output = 255.00
Setpoint = 83.00 Input = 79.00 Output = 0.00
Setpoint = 83.00 Input = 91.00 Output = 0.00
Setpoint = 83.00 Input = 96.00 Output = 0.00
Setpoint = 83.00 Input = 99.00 Output = 0.00
Setpoint = 83.00 Input = 88.00 Output = 0.00
Setpoint = 83.00 Input = 68.00 Output = 0.00
Setpoint = 83.00 Input = 58.00 Output = 255.00
Setpoint = 83.00 Input = 64.00 Output = 255.00
Setpoint = 83.00 Input = 78.00 Output = 255.00
Setpoint = 83.00 Input = 95.00 Output = 0.00
Setpoint = 83.00 Input = 97.00 Output = 0.00
Setpoint = 83.00 Input = 95.00 Output = 0.00

(1) I don't see the make, model and link to datasheet of your sensor in your question. (2) I don't see a schematic. (There's a button on the editor toolbar.) (3) You haven't posted any voltage readings on the analog input to confirm that the accelerometer is working properly.

You appear to be slamming to the alternate output limits.  To investigate this type of problem, generally try reducing the gain, look at how the default sample interval means the calculation may only be performed on some loop iterations, and make sure you don't have any "all or nothing" integer vs. floating point conversions.  You may want to move the PID code into your sketch and add debug output to it.

Is the cycle time between reporting/looping mostly the time it takes to print each ~50char line at 9600 baud?  Is the input changing due to  just you wiggling the accelerometer?  Why use the map() rather than use the measurements and setpoints directly?  If you want to think in terms of '336' being level, you should use it drectle and scale your pid parameters to translate units of error into units of output.

Ensure that your period for the PID execution routine is reasonable for your system.  I generally like to execute my PID loops at 5 to 20 times the system impulse response.  For instance, with a motor, I will apply 100% power from a standstill and measure the time it takes to get up to 90% of final value.  I will then multiply that time by 0.1 and start there.  If it takes 1s, then I will start my PID loop executing every 0.1s.  Sometimes I adjust this up or down, depending on system requirements, but this is not a bad starting point.
If your PID loop is executing too fast, then it will respond too quickly to actually have a real-world effect on the system.  The output will tend to oscillate.  Motors vibrate and make more noise.... different systems respond differently, but you see the point.

Start at kp = 0,ki = 0, kd = 0
Increase kp until you get a reasonable response.  Don't expect your error to go to 0.  As long as you aren't oscillating, that should be good.
Very slowly increase kiuntil you are happy.
You should probably keep kd to 0.  It is for advanced usage and PI loops will meet the vast majority of application requirements.

This is a very crude guide.  There are better on google, but this should get you started.  PID loops are fun, especially with motors.  Enjoy!

If you find and study the code of the PID implementation (which should have been in or linked from the question) it already has a sense of sample interval, and simply does nothing if called before the next interval has elapsed.  So your first suggestion is basically already implemented, though the period may need consideration, and may be interacting oddly with the serial output.

Thanks for the catch, I am not familiar with the Arduino-flavor PID loop.  I'll edit the answer.


text:
ESP8266 UDP multicast doesn't receive packets
I am currently working on an ESP8266 with the Arduino IDE. I try to implement an ESP8266 in STA mode as multicast receiver. I was writing my code with the help of this documentation. Especially the following part:

The WiFiUDP class supports sending and receiving multicast packets on STA interface. When sending a multicast packet, replace udp.beginPacket(addr, port) with udp.beginPacketMulticast(addr, port, WiFi.localIP()). When listening to multicast packets, replace udp.begin(port) with udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port). You can use udp.destinationIP() to tell whether the packet received was sent to the multicast or unicast address.

Sending to the multicast group with udp.beginPacketMulticast(addr, port, WiFi.localIP()) and udp.write(message, messageLength)works flawlessly.
The receiving part of my code is as follows:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#define BUFFER_LENGTH 256

const char* ssid = "xxxxxx";
const char* password = "xxxxxx";

WiFiUDP Udp;
IPAddress multicastAddress(226,1,1,1);
unsigned int multicastPort = 4096;

char incomingPacket[BUFFER_LENGTH];

void setup(){
    WiFi.mode(WIFI_STA); //station
    WiFi.setOutputPower(0);
    while (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, password);
        delay(500);
    }
    Udp.beginMulticast(WiFi.localIP(), multicastAddress, multicastPort);
}

void loop(){
    int packetLength = Udp.parsePacket();
    if(packetLength){
        int len = Udp.read(incomingPacket, BUFFER_LENGTH);
        if (len > 0){
            incomingPacket[len] = 0;
            Serial.printf("%s\n", incomingPacket);
        }
    }
}

When sending a packet with a simple multicast sender (with matching IP and port), my multicast receiver on my linux laptop receives the packet, but the ESP8266 doesn't.
Maybe some of you have experienced a similar behavior and are able to give me some hints, where I might be wrong.
EDIT:
Since the time I asked this question I completely ruled out an error of the sender on the linux machine by using a verified, 100% working sender. The ESP8266 still doesn't receive any multicast datagramms.

Are the laptop and the ESP8266 on the same network? If not, you need to adjust TTL for the simple multicast sender. Default is 1.

yes they are both on my home WiFi

that still does not work and workaround above does not help. See also https://www.esp8266.com/viewtopic.php?f=8&t=15467

I recently had the same problem.
The unequivocal answer is that there is a power optimization (internal by Espressif) to save power, I guess, and it really creates havoc in the UDP Multicast receiving. Why? I have no idea. Same problem with the ESP32 and ESP8266.
Solution:
#include "user_interface.h"

and after:
WiFi.mode(WIFI_STA);
// the below instructions and now u will receive.
wifi_set_sleep_type(NONE_SLEEP_T); //LIGHT_SLEEP_T and MODE_SLEEP_T

Thank you very much for the answer. This is a really hard to find solution.

source: Stack Exchange

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

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

sort: votes


text:
Burn hex with optiLoader
Can optiLoader be used to burn custom hex?
For example, there's hex representation stored in optiLoader.ino in image_328, if that value is replaced with content of my pre-compiled hex, should that work right out of the box or some additional tweaking is needed?
EDIT
Discussion about the same topic on arduino forum as well.

ISP is for writing hex. bootloader or program or booth together. why do you want to use optiload? AVRISP sketch in IDE examples does it too.

The reason why I want to use it is because I want to try it without IDE, basically without computer. So I just want to write firmware on new blank IC by pressing a button from my proto board.
AVRISP in should work as well, but I feel like I will have to change much more code in order to make it to work without IDE, because it's using Serial to get data and pass it to target IC, right? ...and if optiLoader works as I thought above, then I can just simply replace HEX content with my.

ISP is not Serial. ISP uses SPI connection

It does but only to talk with target IC, but communication between programmer IC and IDE is done via serial.

@Juraj BTW I was referring to these methods getch and avrisp in that ArduinoISP sketch.

ok, I understand, you want to have the hex as part of the flashing sketch. but hex is more then twice larger then the binary representation of the program. you would be limited to a small program with hex. or you want to use SD card to store the hex?

Yes, that's correct, for now I would like to stick with small program with HEX. Later I want to move to SD card to store hex.

sure is, it is possible. the esp8266 AVRISP library does it with SPI connected AVR. the HEX is first received over WiFi there. try it with optiload. btw, WestfW is active on arduino.cc forum

Thanks @Juraj I will take a look at this one as well.

What do you really want to do? Burn a bootloader, or burn some useful code that does something? (A bootloader is just for uploading code)

hex is more then twice larger then the binary representation of the program - So? The .hex file stores each byte as readable hex, so the byte 0xAB is stored as "AB". However it only takes up one byte in the program memory.

Also see parse intel hex into SPI commands for arduino ICSP AVR

@NickGammon this looks amazing! So, basically in order to achieve what I mentioned above, in your sketch I would just need to replace this part ifstream sdin (fName); in readHexFile method, to read from hard-codded value, instead of using SD card as data source. Ofc, to remove the part related to display, sd card, etc. but this is how you are reading content of that HEX file, line by line?

@NickGammon, what was wrong on my statement about the size? the 'more' was for line endings

@Juraj - I didn't see why "you would be limited to a small program with hex". The hex digits in the .hex file are just an intermediate way of representing the same data. There is no limitation in size because you are reading from the .hex file.

@NickGammon, it was about in-memory hex. like the in-memory  bootloader hex in OptiLoader, Chris has it strong in the answer

Yes, it should work provided that your desired target image is stored in the same form, with correct metadata, and that it is small enough to fit in the programmer device.
The storage format of the payload-to-program could be made more optimal by a factor of almost two; however, for the original purpose of injecting compact Arduino-style bootloaders that is scarcely needed, and would have made preparing payloads more complicated.

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


text:
Chinese CH340 Arduino Uno - Burning stand allone chip
I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this CH340 UNO and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.
So what I tried was to use my FTDI cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.
So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.
As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...
UPDATE
Here's how my board look like:

Update 2:
OK, everything works great now! I just needed one pull-up resistor for reset pin.
Thanks everyone!

you also need to physically connect Reset (RST/DTR)

What is DTR I don't see that pin on my FTDI cable. So that is RTS pin from here ?
http://www.canadarobotix.com/serial-ttl/ftdi-cable-5v-vcc-3-3v-i-o

some FTDI breakouts/cables use RTS, others use DTR. Both ~kinda~ do the same thing: reset your MCU before uploading the sketch. (So the bootloader will know to expect something from the serial port). Note that some breakouts will need a 100nF cap in series with this connection, others wont.

Same thing, I'm still getting the same error.

How do you connect DTR or RTS?  Did you follow the full guide with pullup resistor and series capacitor?  When you switch from one serial device to another, you probably have to point the IDE at the new port, did you do that??  In theory you could use your CH340 board if you hold its onboard ATmega in reset.

I tried both scenarios but keep getting the same error. I put 100nF in series with RTS and Reset but nothing is changed. I don't have any resistor for reset... Do I need any? And yes I pointed in IDE to new port...and I also tried with all of these programmers.

I have updated my original question with my board image, please take a look.

What should be the value for that pull-up resistor?

Try Arduino ISP to flash standalone chip. Try to flash bootloader first as you didin't mention anything about it and bare chips are just empty.

I was able to successfully burn bootloader, I just had an issue with uploading sketch later, but that was my fault. I put pull-up resistor on wrong pin :) Everything is ok now.

No problem, I will accept it. :-)

authors: Илья Паймушкин


text:
Arduino OBD library and software serial library
Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?
This is the OBD library that I'm referring to.
And I'm using this Allpro OBD board.
Update
Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:
void getResponse(void){
 while(obdSerial.available()){
   Serial.write(obdSerial.read());
  }
}

Here I don't know when the message is received. And if I try to use example from Sparkfun obd-ii-uart-hookup-guide (different board doe) I ended up in infinite-loop since the board never return \r, if I send ELM command to use \n as terminator, and if I disable ELM to echo the command so that I use just one getResponse call I get some readings, but not all the time, I ended up in infinite-loop again.

What / where is an Arduino OBD library? What does its documentation say?

Sorry I have updated my question with links.

That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.
#ifndef OBDUART
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
#define OBDUART Serial
#else
#define OBDUART Serial1
#endif
#endif

You can edit the library's header file OBD.h to define your own serial port though:
#include <SoftwareSerial.h>
extern SoftwareSerial mySerialPort;
#define OBDUART mySerialPort

And then in your sketch create the mySerialPort SoftwareSerial object.

I have updated my question again, sorry :) I would really appreciate if you can take another look. But thanks for this one, this is also something that I needed.


text:
What is the sampling-rate of the `analogRead()`?
I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.
My code is very simple, here it is:
      // the setup routine runs once when you press reset:
  void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }

  // the loop routine runs over and over again forever:
  void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
  }

Roughly 9600 sampl/s, but the sampling rate will not be constant because of the timer interrupt. For an example on how to get a steady and controlled sampling rate on an AVR-based Arduino, see this example of configuring the ADC in free-running mode.

Thanks, will look into it after dinner. If it solves it, i'll get back to you and mark it as answer :)

BTW, could you please tag your question with the type of Arduino? It may make a difference. My comment above applies to most (if not all) AVR-based Arduinos, but not to ARM-based ones. Oh, and the Serial.println() will likely slow down the acquisition by a factor 50 or so once the Serial output buffer fills out.

Yeah, just realized that the serial.println does NOT print 9600 values/sec, This messes up my data. Basically what i want to do is do some tests on some different sounds i expose it to and then find those frequencies with fourier analysis.

Note that you can do other stuff while a conversion is taking place. The implementation of analogRead just wait/block until it's done. What I've done is some cases, is read the data from a previous conversion, start a new conversion, and process the data from the previous conversion , while the new conversion is running (in the background).

you should probably use an arduino due for this type of load(FFT). anyway, tomorrow I will take measures for your code with oscilloscope and report the results. (for uno and due).

The ADC in default configuration will take 104 µs to make a sample (which agrees with Edgar Bonet's comment of roughly 9600 per second).
You can speed that up somewhat by changing the ADC prescaler from the default of 128. See ADC conversion on the Arduino (analogRead). A prescaler of 32 will reduce that to 26 µs and still give quite acceptable results.
You can also run the ADC asynchronously (in the background) so you can transmit the previous result while obtaining the next one. A higher baud rate than 9600 baud would be highly recommended in this case.
People have been doing FFT analysis using the Arduino Uno and similar. I suggest you Google for relevant posts about that.

Yeah, i've done som reading now. The problem i currently have is that i know the rate at which the analogread is updated, the problem is that the serial.println does not print at nearly the same speed which gives me an unknown samplingrate of the data i've access to. Currently i'm considering buying a national instruments Data acquisition card. I've used them in uni and they suit my needs. Also, i can get the labview-software from school

@DakkVader: You can send the data to the computer in real time if you sample at 9600 S/s and send only the 8 most significant bits, in binary form (Serial.write()), at 115200 bps. Otherwise you could buffer the samples in RAM at whatever sampling rate you want and send them later, but this will limit you to short sampling runs.

Could you elaborate on this ? Basically i'd like to get whatever information analogread can get, at it's given sampling-rate. Serial.print won't give me at the true rate

I loaded this program on an arduino uno and measured with oscilloscope the time from the rising edge to the falling edge of the signal on pin13.
void setup() {

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

void loop() {
    PORTB = B00100000; //pin13 HIGH
    int sensorValue = analogRead(A0);
    PORTB = B00000000; //pin13 LOW
}

results:

time: 110.4 uS
  relevant freuency: 9.06 kHz

in case you are interested in fast analogRead with Due, I suggest you take a look at this.
The author stated that an analogRead with Due takes about 40uS and he also describes a couple of ways to make it much faster.

Your figure of 110 µs agrees pretty-much with my quoted 104 µs. The code in analogRead does more than just the read, so the other 6 µs would be setting up for the read, waiting for it to finish, and then storing the results. Also, there is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

I appreciate the verification via measurement.


text:
MPU6050 code explanation
I'm new to arduino and electronics. I've been trying to use the MPU6050 with my arduino but I'm having difficulty understanding the code. I'm referring to the code put up on the arduino website (http://playground.arduino.cc/Main/MPU-6050#short). Is there any way I could get a line by line explanation of the code?

.... link? ....

http://playground.arduino.cc/Main/MPU-6050#short

all my values are always zero, what mistake could I be making?

I've added in a bunch of comments for you:
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
void setup(){
  Wire.begin(); // initiate i2c system
  Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true); // done talking over to MPU device, for the moment
  Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
}
void loop(){ // main program loop
  Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // done talking to MPU for the time being
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  // all the fancy <<8| stuff is to bit shift the first 8 bits to
  // the left & combine it with the next 8 bits to form 16 bits
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  // the above lines have gathered Accellerometer values for X, Y, Z
  //  as well as Gyroscope values for X, Y, Z

  Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
}

Sure thing!  If this answer suits you, please remember to click the "answered" checkbox =)


text:
Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808
I wrote the code to produce the periodic signal by using arduino and DAC0808 where i turned on and off the respectively pins of PORTA by using a logic in iterative manner and created the periodic signal. But even without using delay logic, i couldn't get signal time period as comparable to 50 Hz voltage signal. And what i seek to get is to decrease the time period of generated signal. Pls note, blue signal is reference signal of 50Hz frequency.
float increment = 3.14159 / 500;
float initial = 0;
float value = 0;

void setup() {
  Serial.begin(115200);
  DDRA  = B11111111;
}

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

  PORTA = B00000000;
  while (1)
  {
    initial = initial + increment;
    value = sin(initial)  * 255;
    PORTA = abs(value);
  }

}

Your goal is to optimize the code to run faster? Start by using a look-up table instead of sin() and minimize float arithmetics. Are you sure your increment is correct?

You should make more clear what you expect to get and what you get instead.

Please edit question and indicate the timebase (seconds per division).  Also, if wiring diagram as shown is different than what you actually have, say so.  (The diagram apparently wires the bits backwards, LSB to MSB and vice versa.)

jwpat7 sir, blue signal is output signal of 50hz. So, time period per box is around 25 milli second.sorry for the inconvenience as am i operating from mobile.

As Vicente said, floating point math, especially transcendental functions, can be time-consuming. Instead of calculating the sine inside every repetition, you should build up a lookup table in your setup() function, then get the values from this table inside loop(). In order to minimise the size of the lookup table, note that you only need to calculate the sines of values from 0 to pi/2. If you still can not get your arduino to produce a 50Hz signal after that, consider decreasing the 'resolution' - that is, increasing the value of 'increment' from pi/500 to, say, pi/100.

As has been mentioned before, in comments and in jwpat7's answer, your
main problem here is the time taken to compute the sines. I already
provided a link to a faster fixed-point implementation of
sin() but, since you have an Mega2560 with loads of RAM, I
would go to the simpler look-up table method. I would not even bother
optimizing the size of the table.
For controlling the timing, you can use the canonical method described
in the Blink Without Delay Arduino tutorial, with one twist: times
should be measures with micros() instead of millis(). Here is a
first version of the program:
const float FREQUENCY = 50;            // hertz
const float PERIOD = 1e6 / FREQUENCY;  // microseconds
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

void setup()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;
}

void loop()
{
    uint16_t now = micros();
    static uint16_t last_sample;
    static size_t phase;

    if (now - last_sample > SAMPLE_TIME) {
        last_sample += SAMPLE_TIME;
        PORTA = wavetable[phase];
        phase = (phase + 1) % TABLE_SIZE;
    }
}

A few things worth noting:

The float constants FREQUENCY and PERIOD are used only at compile
time.
The table size is a power of two because wrapping a table index
modulo a power of two is way faster than modulo, say, 500: the
compiler optimizes the modulo into a bitwise AND.
The + 0.5 in the expression of SAMPLE_TIME is intended to ensure
that the result is rounded to the nearest integer. In this instance
it happens to be useless because rounding down would give the same
result.
The micros() function returns a 32-bit integer, but in this
application it is sufficient and faster to track only the 16 least
significant bits, hence the uint16_t timing variables. And no,
these variables overflowing is not a problem.

This should give you, in theory, a frequency of 50.08 Hz, i.e.
0.16% too fast. The discrepancy is due to SAMPLE_TIME, which should be
39.0625 µs, being rounded to 39 µs. You could fix this by
counting time with a higher resolution, but given the poor accuracy of
the ceramic resonator clocking the Arduino, this is probably not worth
the trouble.
A potentially worse problem is the large jitter you have with this
approach, on the order of 10 µs. This is due both to the time taken
to run through the loop and the occasional timer interrupt taking some
extra time. You can get rid of this jitter by using a timer interrupt
instead of micros(). Here is a second version of the program that uses
this approach:
#include <avr/sleep.h>

const float FREQUENCY = 50;              // hertz
const float PERIOD = F_CPU / FREQUENCY;  // CPU cycles
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

int main()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;

    // Configure Timer 1.
    OCR1A = SAMPLE_TIME - 1;  // set the period
    TIMSK1 = _BV(OCIE1A);     // enable TIMER1_COMPA interrupt
    TCCR1B = _BV(WGM12)       // CTC mode with TOP = OCR1A
           | _BV(CS10);       // clock at F_CPU / 1

    // Sleep while waiting for interrupts.
    sei();
    sleep_enable();
    for (;;) sleep_cpu();
}

// Service routine for the Timer 1 interrupt.
ISR(TIMER1_COMPA_vect)
{
    static size_t phase;

    PORTA = wavetable[phase];
    phase = (phase + 1) % TABLE_SIZE;
}

Again, a few notes:

The SAMPLE_TIME is now computed in CPU cycles and, since it is an
integer number of cycles (namely 625), there should in principle be
no frequency discrepancy.
For counting 625 cycles we need a 16-bit timer clocked at the full
CPU speed (prescaler = 1). We are using Timer 1 here. See the
datasheet of the ATmega2560, chapter 17, for details on
using the timer.
Sleeping between interrupts is needed in order to obtain
cycle-accurate timings. If we had simply an infinite loop, there
could be a few CPU cycles of jitter, which may not be a big deal.
Writing main() instead of setup() and loop() is a way to skip
the initialization normally done by the Arduino core library. In this
application that initialization is better avoided, because it creates
an extra jitter-inducing interrupt and it messes with Timer 1 in a
way that we would need to undo.

I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow.  At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a sin(), which probably is not enough to compute a 32-bit floating sin().
To speed it up, you can either issue fewer samples per cycle or make the loop go faster.
For the “fewer samples per cycle” approach, you would make increment bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.
For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both.  Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.
Note, after you speed up the code, you will need to set up a time base for issuing samples.  This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value.  Or you could spin until micros() exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.

320 clock cycles is indeed not enough for sin(): I have timed it at 1725.1 cycles average. I've also written a fixed-point sin() that takes 110.25 cycles (page in French, but code documented in English). It's 16 bits, with a maximum error of 9.53e-5, so somewhat overkill for this 8-bit application. But a simpler alternative polynomial is given in the text.

@EdgarBonet, thanks for mentioning that –  it provides a viable alternative to table lookup methods.


text:
Can I connect a camera to an arduino mini?
I was wondering if it was possible to connect a camera like this onto an Arduino mini and have the Arduino save video and audio to a micro SD card.

Not really (at least, not with any appreciable quality). Basically, the bandwidth involved is simply too much for the Arduino's relatively slow 16MHz core speed. You might be able to periodically capture greyscale lowres frames, but capturing the full 1280x960 resolution at any decent framerate is basically impossible.
If you want to find Arduino projects that involve capturing video like this, the search term is arduino composite video input. There are many projects out there that interface the Arduino with a composite input, but none that I know of that can capture full video. Consider the following: your Arduino runs at 16 MHz. If you were to handle 640x480 greyscale video (1 byte per pixel), that would be a data bandwidth (disregarding signal bandwidth) of 640*480*30 = 9216000 bytes/second. That's a pretty tall order: even if you could process each pixel in two (single cycle) instructions with no overhead, you still wouldn't have enough processor bandwidth.
If all you want to do is record composite video to an SD card, there are far easier options out there, search composite video recorder sd.


text:
Atmega2560 + weather station freezing
i made a weather station which is build on a ATmega2560 mini pro, Esp8266 module which communicate with atmega on serial1 which sends values to thingspeak, an TSL2561, 2.4 tft lcd, BMP180, DHT22 and a dust sensor module PMS5003 which is set on serial3 on mega2560.
I made the wiring, program etc. the weather station is working fine for some days when it freezes. The problem is that thingspeak reports that it receive some data every 6 mins like i set it but the data received is blank. Not 0, or any other value, just blank data.
I'm thinking it could be a problem with SRAM since it loses the values it reads. But why the loop is still working since it sends blank data to thingspeak ?
Atmega reads all values from sensors, then communicates with esp8266 by serial and using AT commands it sends the values read to thingspeak. So in my opinion it reads the values, but it won't stores them, then it sending blank data to thingspeak.
If i reset the arduino it works fine for some days when suddenly it decides to stop working.
After compiling the program the arduino ide is reporting this:
Sketch uses 28,890 bytes (11%) of program storage space. Maximum is 253,952 bytes.
Global variables use 1,800 bytes (21%) of dynamic memory, leaving 6,392 bytes for local variables. Maximum is 8,192 bytes.
So, my program it's not filling the SRAM.
I'm a beginner in C++ so i tried to do my best with programming.
Link to thingspeak weather station: https://thingspeak.com/channels/116912
The code:
#include <SFE_BMP180.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include "SWTFT.h" // Hardware-specific library

#define DHTPIN 25     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define ALTITUDE 320.0 // Altitude in Grasse

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

SWTFT tft;

DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
SFE_BMP180 pressure;

Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);

//double bmptemp; //temp bmp rectificata cu 1.9 grade -
float hum;  //Stores humidity value
float temp; //Stores temperature value
float lux; //Stores lux luminosity
char status; //used by bmp180
double T,P,p0; //p0 - sea-level compensated pressure in mb, T - temperature, P = absolute pressure in mb

#define IP "184.106.153.149" // thingspeak.com IP address; see their website for more detail
String GET = "GET /update?key=NWHWO6SLWNJP3HGQ"; // you channel will have unique code
int concentration=0;

//cod dust sensor
#define LENG 31   //0x42 + 31 bytes equal to 32 bytes
unsigned char buf[LENG];

int PM01Value=0;          //define PM1.0 value of the air detector module
int PM2_5Value=0;         //define PM2.5 value of the air detector module
int PM10Value=0;         //define PM10 value of the air detector module

void setup() {

  pinMode(17, OUTPUT); //pin pt esp - on /off
  pinMode(16, OUTPUT); //pin buzzer
  pinMode(31, OUTPUT); //pin on/off dust sensor

  Serial.begin(9600); // this is to start serial monitoring with your Arduino IDE Serial monitor.
  Serial1.begin(9600); // this is to start serial communication with the ESP via Software Serial.
  Serial3.begin(9600); //serial dust sensor

  Serial.println("Begin");
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);

  dht.begin();

  if (!pressure.begin()) {
    Serial.println("BMP180 init fail"); // Oops, something went wrong, this is usually a connection problem,
    while(1); // Pause forever.
    }

  if(!tsl.begin()) {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }
  //tsl.setGain(TSL2561_GAIN_1X);      /* No gain ... use in bright light to avoid sensor saturation */
  //tsl.setGain(TSL2561_GAIN_16X);     /* 16x gain ... use in low light to boost sensitivity */
  tsl.enableAutoRange(true);            /* Auto-gain ... switches automatically between 1x and 16x */
  tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);  /* 16-bit data but slowest conversions */

}

void loop() {
  digitalWrite(31, LOW);
  digitalWrite(17, LOW);
  Serial.println("-----------------------");
  dht22 ();
  bmp120 ();
  tsl2561();
  dust();
  Serial.println("-----------------------");

  tft.fillScreen(BLACK);
  tft.setRotation(1);
  tft.setCursor(0, 0);

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("DHT22");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(temp);
  tft.println(" C");
  tft.print("Humidite = ");
  tft.print(hum);
  tft.println(" %");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("BMP180");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(T);
  tft.println(" C");
  tft.print("Pression = ");
  tft.print(p0);
  tft.println(" mb");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("TSL2561");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Luminosite = ");
  tft.print(lux);
  tft.println(" Lux");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("Pollution aux particules");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  //tft.println("Concentration - ug/m3");
  tft.print("PM1.0: ");
  tft.print(PM01Value);
  tft.println(" ug/m3");
  tft.print("PM2.5: ");
  tft.print(PM2_5Value);
  tft.println(" ug/m3");
  tft.print("PM10: ");
  tft.print(PM10Value);
  tft.println(" ug/m3");
  //tft.println("Pcs/0.01cf");

  String tempdht22 = String(temp);// turn integer to string
  String humdht22 = String(hum);
  String tempbmp180 = String(T);
  String pressbmp180 = String(p0);
  String lum = String(lux);
  String pol01 = String(PM01Value);
  String pol25 = String(PM2_5Value);
  String pol10 = String(PM10Value);
  esp8266(tempdht22, humdht22, tempbmp180, pressbmp180, lum, pol01, pol25, pol10);
  Serial.println("Waiting..");
  delay(300000);

}

void dht22 () {
//Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.println(" % ");
    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.println(" C");
}

//cod pt dust sensor
void dust () {
  digitalWrite(31, HIGH);
  Serial.println("High Pms5003");
  delay(5000);
  for (int i=0; i <= 60; i++){
  if(Serial3.find(0x42)){    //start to read when detect 0x42
    Serial3.readBytes(buf,LENG);

    if(buf[0] == 0x4d){
      if(checkValue(buf,LENG)){
        PM01Value=transmitPM01(buf); //count PM1.0 value of the air detector module
        PM2_5Value=transmitPM2_5(buf);//count PM2.5 value of the air detector module
        PM10Value=transmitPM10(buf); //count PM10 value of the air detector module
      }
    }
  }

  Serial.print("PM1.0: ");
  Serial.print(PM01Value);
  Serial.println("  ug/m3");

  Serial.print("PM2.5: ");
  Serial.print(PM2_5Value);
  Serial.println("  ug/m3");

  Serial.print("PM10: ");
  Serial.print(PM10Value);
  Serial.println("  ug/m3");
  Serial.println();
  delay(1000);
  }
  delay(1000);
  Serial.println("Low Pms5003");
  digitalWrite(31, LOW);
}

char checkValue(unsigned char *thebuf, char leng)
{
  char receiveflag=0;
  int receiveSum=0;

  for(int i=0; i<(leng-2); i++){
  receiveSum=receiveSum+thebuf[i];
  }
  receiveSum=receiveSum + 0x42;

  if(receiveSum == ((thebuf[leng-2]<<8)+thebuf[leng-1]))  //check the serial data
  {
    receiveSum = 0;
    receiveflag = 1;
  }
  return receiveflag;
}

int transmitPM01(unsigned char *thebuf)
{
  int PM01Val;
  PM01Val=((thebuf[3]<<8) + thebuf[4]); //count PM1.0 value of the air detector module
  return PM01Val;
}

//transmit PM Value to PC
int transmitPM2_5(unsigned char *thebuf)
{
  int PM2_5Val;
  PM2_5Val=((thebuf[5]<<8) + thebuf[6]);//count PM2.5 value of the air detector module
  return PM2_5Val;
  }

//transmit PM Value to PC
int transmitPM10(unsigned char *thebuf)
{
  int PM10Val;
  PM10Val=((thebuf[7]<<8) + thebuf[8]); //count PM10 value of the air detector module
  return PM10Val;
} //cod dust sensor

void bmp120 () {
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:
    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Function returns 1 if successful, 0 if failure.

    status = pressure.getTemperature(T);
    if (status != 0)
    {
      // Print out the measurement:
      Serial.print("Temp2: ");
      Serial.print(T);
      Serial.println(" C ");

      // Start a pressure measurement:
      // The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
      // If request is successful, the number of ms to wait is returned.
      // If request is unsuccessful, 0 is returned.

      status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        // Retrieve the completed pressure measurement:
        // Note that the measurement is stored in the variable P.
        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.

        status = pressure.getPressure(P,T);
        if (status != 0)
        {

          // The pressure sensor returns abolute pressure, which varies with altitude.
          // To remove the effects of altitude, use the sealevel function and your current altitude.
          // This number is commonly used in weather reports.
          // Parameters: P = absolute pressure in mb, ALTITUDE = current altitude in m.
          // Result: p0 = sea-level compensated pressure in mb

          p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO)
          Serial.print("Pressure: ");
          Serial.print(p0);
          Serial.println(" mb");
        }
        else Serial.println("error retrieving pressure measurement\n");
      }
      else Serial.println("error starting pressure measurement\n");
    }
    else Serial.println("error retrieving temperature measurement\n");
  }
  else Serial.println("error starting temperature measurement\n");
}

void tsl2561 () {
  /* Get a new sensor event */
  sensors_event_t event;
  tsl.getEvent(&event);

  /* Display the results (light is measured in lux) */
  if (event.light)
  {
    Serial.print(event.light); Serial.println(" lux"); lux = event.light;
  }
  else
  {
    /* If event.light = 0 lux the sensor is probably saturated
       and no reliable data could be generated! */
    Serial.println("0 lux");
  }
}

void esp8266( String temp1, String humm, String temp2, String pression, String luminosite, String pol001, String pol025, String pol010) {
  //update value on thingspeak
  digitalWrite(17, HIGH);
  Serial.println("High ESP8266");
  delay(4000);
  Serial1.println("AT+RST"); // this resets the ESP8266.
  Serial.println("AT+RST"); // this is just echoing the command to your serial monitor so you can follow what is going on
  delay(2000);
  Serial1.println("AT");
  Serial.println("AT");
  delay(5000);
  if(Serial1.find("OK")){
      Serial.println("OK");
      Serial.println("Connected");
  }

  Serial.println("in the update loop");
  //ESP8266.println("AT+RST"); // it seems that mine works better if I reset it everytime before I do CIPSTART
  //Serial.println("AT+RST");
  //delay(5000);
  String cmd = "AT+CIPSTART=\"TCP\",\""; //standard code. see https://github.com/espressif/esp8266_at/wiki //
  cmd += IP; // += is concatenating the previous cmd string with the content of IP
  cmd += "\",80"; // same thing here it just keep adding stuff to the cmd string content
  Serial1.println(cmd);//type in the string in cmd into the ESP8266
  Serial.println(cmd);
  delay(1000);

  if(Serial1.find("Error")){
    Serial.println("AT+CIPSTART Error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
    return;
  }
  cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";
  Serial1.print("AT+CIPSEND=");
  Serial1.println(cmd.length());
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  delay(1000);
  if(Serial1.find(">")){ // if ESP8266 return the > prompt back from the CIPSEND command, you are set, if not something is wrong
    Serial1.print(cmd); //type in the GET command string and done
    Serial.print(">");
    Serial.println(cmd);
    Serial.println("OK Sent");
  }
  else
  {
   Serial.println("AT+CIPSEND error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
  }
  delay(1000);
  digitalWrite(17, LOW);
  Serial.println("Low ESP8266");
}

Here i uploaded the data file from thingspeak. You can see that until 2016-06-17 14:58:00 UTC it was working fine then thingspeak started receiving blank data. It received something but only blank data.
The weather station is in another location so i don't have acces all time to reset it.
http://www.filedropper.com/feeds8
[Shown below are some lines from the front, the transition point, and the end of the feeds (8).csv file at Andrei's filedropper link. – jw]
created_at,entry_id,field1,field2,field3,field4,field5,field6,field7,field8
2016-06-16 05:50:45 UTC,1,19.10,92.70,20.80,1003.02,1512.00,8,15,15
2016-06-16 05:55:07 UTC,2,19.00,94.00,20.91,1003.09,1659.00,41,54,61
2016-06-16 06:01:32 UTC,3,19.10,92.70,20.98,1003.11,2233.00,6,7,12
2016-06-16 06:07:57 UTC,4,19.00,92.90,21.16,1003.11,2620.00,6,7,11
2016-06-16 06:14:22 UTC,5,19.10,92.70,21.19,1002.97,2701.00,6,6,12
2016-06-16 06:20:48 UTC,6,19.10,92.20,21.44,1002.97,2973.00,220,291,327
2016-06-16 06:27:13 UTC,7,19.30,92.20,21.47,1002.99,3197.00,5,6,7
...
2016-06-17 14:19:30 UTC,305,22.70,50.50,23.43,1013.88,1956.00,1,1,1
2016-06-17 14:25:55 UTC,306,22.60,51.20,23.27,1013.88,1979.00,1,1,1
2016-06-17 14:32:20 UTC,307,22.70,50.10,23.18,1014.00,1962.00,1,1,1
2016-06-17 14:38:45 UTC,308,22.70,49.50,23.17,1014.03,1967.00,1,1,1
2016-06-17 14:45:10 UTC,309,22.50,50.90,23.55,1014.01,1856.00,2,2,2
2016-06-17 14:51:35 UTC,310,22.60,51.80,23.62,1013.99,1870.00,1,1,1
2016-06-17 14:58:00 UTC,311,22.60,50.80,23.21,1013.94,1987.00,1,2,2
2016-06-17 15:04:26 UTC,312,"",,,,,,,
2016-06-17 15:10:51 UTC,313,"",,,,,,,
2016-06-17 15:17:16 UTC,314,"",,,,,,,
2016-06-17 15:23:41 UTC,315,"",,,,,,,
2016-06-17 15:30:06 UTC,316,"",,,,,,,
2016-06-17 15:36:31 UTC,317,"",,,,,,,
2016-06-17 15:42:56 UTC,318,"",,,,,,,
...
2016-06-17 22:59:18 UTC,386,"",,,,,,,
2016-06-17 23:05:43 UTC,387,"",,,,,,,
2016-06-17 23:12:08 UTC,388,"",,,,,,,
2016-06-17 23:18:33 UTC,389,"",,,,,,,
2016-06-17 23:24:58 UTC,390,"",,,,,,,
2016-06-17 23:31:23 UTC,391,"",,,,,,,
2016-06-17 23:37:48 UTC,392,"",,,,,,,
2016-06-17 23:44:13 UTC,393,"",,,,,,,

I went and saw the station, it's more like an electrical problem imo because if i reset arduino nothing happens. The data readed by arduino on dht22 is nan and the rest of the sensors is working fine. The only way i could make dht22 reading again is to unplug the power and plug it back. So that's why i think it's more an electrical problem but can't figure why dht22 stops responding and need to switch off all power to bring it back to life. I will try putting an capacitor on wires to dht22 to see if it's better.

Please edit your question and add examples of output from when it is working, and from when it isn't.   Your statement that “the data received is blank” is ambiguous.  Do you mean the whole transmission, or just the data fields; and by blank, do you mean "not there" or "blank characters"?  To avoid that ambiguity, please edit your question and add examples of output from when it is working, and from when it isn't.

I edited some of those lines into the question.  The link to filedropper seems cumbersome to use.  ¶  What I'd like to see, instead of data as processed by  thingspeak, is what was sent to thingspeak.  Ie, what the Arduino is sending, not what thingspeak extracted from that input.  I imagine field names are missing (in the http GET request) as well as data

You may have a power problem, but with all those libraries, I would also suspect memory issues with String.  The percentages reported by the IDE do not show actual String memory usage, just the declared variables and double-quoted string constants, like "BMP180 init fail".
I think those humidity sensors have a heating cycle, so maybe they're causing a power sag, or maybe the sketch has run amok and is constantly requesting conversions.
Regardless, instead of building a String to be printed all at once, just print the pieces.  That is, instead of this:
String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial1.println(cmd);

...do this:
Serial1.println( F("AT+CIPSTART=\"TCP\",\"") );
Serial1.print( IP );
Serial1.print( F("\",80") );

This saves copying bytes into buffers, reallocating Strings, copying them to the output buffer... yuck.
The F("x bytes") macro also saves x bytes of RAM each time you use it on a double-quoted string constant!
And this:
cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";

OMG.  Use separate Serial1.print statements and F() macros.  However, because you have to send the command length first to the ESP8266, don't pass them in as Strings, pass them as ints or floats, and add up the individual string lengths.
There are several ways to do this, depending on the old RAM-vs-speed tradeoff.  Here's a minimal RAM approach:
  //  Pass in values, not Strings
  esp8266( temp, hum, T, p0, lux, PM01Value, PM2_5Value, PM10Value );
}
    ...

void esp8266( float temp1, float humm, float temp2, float pression, float luminosite, int pol001, int pol025, int pol010 )
{
    ...

  //  Start with the fixed-length string constants:
  //     GET + 8 * "&field#" + line termination
  size_t cmdLength = strlen(GET) + 8 * 8 + 4;

  //  Convert each value to a char array to see how big each one is...
  char buf[16]; // to hold temporary "char strings"

  unsigned char decimalPlaces = 2;
  dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);
     ...
  itoa( pol10, buf, 10 );  // value, char *, base
  cmdLength += strlen(buf);

  //  Now we know the total length
  Serial1.print("AT+CIPSEND=");
  Serial1.println( cmdLength ); //  <-- calculated!
  delay(1000);

  if (Serial1.find(">")) {

    // send all the same pieces of the GET command
    Serial1.print( GET );

    Serial1.print( F("&field1=") );
    dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field2=") );
    dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field3=") );
    dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );
        ...
    itoa( pol010, buf, 10 );  // value, char *, base
    Serial1.print( buf );

    Serial1.print( F("\r\n\r\n") );

NOTE: It is important that you use the same technique to calculate the length of one piece and to print that piece.  Here, the same dtostrf call with the same decimalPlaces is used for each piece.  Ditto for itoa.
The speed penalty is that you convert each parameter twice, but this is probably still quicker than all the alloc/realloc/delete/copy that String was doing.
The RAM advantage is that you are using only 16 bytes for buf instead of hundreds of bytes on the heap (that's where String actually stores its characters).
The program space advantage is about 1600 bytes for not using the String library.
I hope you now see that the apparent "convenience" of using the String class has real costs in speed, RAM and program size.  String also affects the long-term stability of your program: you get weird crashes, hangs or string values.

Thank you very much for your reply. I am a beginner in C programming, i started learning C about some months ago, so i will try to understand what you told me about optimising the program and then applying to my project, because honestly now i don't understand them :) I did a research on google and saw that others are having problems with DHT22 sensor that stops working and need to replug it on power to works.
When i saw the weather station today like i told all the sensors was running except the dht22 which replied as nan.Since nan is not an int value thingspeak is not accepting transmission

The dht22 is doesn't have a heating time so i could attach the vcc pin of dht22 to an arduino pin and activate it when i need to read the temperature.
The library is made like this when dht22 is not responding it give a value of nan. I could modify the library to give a value of 50 degrees for example but this is not a solution to my problem.
If you have any other comments regarding my program feel free to help me :) Thank you !


text:
Arduino crashing and rebooting
I have recently written a program which is supposed to change the duty-cycle to keep the feedback voltage measured on A0, A1 constant. The problem is that the Arduino will start crashing at pretty constant intervals if it approaches it's target current. Once it crashes I have confirmed that it restarts the program (but crashes again in a moment).
Here's a sample of the serial output during the crash:
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 236.00
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.96
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.92
Current A: 64   Current B: 67   PWM A: 175.00   PWM B: 235.88
Current A: 64   Current B: 66   PWM A: 250.00   PWM B: 285114740000000000000000000.00
Current A: 0    Current B: 0    PWM A: 1.30     PWM B: 0.00
Current A: 0    Current B: 0    PWM A: 2.60     PWM B: 1.30
Current A: 0    Current B: 0    PWM A: 3.90     PWM B: 2.60
Current A: 0    Current B: 0    PWM A: 5.20     PWM B: 3.90

And here is all of my code:
#include <MemoryFree.h>

//Program to run on the Vegetarium
//Written by Leon Teichroeb on 12/6/2016

//Hardware description:
//-Oscillator 2A and 2B for the two onboard driver circuits
//-Pin 13 is attached to the "heartbeat" LED
//-Channel A (3) and B (11) current measurements on A0 and A1

//Functionality:
//-Drive Channels at set current

float PWMA = 0;
float PWMB = 0;

int TARGETA = 65;
int TARGETB = 65;

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

  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS20);
  OCR2A = (int)PWMA;
  OCR2B = (int)PWMB;
  digitalWrite(3, LOW);
  digitalWrite(11, LOW);

  delay(5000);
}

void loop() {
  int CURRENTA = analogRead(A0) / 4;

  if(CURRENTA < TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA > 250) {
      PWMA = 250;
    }
  }
  if(CURRENTA > TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA < 5) {
      PWMA = 5;
    }
  }

  int CURRENTB = analogRead(A1) / 4;

  Serial.println("Current A: " + (String)CURRENTA + "\t" + "Current B: " + (String)CURRENTB + "\t" + "PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.println("PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.print("freeMemory()=");
  //Serial.println(freeMemory());

  if(CURRENTB < TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB > 250) {
      PWMB = 250;
    }
  }
  if(CURRENTB > TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB < 5) {
      PWMB = 5;
    }
  }

  if(PWMA < 10) {
    digitalWrite(3, LOW);
  } else {
    analogWrite(3, (int)PWMA);
  }
  if(PWMB < 10) {
    digitalWrite(11, LOW);
  } else {
    analogWrite(11, (int)PWMB);
  }

  delay(40);
}

My circuit also provides power for the Arduino through a simple 7815 voltage regulator. The analog input does not exceed a few volts, and the PWM outputs are driving two logic level MOSFETs. If more information on the circuit is necessary please let me know!
EDIT: I have found out that it isn't a bug in the two feedback loops, because both work on their own. It crashes as soon as I use both feedback loops together. As far as I'm aware, there are no shared variables or data between them

I can't see anything horribly wrong with your code. Maybe a memory issue. Did you try printing without Strings? Like: Serial.print("Current A: "); Serial.print(CURRENTA); .... It's cumbersome but memory friendly.

I can definitely give it a try, but I actually wrote the serial code to debug this problem specifically. I also suspected memory issues, but with MemoryFree.h I found that I still have >1500 bytes free and no leaks

The 285114740000000000000000000 is kind of odd.  Also, PWM B: 0.00 seems to be impossible with the code above. Very odd. (Did you add some capacitors to the output of the 7805?)

The 0.0 PWM signal is possible because it is only limited to 5.0 if it is lowering the duty-cycle. Also, I have a 0.1uF capacitor on the output of the 7805 even though it's powered with a lab bench power supply

Target current or target voltage?

I finally figured it out, the Arduino was entering a current protection mode causing it to reset. The pins driving the MOSFETs were pulling too much current once the regulation started because of the BUZ11's input capacitance.
To fix the problem I just had to add 120 ohm resistors in series with the gate. This made the activation and deactation slower resulting in less current flow.

are u telling u have added 120 ohm resistor in series with ic 7815 i am having same prob. please tell is this sol. will work

What's a BUZ11, a MOSFET? So the gate input capacitance on the MOSFET was exceeding the current limits on the logic lines? Or are you talking about the power draw of the MOSFET? Can you provide a wiring diagram? It's hard to understand what you're saying.


text:
ESP8266 disconnects after few hours
My system looks like this:
ESP8266 is connected to Arduino Uno (2, 3 pins) and a relay's data input to Arduino's pin 12 and power for relay is provided from another source.
Arduino gets data from server and switches on/off relay according to that signal. This system works perfectly for few hours and then suddenly crashes. In my WiFi console I have:

wlan0: STA 2c:3a:e8:4e:bf:70 WPA: pairwise key handshake completed
  (RSN) wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0:
  AP-STA-DISCONNECTED 2c:3a:e8:4e:bf:70 wlan0: STA 2c:3a:e8:4e:bf:70
  IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11:
  associated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated
  wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA
  2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: AP-STA-CONNECTED
  2c:3a:e8:4e:bf:70

I have read this Arduino question, but circuit diagram similar to that one. I get power from my PC to run Arduino.
This is my Arduino code :
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds
int testLED = 12;
// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

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

  Serial.println("You're connected to the network");

  //printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    //code to run relay
    if (c == '#')
    {
      while (client.available() == 0) { } // Do nothing while we wait for the next value

      // reading the second charactor
      c = client.read();
      if (c == '1') {
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(600000);
      }
      else if (c == '0') {
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(600000);
      } //end of C cheking if-else
    }  //end of first charactor # if
    //end of replay code
  }
  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /simple.txt HTTP/1.1"));
    client.println(F("Host: localhost"));
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    WiFi.begin(ssid, pass);
    Serial.println("Reconnecting again");
  }
}

this does not describe how you are powering the arduino ... I get power from my PC to run Arduino.

After quite long research I found the solution for my problem.
I did some changed power connection to ESP-8266.
ESP 8266    ---------  Arduino Uno
Vcc       --------->  3.3v
CH_PD     --------->  5v divided into 3.3v using resistors
RX        --------->  PIN-2 via 3.3v regulator.
After this configuration, my system was working perfectly for days. Thanks for the all suggestions given.

powering CH_PD from 5V did the trick. I suspect it powers the WiFi part

@Juraj sorry, what do you mean? directly connect 5v to ESP's CH_PD port?

no no, the regulator is ok. 3.3 V pin on Uno can provide only 50mA. normal is connecting Vcc and CH_PD together but the 3.3 V is not strong enough to power esp8266. I wonder that powering only CH_PD from stronger source helped.

@Juraj I tried to connect external voltage to Vcc, but it didn't work.

I looked up the docs. Your esp8266 is now stable because the CH_PD (chip enable) pin has stable power not affected by power drops caused by WiFi. a stronger power supply would by a better solution

As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.

solder capacitors to Arduino board? can you explain it ?

@Sachith http://www.instructables.com/id/NRF24L01-Fixing-Connection-Issues/

you need 100-200mah for the arduino - 100 milliamp-hours? You mean 100-200mA don't you?

OP uses WiFiEsp library in Uno with AT firmware in esp8266

@Coder_fox An Ampere is a unit of measurement on its own. That's like saying kilograms are measured in kilogram-hours.

Amp-hours are for things like batteries. A 40Ah battery might produce one amp for 40 hours, or 2 amps for 20 hours, and so on.

@Sachith, are you here? You offered a bounty. It will go to Coder_fox. Did this answer help? If yes accept it, if not, give feedback

@Juraj No, that didn't slove my problem. I posted my answer below.

After four months of searching - Just use 3.3 V with 1.5 or 2 A and everything will work correctly.

can you suggest full answer?


text:
Wemos D1 doesnt drive Relay
I recently bought a Wemos D1 board and tried to connect a relay and test its connection.
I got an example server from here and executed. I connected D5 to a Relay's data and 5v and GND from Wemos board.
But this does not change the state of relay, it always remains high. I connected a LED for D5, it works perfectly with client's response.
Then I powered relay using an external 5v and ground connection, but the same result.
I have checked for possible solution, but coulnt find an answer.
The relay I am using is this one

Normally it is because people work under the misconception that D5 in the code is D5 on the board, but using the LED means you are using the right port in the code and hardware, so have you looked at it the board can supply enough current to trigger the relay (it only outputs <20mA).

Sounds like the pin cannot provide enough current to drive the relais. Try to use a transistor or MOSFET for it

@chrisl can you provide me an example? I am not good with electronic stuffs. Thanks for the comment.

You may need a BJT transistor to amplify the current. Look at https://electronics.stackexchange.com/questions/220492/safely-pull-5v-to-gnd-on-3-3v-gpio. Do you use a bare-bones relay or a relay board? Which one exactly?

you have a relay module? add a link to it

@chrisl if the relay has separate power and signal pins, I would think that it is a relay module with supporting circuit

Please give a link to the exact relay you are using.

Many of the cheap 5v relay modules i've gotten don't work because the D1 runs on 3.3v, so it's high is not enough to trigger the relay. fwiw, every dual-relay module i've gotten works on 3.3v boards, but there's not reason on paper why that should be the case, it just happens to be true; maybe they use better driving electronics in the dual modules...

the relay you linked has no digital pin. how did you wire it?

The board which you are using is operating on 3v3. Even if you try to run the relay using the D5 or any other pin on the board, you may not be able to run it successfully at all times. In this case, you can go for either MOSFETs or Pull-up resistors so that you can hold the voltage to 5V for triggering the relay. I would personally suggest to go for a PNP type.
As requested by Sachith, here is the circuit suggested for the problem stated. Just note that the voltage source should be +5 V (which is +1 V in the schematic). Also, the MOSFET is not the specific one, it is just for the schematic purpose.

simulate this circuit – Schematic created using CircuitLab

I would expect that a 5 V TTL senses 3.3 V as HIGH. I think he has some other problem.

@Juraj: your expectations are too high for fleabay modules; i have several single-relay boards that work perfect at 5v, but spotty or not at all on 3.3v...

@dandavis, with 5 V power supply  and 3.3 V signal?

@Juraj: yes, with 5v in from usb, 3.3v i/o on ESP, many are sporadic at best

but patching the module's on-board TTL circuit with external MOSFET?  is it a good answer? if I would want to care about electronics details, the I would take a plain relay

@Juraj I understand that it feels awkward to have a TTL with external MOSFET, but the best solution could be possible only when we would be clear with the actual scenario. So, Sachith please let us know which relay you are actually trying in your case. If possible, share a link of the same.

@SumitPanse I have updated the relay I am using.

Okay @Sachith. I saw that update just now. I would need a little time to check and revert back on it.

@Sachith, how did you wire it?

@Juraj https://www.amazon.ca/Indicator-Light-Channel-Module-Arduino/dp/B00P7QDJD2

@SumitPanse Can you give an example of the circuit I need to implement? I do not have a good electronic knowledge.

so, this is a module. it needs 5 V VCC and not specified signal level, where 3.3 V doesn't work. buy one which accepts 3.3 V as HIGH

@Sachith I have updated and modified my answer with the circuit you have requested. Please check it let me know whether it is clear to you or not.

@SumitPanse thanks for the updated answer.  So I should use P1 = D5 and 5v supply to J310 MOSFET.

@Sachith I have taken J310 just for reference. But yes, other connections can be done as per the schematic.

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


text:
Two power source for Arduino and a relay
In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.
If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)
If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

The uno can't provide enough power to power an ESP8266 reliably.  I suggest you power it from a separate source.
When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them.  Otherwise the circuits don't use the same definition of zero.

Use  a relay driver IC like ULN2003 to drive relay.
Here is a sample circuit diagram :


text:
Which Protocol to use to control WiFi (ESP8266) enabled Led Light
I am developing a Wifi based Led light (Got Inspired from Philips hue, Lifx). I have little knowledge about web server, clients, Web protocols. I will be using ESP8266 as Controller cum WiFi module.
There are two ways to control Led light over WiFi.

Locally
Remotely

Android/iOS app will be handling all the control part.
Which protocols can I use to control Led light, locally? HTTP or Websockets?

Note :- The speed is critical, android/iOS app can send around 50-60 values per second.

Also, which protocol should I go with if Led light is controlled Remotely.? So far, MQTT seems reliable. Any suggestion?
Kindly help!

why not use a single protocol for both local and remote - far simpler code - MQTT should suffice

What if internet is not working, in that case as well, Local transmission of data will not happen, because MQTT works over Internet. I should have the option of controlling it locally.

MQTT works over a network, doesn't have to be "the internet" if you have a local MQTT server

But I see what you mean. My setup is more flexible because all my IOT servers are within my LAN - still externally accessible, but all under my control and I have a router that loops back requests for external IP from within the LAN ... so, it just works with one single domain, I don't have to do anything different for external vs internal access

UDP :D
Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.
This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.
MQTT is nice, but it doesn't work well for 60hz updates, I Tried :D
It resulted in un-smooth animation, and frames out of order.


text:
Code Optimisation
I have tried fading the RGB Led with different colour format and sequence.
Working of Code :-

When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
When value of number is 2, the Green LED works as above.
The change of state from Red to green takes 4 seconds.

Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.
Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.
int RED_LED = 12;           // the PWM pin the LED is attached to
int BLUE_LED = 14;
int GREEN_LED = 15;

int RedLedBrightness = 0;    // how bright the LED is
int GreenLedBrightness = 0;    // how bright the LED is

int RedFadeAmount = 5;
int GreenFadeAmount = 5;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

int j = 0;

void setup()
{
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200)
}

void loop()
{
    if (millis() - previousMillis2 >= interval2)
    {
     previousMillis2 = millis();

    j += 1;
    if (j > 2)
    {
        j = 1;
    }
    Serial.print("\n");
    Serial.println(j);
   }
    SpecialFunction(j);
}

void SpecialFunction(int Number)
{
  if (millis() - previousMillis >= interval)
  {
    previousMillis = millis();

    if (Number == 1)
    {
      RedGradualChange();
    }

    else if (Number == 2)
    {
      GreenGradualChange();
    }
  }
}

void RedGradualChange(void)
{
  analogWrite(GREEN_LED, 0);

  GreenLedBrightness = 0;    // how bright the LED
  GreenFadeAmount = 5;

  analogWrite(RED_LED, RedLedBrightness);
  RedLedBrightness = RedLedBrightness + RedFadeAmount;

  if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
  {
    RedFadeAmount = -RedFadeAmount;
  }
}

void GreenGradualChange(void)
{
  analogWrite(RED_LED, 0);

  RedLedBrightness = 0;
  RedFadeAmount = 5;

  analogWrite(GREEN_LED, GreenLedBrightness);
  GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;

  if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
  {
    GreenFadeAmount = -GreenFadeAmount;
  }
}

Perhaps if you were to write out, in plain English, what you want your program to achieve it may help.

@Majenko Please review my question again and my code as well,

I have updated my answer.

How can I improve the code - this is not a reasonable question for this site. It is too broad. With all due respect to Majenko who is trying to help you, this is a very broad question. Plus, you keep editing the code so that answers don't make any sense. Please read How do I ask a good question?.

Without deciphering what all those functions are supposed to do, I can see a few fundamental flaws and inefficiencies:

Don't use string - especially if you're only then using it to convert into a char array. Just use the char array.
You're storing a number in a char array then comparing it to string constants. What is wrong with dealing with just numbers in the first place...?
This bit is wrong: if (incomingByte = '#') - you have an assignment (=) instead of a comparison (==) so it will always be true.
If you fix point 3 the rest of the code won't work, since your string will now always have # at the end (3# for instance) and the comparison against 3 (for example) will fail.

You should learn more about how to input values through serial:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

For your fading code there is a lot of redundancy in there. Personally I would use a bitfield indicating which LEDs are to fade and which aren't.
Basically you have a single value and OR together bits within it to indicate the enabled LEDs.  For instance, assign the value 1 to red, 2 to green and 4 to blue. These correspond to 0b001, 0b010 and 0b100 respectively.
When the state is changed, either by your loop or by an external serial signal, you reset all three colour brightnesses to 0 (to keep them synchronised) and set the right bits in the bitfield for the colours you want fading. For instance, for red you set the bitfield to 1. For cyan you set it to 6 (0b110).  Then in your processing loop you just fade the colours that are enabled, and write all three values (the colour that isn't enabled will already be 0).  This also has a side-effect that you now already have numbers assigned to the colours:
0 = 0b000 = All off
1 = 0b001 = Red
2 = 0b010 = Green
3 = 0b011 = Yellow
4 = 0b100 = Blue
5 = 0b101 = Magenta
6 = 0b110 = Cyan
7 = 0b111 = White

In fact, since all the colours are fading together, you don't even need separate values for each colour - just one global brightness value.
Some code (untested) for you:
#define RED   0b001
#define GREEN 0b010
#define BLUE  0b100

int brightness = 0;
uint8_t enabled = 1;
int fadeAmount = 5;

const uint8_t RED_LED = 12;
const uint8_t BLUE_LED = 14;
const uint8_t GREEN_LED = 15;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

void setup() {
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200);
}

void loop()
{
    if (millis() - previousMillis2 >= interval2) {
        previousMillis2 = millis();
        enabled ++;
        if (enabled >= 8) enabled = 1;
        Serial.println(enabled);
    }

    if (millis() - previousMillis >= interval) {
        previousMillis = millis();
        if (enabled & RED) {
            analogWrite(RED_LED, brightness);
        } else {
            analogWrite(RED_LED, 0);
        }
        if (enabled & GREEN) {
            analogWrite(GREEN_LED, brightness);
        } else {
            analogWrite(GREEN_LED, 0);
        }
        if (enabled & BLUE) {
            analogWrite(BLUE_LED, brightness);
        } else {
            analogWrite(BLUE_LED, 0);
        }
        brightness += fadeAmount;
        if (brightness > 1023) {
            brightness = 1023;
            fadeAmount = -fadeAmount;
        } else if (brightness < 0) {
            brightness = 0;
            fadeAmount = -fadeAmount;
        }
    }
}

I removed the serial part and I just want you to focus on rest of the code, which is necessary. I now used a loop to fill values into j after every 4 seconds.


text:
Scan IP address of ESP8266
I am working on a project in which, the mobile app/browser sends HTTP command to ESP8266 in AP mode. The default IP address of ESP is 192.168.4.1. Therefore in order to connect the ESP to WiFi, the command goes like this :- 192.168.4.1/SSID=XYZ/Pass=XYZ.
On connecting to router, the ESP goes into STA mode and Doesn't create AP until WiFi is not found to which it was connected earlier. Now when ESP is connected to router, the router assigns the IP to ESP through which HTTP command will be sent. On Serial monitor, it does show the IP address to which it is assigned, but what if app controls the ESP, there is no serial communication. How will app know the IP address assigned to particular ESP8266? Is there any way app can scan the router? Or any other way to do this? If there are multiple ESP connected to router, how can I identify the IP of particular ESP.

Other than mDNS?

The de-facto standard way for devices to broadcast their IP address to clients is through the Multicast DNS system (mDNS). In this system the server sends a UDP message to a specific multicast group address and clients listen for it so they can work out what is where.
mDNS is also known as Zeroconf or Bonjour depending on who you talk to.
The ESP8266 Arduino core (if you are programming the ESP8266 directly) has mDNS examples with it. If you are using the AT command interface instead, then you will need to read the manual to find how to send UDP packets to multicast addresses.

Is it different from Multicast UDP by any chance?

mDNS uses multicast UDP.

Have the app send a broadcast UDP packet, and have the ESP listen for such  broadcasts. Now the ESP knows the IP address of the device on which the app is running, and it can somehow let it know its own IP address: perhaps connecting to a particular socket on which the app will listen, or sending a UDP broadcast of its own.

You can hard-code the required IP address for ESP8266. (That may not be possible all the times).
There's a sample code :https://www.arduino.cc/en/Reference/WiFiConfig
If you are not hard-coding IP address, you can read IP address of ESP by using WiFi.localIP() function in Arduino.

Please read question carefully before answering.

The hardcoded IP can conflict with existing devices connected to router with same IP.

The app has no way to know the the IP of devices, even after using the WiFi.localIP(). This can only be useful in serial.

You can use sockets

I know that, but question is different. Kindly do not provide vague answers.

Regarding mDNS is the solution but unfortunately it has limitation just like currently not supported with Android Platform.
My Suggestion is to keep listen the UDP port on all range of IP address of network as of token and on when you found right reply of UPD packet along with that device IP/MAC/port inside of that replayed packet then you will good to go.
No doubt this will take bit time to done but its only one time or until the IP has been changed.


text:
ESP8266 Upload hex file Arduino IDE
I am using ESP12E Wifi module, using library based on Arduino. Is there any way I can upload hex file of the project to esp8266 using Arduino or any tool?
I need to send hex file instead of code to my client. Is there any way?

Hex file of what?  A program built for the ESP8266, or a program built for a classic ATmega Arduino talking to it?  Either way, while you may be able to obtain a hex file, you probably can't upload it with the IDE without various hacks, but would need to use avrdude (for an ATmega) or some other tool (for an esp8266) directly.

Hex file of the code compiled in Arduino for esp8266

Hex file or binary file? Why can't you just use the Arduino IDE?  Esptool (https://github.com/themadinventor/esptool) should do what you want though, but finding out the correct arguments might take some effort.

I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."
The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.
When you build your sketch, there is a .hex file created that you can send to your client.
There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:
Sketch > Export Compiled Binary
The sketch will compile.
Sketch > Show Sketch Folder
The .hex file will be in the sketch folder.
You can send this hex file to your customer.
If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support import of hex files at this time.
Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.
If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.

Turn on Show verbose output during compilation in your Arduino IDE and press Verify. After compile you can examine the parameters sent to esptool.exe in the last line before Sketch uses.... You will see some .elf, .bin and .text files. These are the files you want to send.


text:
motor does not move without Serial.println
having strange behavior with motor shield and steppers. when i'm trying to make onestep, motor just makes some high-frequent noise, but when i add Serial.println for debugging, it moves as intended.
what is going on here?
here is an example:

#include AFMotor.h //dunno how to put angle brackets here

AF_Stepper lrM(48, 1);

void rightStep() {
  lrM.onestep(BACKWARD, INTERLEAVE);
}
void leftStep() {
  lrM.onestep(FORWARD, INTERLEAVE);
}

void setup() {
  Serial.begin(9600);
  Serial.println("ready");
}

void loop() {
  rightStep();
//Serial.println("right");
}

We need Minimal, Complete, and Verifiable example

ok. i've added one, but it is very common usage

My guess is Serial.println adds additional delay so stepper motor can react. Without it changes are way too fast (= high frequency noise) to do whole step.
Try to add delay(1); or more into the main loop.

i thought that if onestep function is blocking, it would be ok, but it appeared that i need delay(10) so that motor can run. thank you!

Method step contains delays, but there are no delays in onestep (at least not obvious ones).

When you have a Serial print statement running really quickly the output buffer will fill up and the print command will have to wait for there to be room; That causes the command to take a substantial amount of time to complete.
When the statement is missing, you loop probably runs a few hundred times faster than without it (depending on how long onestep takes), probably fast enough that the physical motor can not keep up.
Try adding a delay of a few milliseconds or some kind of rate limiting to the program and then see how much of a difference serial.println makes.


text:
Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno
I have an Arducam-Mini-5MP with Arduino UNO R3. I am running the unaltered example ArduCAM_Mini_OV5642_Video_Streaming to the arduino and am running ArduCAM_host_v1.0.exe on my PC with huge successes.
In this state, I can reliably take photos at low resolution (up to 1280x720) in all tested settings. However, when I go to higher resolutions (2592x1944, 2048x1563, and 1920x1080), certain situations result in consistently corrupt images all with the exact size of 524288 bytes.
The images are corrupted whenever I point the camera outside my window, and images are fine when taking photos inside my house. At 1280x720, a typical photo inside my house is 80kb and a typical photo out the window is 190kb (more than double in size). I suppose some content of the photo is impacting the jpg compression?
Unfortunately, images are corrupt 100% of the time for the actual subject I want to take; but the camera works perfectly when I'm testing it indoors. In my scenario I can only capture 0.8MP before images become corrupt.
The frame buffer limit for Arducam is 512kb, so am I just running up against the constraints of the hardware? I feel a bit fooled because I bought a 5MP camera and can only take 0.8MP photos with it.
Is my understanding of this failure correct -- is this the frame buffer size being hit by conditions impacting jpg compression? Are there Arducam shields available with higher frame buffers? Can I avoid this situation somehow?

You're getting corrupted images of size 524288 bytes consistently. It so happens that 512 kB * 1024 bytes/kB = 524288 bytes. You said it already; you've most likely hit the buffer's limit. I suggest you contact the Arducam support team concerning other shields with larger frame buffers.

Thanks for confirming that. So I guess I just wonder why do they put a 5MP camera onto a shield that only reliably supports 0.8 MP image sizes? Also wondering if there is a way to increase compression ratio or if there is something I'm missing here to make this design make more sense.

Okay - I have reached out to ArduCam team. https://github.com/ArduCAM/Arduino/issues/66

The problem may also be on the Arduino side. E.g. The SD library might not support files larger than 512kb.

The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).
To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04.  myCAM.wrSensorReg16_8(0x4407,0x09);
To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf
Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.


text:
How can I understand the circuit diagram for Arduino Starter Kit Project 4?

I have acquired the arduino starter kit project book, and the explanations seem at times confusing and difficult to understand.
Concerning the above circuit diagram, the book states (I am translating from French): "The resistor and the photoresistor are in series and together they divide up the voltage. The voltage at the point where they meet is proportional to the ratio of their resistances, according to Ohm's Law."

What does "the voltage at the point where they meet" mean? The voltage/ p.d. is always supposed to be across something, e.g. a certain component. This statement makes no sense to me at all.
The above misunderstanding leads on to me not understanding what the input pins A0-A2 actually receive. I understand that they receive a voltage, but don't know across what. Also, if the voltage inputs from these pins are used later on, are they digital? (these pins have an analogue-digital converter).

The important thing to remember, which will help you understand everything else, is that voltage is measured with respect to another point.
In this (and almost every) case it is measured with respect to ground. So when you say the voltage at point X is Y volts you are actually saying that the difference in voltage between point X and GND is Y volts.
So on your schematic A0 measures the difference in voltage between it's IO pin (the junction between the 10KΩ resistor and the LDR) and ground. And looking at it, what is between its IO pin and ground? The 10KΩ resistor. So it is actually the voltage across that resistor that you are measuring.
Doing the sums:
Assume there is enough light falling on the LDR to make it have a resistance of 5KΩ.  Current flows through both the LDR and the 10KΩ resistor in series, so it has a total resistance of (10,000 + 5,000) 15KΩ. With 5V across the whole lot (5V -> LDR -> 10KΩ -> GND) you get:
I = V/R = 5/15,000 = 0.000333... or 333µA.

333µA flowing through 10KΩ drops how much voltage?
V=RI = 10,000 × 0.000333... = 3.333...V

So A0 would be measuring 3.333V at that point.
Now, you turn out the lights, and the resistance of the LDR rises to, say, 50KΩ. What happens to those sums now?  Well, let's look:
Total resistance = 50,000 + 10,000 = 60,000Ω
I=V/R = 5/60,000 = 0.00008333...
V=RI = 10,000 × 0.00008333... = 0.8333...V

The formulae can be simplified into just the ratio of the two resistances:
           R2
Vout = --------- × Vin
        R1 + R2

So that is, with the lights on:
        10,000
Vout = --------- × 5 = 0.666... × 5 = 3.333...
        15,000

And with the lights on:
        10,000
Vout = --------- × 5 = 0.1666... × 5 = 0.8333...
        60,000

From that measured voltage, of course, you can then calculate what the resistance of the LDR must have been at the time. Rearranged the formula looks like:
      R2 × Vin
R1 = ---------- - R2
        Vout

Plug in the numbers for the voltage with the lights on:
      10,000 × 5              50,000
R1 = ------------ - 10,000 = -------- - 10,000 = 5,000Ω
       3.333...              3.333...

The kind of circuit is known as a Voltage Divider or Potential Divider and you can read more about them here: https://en.wikipedia.org/wiki/Voltage_divider

The analog inputs of the arduino can't read resistances. They read voltages and compare them with a reference voltage. They give you a number between 0 and 1023 so the read voltage is 1/1024 of the reference voltage.
The configuration of the LDR and the resistor is called a voltage divider. It is needed to get a voltage that the analog pin can read.
The intersection of the LDR and the resistor is where you can measure that voltage (or connect it to the analog pin of the arduino).
More info about this subject was already given in this question:
Why do you need a second resistor when using a photoresistor/LDR?
Wiki page about voltage dividers and the relevant formulas
https://en.wikipedia.org/wiki/Voltage_divider

I think what it means is that A0 = (5V / (Photo Resistor + 10K)).  Since the Photo Resistor will vary the voltage you get at A0 will be proportional to the light.  So by rearranging the formula above (I'm no good at doing that so you are on your own) you can convert the number received by A0 into the resistance that the photo resistor as applying and presumably turn that into Lux (?).
The analog pins report a number between 0 and 1023.  I can never remember if this equates to receiving a voltage of 0 - 5V or 0 - 2.5v.  Either way it is a linear conversion, so you can use (5V/1024)*reading to work out what the voltage at the pin is (or (2.5C/1024)*Reading).

Hope that helps.