text:
How can I concatenate multiple byte Arrays into one Array
I have three byte arrays. I first change their values during runtime and after that I want to combine them into one bigger 4th array.
byte a1[] = { 0x01, 0x00, 0x01 };
byte a2[] = { 0x00, 0x11, 0x01 };
byte a3[] = { 0x11, 0x00, 0x01 };

byte c1[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I first tried this, but it did not compile.
c1 = a1 + a2 + a3;

I also tried strcat() and I did got a error.

the answer depends on what you meant by "concatenate". you may be able to clarify by showing what you expect to be in c1[].

If any of the answers solved your problem, you should accept it.

You can concatenate with memcpy. You just need to set the pointer at the right place inside the c1 array.
memcpy(c1, a1, sizeof(a1));
memcpy(c1+sizeof(a1), a2, sizeof(a2));
memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));

They should also be careful that they use this method (with sizeof(), I mean) only when in the same scope where the arrays are declared. If the pointers to the arrays are passed to a function concat(), for instance, this will fail since sizeof() would return the pointer size and not the array size.

You can do it like this
byte c1[] = {0x01, 0x00, 0x01, 0x00, 0x11, 0x01,0x11, 0x00, 0x01 };
byte *a1 = c1;
byte *a2 = c1+3;
byte *a3 = c1+6;

Note that This does not make a copy byt you can access the C1 and a1 a2 and a3 as you liked.

I have a problem with jantje answer. As any array (c1) is a pointer to the array. So when you attempt to byte a1[] = c1; You are attempting to place the address of c1 into the 'byte'. More likely without an index attempting to change the location of a1. This will not compile. All of these are doing just what gre_gor suggested (memcopy) and is the accepted way of copying or moving data. :)

You are right on byte a1[] = c1; I changed the answer.
You are not right on stating this is the same as gre_gor suggested.
In my case only 9 bytes of memory are used for data (I don't count the pointers). In other words there is only 1 copy of the data where in gre_gor there are 2 copies.
Note that the question is very unclear about what is needed so for now we don't know a copy or simple reference is needed.

My suggestion about gre_gor was that it was the proper way to do it.  Any changes will be fixed during a compile, your code will not.  gilhad is virtually the same.   This new version will not compile either as you didn't change the problem.  Also, his code moves it from a to c, the opposite of yours, but the original source has the same value as does the destination.  Where is the 'other' copy? But you are correct, more information is needed for a good answer.

This is really a comment, not an answer. With a bit more reputation, you will be able to post comments. For the moment I've added the comment for you, and I'm going to delete this answer. Thanks for your understanding and cooperation!

byte *src;
byte *tgt;
tgt=c1;
src=a1;
for (int i=0;i<3;i++) *(tgt++)=*(src++);
src=a2;
for (int i=0;i<3;i++) *(tgt++)=*(src++);
src=a3;
for (int i=0;i<3;i++) *(tgt++)=*(src++);


text:
Problem to convert rotary encoder output to angle
I'm using this incremental rotary encoder with a rotating disc.
Here is my system:

I will explain the system briefly and above is the illustration for that:
The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle.
The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface.
There is also a fixed red arrow on the disc.
Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface.
This adjustment each time at the beginning will provide the reference point.
After this adjustment I want to output the actual angles via Arduino.
I tried the following example code from Arduino website:
#define encoder0PinA  2
#define encoder0PinB  4

volatile unsigned int encoder0Pos = 0;

void setup() {

  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

  attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");                // a personal quirk

}

void loop(){
// do some stuff here - the joy of interrupts is that they take care of themselves
}

void doEncoder() {
  /* If pinA and pinB are both high or both low, it is spinning
   * forward. If they're different, it's going backward.
   *
   * For more information on speeding up this process, see
   * [Reference/PortManipulation], specifically the PIND register.
   */
  if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos++;
  } else {
    encoder0Pos--;
  }

  Serial.println (encoder0Pos, DEC);
}

/* See this expanded function to get a better understanding of the
 * meanings of the four possible (pinA, pinB) value pairs:
 */
void doEncoder_Expanded(){
  if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
    if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                             // encoder is turning
      encoder0Pos = encoder0Pos - 1;         // CCW
    }
    else {
      encoder0Pos = encoder0Pos + 1;         // CW
    }
  }
  else                                        // found a high-to-low on channel A
  {
    if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                              // encoder is turning
      encoder0Pos = encoder0Pos + 1;          // CW
    }
    else {
      encoder0Pos = encoder0Pos - 1;          // CCW
    }

  }
  Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                              // before final program run
  // you don't want serial slowing down your program if not needed
}

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction.
It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW.
I want to translate this code such that I can output the angle in degrees.
My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.
Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

if it's 30ppr then every count is 12 degrees. So multiply the number by 12. The do a modulo 360 ( x = x % 360), so you only get values from 0 to 360. But not that you can only know the angle difference from when the sketch first started. So you have to set the disk to the zero position before turning on the Arduino.

Serial.println() can cause problems when used within an ISR.  Set a flag instead, and print from loop()

@jwpat7 How can I implement that setting flag and outputting from void? I also experience two outputs at some single encoder ticks. Can that be because of bouncing?

Declare a flag, eg volatile byte cchange;, and set it true in the ISR.  In loop(), say if (cchange) { cchange=false; printstuff(); }   ¶ Re double counts, the ISR shown is slow, which can mess up counting.  If your ISR were to catch all the edges and treat them correctly, eg via a state machine like in my answer to question 32572,  bouncing would cancel out.

How could this code be modified to use an indexed encoder to reset the counter to 0 every time it hit the index. I would like to use this to track a rotating mast for direction finding.

Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos += 24;
} else {
    encoder0Pos -= 24;
}
encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

"The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.
This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.
#include <Bounce2.h>

#define encoder0PinA  2
#define encoder0PinB  4
#define STEP_SIZE 12

byte encoder0Pos = 0;

Bounce debouncerA = Bounce();
Bounce debouncerB = Bounce();

void setup()
{
    debouncerA.attach(encoder0PinA, INPUT_PULLUP);
    debouncerA.interval(5); // interval in ms
    debouncerB.attach(encoder0PinB, INPUT_PULLUP);
    debouncerB.interval(5); // interval in ms

    Serial.begin (9600);
    Serial.println("start");                // a personal quirk

}

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }

    if (EncVariation != 0)
    {
        encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

        Serial.println (encoder0Pos, DEC);
    }
}

Disclaimer: I haven't tested this, but I'm pretty confident this will work.
I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See here for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)

This code works better I dont see erratic outputs. Is it also possible to output the direction CCW or CW. I mean this code will work but I also want an LED to turn on when  the encoder rotates CCW. How can it be done? Thanks in advance

oh i actually noticed EncVariation indicates the direction:)

@doncarlos yes, just check it and it tells you whether it is turning (!= 0) and the direction. By the way, if the answer fully answers your question please mark it as accepted; otherwise just ask ;)

As noted in a comment, treating the numbers modulo 360° will put results into the range you want.
Note, however, that you can (and should) avoid use of long arithmetic by taking the pulse count modulo 30 before multiplying by 12°.
To compensate for the reference point adjustment, have the program set your tick count to correspond to 0° when the arrows align.  If you set the base count to some value that's a multiple of 30, say 120, and store it in an unsigned byte, the code would look like so:
angle = 12*(count%30);

Since the base count 120 is a multiple of 30, it falls out automatically when the modulus is taken.  To make this work in the long run, you would set the encoder count to 120 whenever the arrows align (or to (current%30)+120 if required to adjust it at other times).
If your base count were 0 instead of 120 and the count an unsigned integer instead of a byte, when the rotor goes CCW the modulus counts would have 15 extra counts.  For example, a count of 0 correctly converts to 0°, but a count of 65535 is 15 modulo 30, so converts to 180° instead of 348°.
Note, there is no need to debounce rotary encoder inputs if a proper state machine is used; and debouncing slows processing to the point that ticks will be lost.  See my answer to question 32572 which includes code for reading several encoders active at once.

source: Stack Exchange

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

sort: votes


text:
How can I switch a 1.5V buzzer with my Arduino?
I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.
I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.
I did some reading on transistors and this is what I came up with:
I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

To me it looks like you have your emitter and collector backwards? (but it's hard to tell from the picture, is it E B C? I think it should be C B E)

Could you add your ground connection(s) in, please?  as @redstarcoder says, it's hard to understand where you're going with it. Are you trying to put the buzzer on the collector or the emitter?

I just registered to the website to check, the first NPN transistor I saw was in fact C B E.

You need to connect the GND of the Arduino to the GND/- of the battery. In most application the transistor is placed after the load (buzzer). So + -- buzzer -- transistor -- -. But I don't think it matters in this case. But I have the feeling you can connect the buzzer directly to the Arduino by just adding a proper value resistor, to lower the voltage to around 1.5V. Where did you get the buzzer from?

@ redstarcoder The transistor in the picture is C B E, so the buzzer is connected to the emitter -- I expected it to be E B C. So the buzzer is on the collector, that's correct, right?
@ MarkSmith Grounding the Arduino surely helped a lot and indeed fixed my problem.
@ Gerben The buzzer is inside my alarm clock, I'll need to open it up to measure the exact voltage and current it requires -- I'll do that and report back.

You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.

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


text:
Fading LED Lights
How do you make a fading led with 8 different colors I already made a blinking led every 1 second. Can you give me an idea how am I going to fade it every time it switch?
const int red = 5;
const int green = 6;
const int blue = 9;

void setup() {
    // put your setup code here, to run once:
    pinMode(red, OUTPUT);
    pinMode(green, OUTPUT);
    pinMode(blue, OUTPUT);
}

void loop() {
    lightMe(red);
    lightMe2(red, green);  // yellow
    lightMe(green);
    lightMe2(green, blue);  // cyan
    lightMe(blue);
    lightMe2(blue, red);  // magenta
    lightMe3(red, green, blue); // white
}

void lightMe(int pin){
    digitalWrite(pin, HIGH);
    delay(1000);
    digitalWrite(pin, LOW);
    delay(500);
}

void lightMe2(int pin1, int pin2) {
    digitalWrite(pin1, HIGH);
    digitalWrite(pin2, HIGH);
    delay(1000);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    delay(500);
}

void lightMe3(int pin1, int pin2, int pin3) {
    digitalWrite(pin1, HIGH);
    digitalWrite(pin2, HIGH);
    digitalWrite(pin3, HIGH);
    delay(1000);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(pin3, LOW);
    delay(500);
}

I explain a good method here: https://hackingmajenkoblog.wordpress.com/2016/10/02/flexible-led-fading/

You could look at this example, which fades an LED using PWM.
https://www.arduino.cc/en/Tutorial/Fading
Basically you use analogWrite to control the output of the pins with finer resolution, 0-255 rather than 0-1.  Only certain pins support PWM, they should be marked on your board.  You just need to extend the example to support your LED.  (Put the resistor on the common pin)

int color_set = 0;    //set to red first
int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec

// set the color for all the LEDs based on the color code
void setcolor(int colorcode) {

  for (int i = 0; i < LED_COUNT; i++) {
    // instead of setting the color all at once we're going to step through each LED to show how to set them individually
    switch(colorcode) {
      // We're going to pass a CRGB here,
  case 0: leds[i] = CRGB(255, 0 , 0); break; // red

  case 1: leds[i] = CRGB(255, 127, 0); break; // orange

  case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

  case 3: leds[i] = CRGB(0, 255, 0); break; // green

  case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

  case 5: leds[i] = CRGB(0, 0, 255); break; // blue

  case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

  case 7: leds[i] = CRGB(148, 0, 211); break; // violet
}
  }
     LEDS.show();
    }
// we'll make the color fade in and out by setting the brightness
void pulse(int wait_fade) {
  // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
  // Oh, and 93 is plenty bright!
  for(int scale = 0; scale < 93; scale++) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
  // now let's fade down by scaling the brightness
  for(int scale = 93; scale > 0; scale--) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
}

// this is the main loop where we call the other functions.
void loop() {
  int waiting_time = 10; //time in ms for color scaling
  setcolor(color_set);  //we call our color-set routine
  pulse(waiting_time); //now we make it fade in and out
  color_set++;        //next color
  color_set = color_set % 8; // number of color modulus, remember it's 0 based.
}

because there are so many different microcontrollers, i left it basic, and you only need to define color_set as a integer and then the setcolor() loop, as you can see in the main loop we pass the parameter color_set from our integral 8 colors. here is my complete arduino setup:
#include <FastLED.h>

#define LED_COUNT 96 // number of LEDs!
struct CRGB leds[LED_COUNT]; // this struct contains 60 CRGB values.

#define PIN_BUTTON 10
#define PIN_IO_A   7
#define PIN_IO_B   11
#define PIN_SIGNAL 13
#define PIN_INPUT  10

int color_set = 0;   // set to red
int wait_fade = 1000 // delay time in ms.  1000ms is equal to 1sec
// first, let's get ready to blink using some FastLED routines
// take a look at the FastLED example called Fast2Dev for more usage info
void setup()
{
  LEDS.addLeds<WS2812B, PIN_SIGNAL, GRB>(leds, LED_COUNT); // this configures the Board - leave as is.
  LEDS.showColor(CRGB(0, 0, 0)); // set the color for the strip all at once.
  LEDS.setBrightness(0); // start out with LEDs off
  LEDS.show(); // you'll always need to call this function to make your changes happen.
}

// set the color for all the LEDs based on the color code
void setcolor(int colorcode) {

  for (int i = 0; i < LED_COUNT; i++) {
    // instead of setting the color all at once we're going to step through each LED to show how to set them individually
    switch(colorcode) {
      // We're going to pass a CRGB here,
  case 0: leds[i] = CRGB(255, 0 , 0); break; // red

  case 1: leds[i] = CRGB(255, 127, 0); break; // orange

  case 2: leds[i] = CRGB(255, 255, 0); break; // yellow

  case 3: leds[i] = CRGB(0, 255, 0); break; // green

  case 4: leds[i] = CRGB(0, 255, 255); break; // cyan

  case 5: leds[i] = CRGB(0, 0, 255); break; // blue

  case 6: leds[i] = CRGB(75, 0, 130); break; // indigo

  case 7: leds[i] = CRGB(148, 0, 211); break; // violet
}
  }
     LEDS.show();
    }
// we'll make the color fade in and out by setting the brightness
void pulse(int wait_fade) {
  // let's fade up by scaling the brightness - in general, brightness shouldn't go above 93, so the strip won't draw too much power.
  // Oh, and 93 is plenty bright!
  for(int scale = 0; scale < 93; scale++) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
  // now let's fade down by scaling the brightness
  for(int scale = 93; scale > 0; scale--) {
    LEDS.setBrightness(scale);
    LEDS.show();
    delay(wait_fade);
  }
}

// this is the main loop where we call the other functions.
void loop() {
  int waiting_time = 10; //time in ms for color scaling
  setcolor(color_set);  //we call our color-set routine
  pulse(waiting_time); //now we make it fade in and out
  color_set++;        //next color
  color_set = color_set % 8; // number of color modulus, remember it's 0 based.
}

A lot of the code is commented.  I use FastLED too.  If you have any questions please let me know.

You have to explain what it do and how you use it. Code is incomplete ... what is CRGB? What is colorcode (RGB, HSV, ...)? What is wait_fade (ms, sec, other)?

i defined 'wait_fade', which is the delay time.  everything runs just fine in any arduino IDE


text:
Can I use Arduino to generate a 0 to 15V analog output?
Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

Yes, if you use an amplifier.

The Arduino cannot directly produce anything more than 5V.
You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.
If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

simulate this circuit – Schematic created using CircuitLab
R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't rail-to-rail which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.

Thank you very much. Your explanation is really helpful. I don't need a high current output. What op-amp do you suggest me to use? What is the triangle at the bottom of the figure? Is that the ground?

Yes, that is ground. I suggest a parametric search on your favourite electronics supplier. You are looking for one that works at a high enough voltage and, if you don't want a negative supply, then one that works on a single supply rail.

The supplier in my region is quite hard to work with. Do you mind suggest a model no. for me? I think the minimum voltage output I need is 0.3V. Do I need a negative supply?

You could try the TL072, though I can't see in the datasheet how well it works with a single supply.

finally, I have tried the circuit, but I found that the voltage output is 5-17V.

I connect the arduino board to my macbook air without charging, the circuit ground is connected to the arduino ground pin. Any idea?

The Arduino does not have any "analog output pin". There are analog inputs, and you can generate a variable output with PWM pins.
Whether the latter meets your needs depends on your (unstated) requirements.


text:
Flash Esp-01 and Esp-12 using NodeMCU module
I am building a test IOT architecture. At the moment I do have a NodeMCU "Amica" V1 module (more will come) and some ESP-01. I have not yet tried to flash the ESP-01 because the MCU is just so user friendly, while buying 6 MCU is more pricey than .
I was wondering, if I do de-solder the ESP-12 from the NodeMCU and then connect a female receptacle for the ESP-01 to the now empty MCU breakout board, would i be able to flash the ESP-01 from the Arduino IDE?
Would it maintain the automatic Reset and Flash pulls (as on the stock ESP-12)?
Will it also work with a pogo-pin assembly to flash other ESP-07/12 ?
Approximate answers and thoughts are well accepted, thank you very much.

look it up, it's open source hardware: https://smartarduino.gitbooks.io/user-manual-for-esp-12e-devkit/content/schematics_for_esp-12e_devkit.html

On this site there's a description of how to use a USB-serial adapter to flash a ESP-01 with the Arduino IDE. I'm not very familiar with the NodeMCU boards, but I imagine that they contain a USB-serial chip, and thus it is possible to desolder the ESP-12 and connect a ESP-01 (with cables or an adapter with pogo-pins) and program it that way. I'm not sure about the Reset/Flash pulls, but I imagine that it could be possible, study the pinouts for the ESP-12 and ESP-01 and circuitry for flashing (see the link). I did flash my ESP-01 this way, before I got other ESP8266 boards.
I would only do this operation if I was very handy with a soldering iron and the NodeMCU/ESP-12 was something that could go to waste if anything went wrong.
I think picking up a 3.3V LDO and USB-serial (3.3v!) breakout much easier, and more failproof, so that's what I'd recommend.


text:
Writing to a SPI memory
Recently I salvaged a BIOS chip (EN25QH16) which has 2 Megabytes of memory (8192 pages, 256 bytes/page). I followed this instructables and it works. I double checked the opcodes because the code is for a Winbond chip, mine is Eon and of course, they're the same (standards?). All commands worked as it should. I modified the code that writes Hello World string to a page. I tried the command but it returns (from the memory) Hello Worlb. This is the snap of the serial monitor:

I erased the chip just to make sure and ran the command test_write (which I added). It wrote 48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00 which is in ASCII Hello Worlb and I don't know why that happened. Btw this is the modified code:
/*
    windbond_serial_debug.cpp
    A simple program for the Arduino IDE to help familiarize you with
    using WinBond flash memory; can also be used to download the entire
    contents of a flash chip to a file via a serial port interface.

    Important bits of the code: the low-level flash functions (which
    implement the timing diagrams in the datasheet), and a simple
    serial-port command interface that allows you to talk to your
    UNO with any generic terminal application (even the command line).

    Copyright 2014, Peter J. Torelli

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Revisions:
    rev 2 - 21-SEP-2014.
    User 'fiaskow' pointed out that driving the WEL instruction after
    program and erase w/o waiting for the op to finish may be corrupting
    execution. Removed this code (also not needed b/c the WEL is already
    cleared after page write or chip erase).
*/

#include <SPI.h>
// SS:   pin 10
// MOSI: pin 11
// MISO: pin 12
// SCK:  pin 13

// WinBond flash commands
#define WB_WRITE_ENABLE       0x06
#define WB_WRITE_DISABLE      0x04
#define WB_CHIP_ERASE         0xc7
#define WB_READ_STATUS_REG_1  0x05
#define WB_READ_DATA          0x03
#define WB_PAGE_PROGRAM       0x02
#define WB_JEDEC_ID           0x9f

/*
 * These global variables enable assembly of the user serial
 * input command.
 */
boolean g_command_ready(false);
String g_command;

/*
 * print_page_bytes() is a simple helperf function that formats 256
 * bytes of data into an easier to read grid.
 */
void print_page_bytes(byte *page_buffer) {
  char buf[10];
  for (int i = 0; i < 16; ++i) {
    for (int j = 0; j < 16; ++j) {
      sprintf(buf, "%02x", page_buffer[i * 16 + j]);
      Serial.print(buf);
    }
    Serial.println();
  }
}

/*
================================================================================
User Interface Routines
The functions below map to user commands. They wrap the low-level calls with
print/debug statements for readability.
================================================================================
*/

/*
 * The JEDEC ID is fairly generic, I use this function to verify the setup
 * is working properly.
 */
void get_jedec_id(void) {
  Serial.println("command: get_jedec_id");
  byte b1, b2, b3;
  _get_jedec_id(&b1, &b2, &b3);
  char buf[128];
  sprintf(buf, "Manufacturer ID: %02xh\nMemory Type: %02xh\nCapacity: %02xh",
    b1, b2, b3);
  Serial.println(buf);
  Serial.println("Ready");
}

void chip_erase(void) {
  Serial.println("command: chip_erase");
  _chip_erase();
  Serial.println("Ready");
}

void read_page(unsigned int page_number) {
  char buf[80];
  sprintf(buf, "command: read_page(%04xh)", page_number);
  Serial.println(buf);
  byte page_buffer[256];
  _read_page(page_number, page_buffer);
  print_page_bytes(page_buffer);
  Serial.println("Ready");
}

void delayed_read_all_pages(void) {
  delay(5000);
  read_all_pages();
  }

void read_all_pages(void) {
  Serial.println("command: read_all_pages");
  byte page_buffer[256];
  for (int i = 0; i < 4096; ++i) {
    _read_page(i, page_buffer);
    print_page_bytes(page_buffer);
  }
  Serial.println("Ready");
}

void write_byte(word page, byte offset, byte databyte) {
  char buf[80];
  sprintf(buf, "command: write_byte(%04xh, %04xh, %02xh)", page, offset, databyte);
  Serial.println(buf);
  byte page_data[256];
  _read_page(page, page_data);
  page_data[offset] = databyte;
  _write_page(page, page_data);
  Serial.println("Ready");
}

/*
================================================================================
Low-Level Device Routines
The functions below perform the lowest-level interactions with the flash device.
They match the timing diagrams of the datahsheet. They are called by wrapper
functions which provide a little more feedback to the user. I made them stand-
alone functions so they can be re-used. Each function corresponds to a flash
instruction opcode.
================================================================================
*/

/*
 * See the timing diagram in section 9.2.35 of the
 * data sheet, "Read JEDEC ID (9Fh)".
 */
void _get_jedec_id(byte *b1, byte *b2, byte *b3) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_JEDEC_ID);
  *b1 = SPI.transfer(0); // manufacturer id
  *b2 = SPI.transfer(0); // memory type
  *b3 = SPI.transfer(0); // capacity
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.26 of the
 * data sheet, "Chip Erase (C7h / 06h)". (Note:
 * either opcode works.)
 */
void _chip_erase(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_CHIP_ERASE);
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }
/*
 * See the timing diagram in section 9.2.10 of the
 * data sheet, "Read Data (03h)".
 */
void _read_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_DATA);
  // Construct the 24-bit address from the 16-bit page
  // number and 0x00, since we will read 256 bytes (one
  // page).
  SPI.transfer((page_number >> 8) & 0xFF);
  SPI.transfer((page_number >> 0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    page_buffer[i] = SPI.transfer(0);
  }
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.21 of the
 * data sheet, "Page Program (02h)".
 */
void _write_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_PAGE_PROGRAM);
  SPI.transfer((page_number >>  8) & 0xFF);
  SPI.transfer((page_number >>  0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    SPI.transfer(page_buffer[i]);
  }
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}

/*
 * not_busy() polls the status bit of the device until it
 * completes the current operation. Most operations finish
 * in a few hundred microseconds or less, but chip erase
 * may take 500+ms. Finish all operations with this poll.
 *
 * See section 9.2.8 of the datasheet
 */
void not_busy(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_STATUS_REG_1);
  while (SPI.transfer(0) & 1) {};
  digitalWrite(SS, HIGH);
}

/*
 * This handy built-in callback function alerts the UNO
 * whenever a serial event occurs. In our case, we check
 * for available input data and concatenate a command
 * string, setting a boolean used by the loop() routine
 * as a dispatch trigger.
 */
void serialEvent() {
  char c;
  while (Serial.available()) {
    c = (char)Serial.read();
    if (c == ';') {
      g_command_ready = true;
    }
    else {
      g_command += c;
    }
  }
}

void setup(void) {
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);
  Serial.begin(9600);
  Serial.println("");
  Serial.println("Ready");
}

/*
 * loop() dispatches the commands compiled by the serialEvent
 * parser callback. Some commands take multiple arguments, so
 * I have to split up the strings with some messy manipulation.
 */
void loop(void) {
  if (g_command_ready) {
    if (g_command == "get_jedec_id") {
      get_jedec_id();
    }
    else if (g_command == "test_write") {
      Serial.println("Custom command: test_write");
      _write_test();
      }
    else if (g_command == "chip_erase") {
      chip_erase();
    }
    else if (g_command == "read_all_pages") {
      read_all_pages();
    }
    else if (g_command == "delayed_read_all_pages") {
      Serial.println("Custom command: delayed_read_all_pages");
      delayed_read_all_pages();
      }
    // A one-parameter command...
    else if (g_command.startsWith("read_page")) {
      int pos = g_command.indexOf(" ");
      if (pos == -1) {
        Serial.println("Error: Command 'read_page' expects an int operand");
      } else {
        word page = (word)g_command.substring(pos).toInt();
        read_page(page);
      }
    }
    // A three-parameter command..
    else if (g_command.startsWith("write_byte")) {
      word pageno;
      byte offset;
      byte data;

      String args[3];
      for (int i = 0; i < 3; ++i) {
        int pos = g_command.indexOf(" ");
        if (pos == -1) {
          Serial.println("Syntax error in write_byte");
          goto done;
        }
        args[i] = g_command.substring(pos + 1);
        g_command = args[i];
      }
      pageno = (word)args[0].toInt();
      offset = (byte)args[1].toInt();
      data = (byte)args[2].toInt();
      write_byte(pageno, offset, data);
    }
    else {
      Serial.print("Invalid command sent: ");
      Serial.println(g_command);
      g_command = "";
    }
done:
    g_command = "";
    g_command_ready = false;
  }
}

byte data[sampleText.length()];, should be byte data[256];, as _write_page expects the page_buffer to be 256 bytes long. Also 48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00 isn't Hello Worlb but Hello Worl<null>b<etx><vt><null><vt><null>

@Gerben Hello Worlb is from an online converter but the Notepad++ conversion looks like yours.

Strings in C are terminated with a null byte - so the string "A" is in fact two bytes: the 'A' followed by a null.
Your _write_test() function counts only the characters in the string, and hence allocates one byte too few.  It should be:
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()+1];
  sampleText.getBytes(data, sizeof(data));
  // See text below before calling write_page()
}

But then we hit the issue of how much data write_page() will write.  It doesn't have any way of knowing how much data you are passing in - it just gets a pointer.  Looking at its implementation we can see that it writes exactly 256 bytes, so we need to pass in a buffer of 256 bytes.
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[256];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }

(If we pass in a smaller buffer we're leaving it up to chance what will happen.  The Arduino doesn't have much protection so probably you'll just write garbage, but maybe, just maybe, you'll get unlucky and some weird crash will happen.)

Yep with my code it writes some garbage (I converted the hex and there's some of it). Well, it works now. Thanks!


text:
Confusion in the use of byte variable
A byte stores an 8-bit unsigned number, from 0 to 255.
I can understand the following line:
byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:
volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

There is probably somewhere else, like this:
#define LOW 0

Which means the pre-processor turns your line from this:
volatile byte state = LOW;

into this:
volatile byte state = 0;

There is nothing arduino-specific here, just the use of standard C/C++ features.

It is common practise in C/C++ to define certain much-used constants at the beginning of the code.
#define true 1

this means that every time you write true in your code, the compiler will see it as 1.
The arduino IDE comes with a few constants predefined:

true = 1
false = 0
HIGH = 1
LOW = 0
...

in C++ true and false are already keywords, why would one try to  #define them?

@jfpoilpret Perhaps if one is not using C++ ...

In the same way that you can do
int blarb = 12;
#define wibble 73

you can do
int FOO = 73;
#define BINKY 99

or even
int LOW = 0;
#define HIGH 1

So in the line
volatile byte state = LOW;

someone has created some sort of numerical constant with the name LOW.
You can read all about various constants provided for you here.


text:
Multiple if statements - stuck
I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.
The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.
The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.
I have adapted NewPing and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.
If anybody has any suggestions, it would be greatly appreciated.
#include <NewPing.h>

#define SONAR_NUM     3 // Number of sensors.
#define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(8, 3, MAX_DISTANCE),  //Center
  NewPing(7, 9, MAX_DISTANCE),  //Right
};

int ledR = 13;
int ledG = 2;
int ledB = A0;
int motorPinL = 5;
int motorPinR = 6;
int ePIR = 10;
boolean epirVal;

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
  pinMode (ledR, OUTPUT);
  pinMode (ledG, OUTPUT);
  pinMode (ledB, OUTPUT);
  pinMode (motorPinL, OUTPUT);
  pinMode (motorPinR, OUTPUT);
  pinMode (ePIR, INPUT);
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1)
        oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // Other code that *DOESN'T* analyze ping results can go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void allStop () {
  analogWrite (motorPinL, 0);
  analogWrite (motorPinR, 0);
  digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
  digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
  digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
}

What exactly do you want it to do? Currently your top priority is to stop if any sensor is outside the range bracket or if epirVal is true. If epirVal is false and a sensor is in range you turn. If epirVal is false and no sensor is within range you keep doing whatever you were doing before.

@Andrew I want the robot to go straight if the middle sensor detects the person between 65cm and 150cm and the PIR sensor sees the person (when it sees a person epirVal == false because it's active low. If the right sensor sees the person in the same range and the epirVal is low, the robot turns right. If the left sensor sees the person in the same range and the epirVal is low, then it turns left. I had too many else if's in the last code. I have rewritten my code and the applicable part is the very last function. There is something very wrong with my logic. looking for help.

@Andrew  and btw it doesn't do anything with this current code. It just sits there.

Do not vandalise your post. This may result in a question ban. see question bans

Your logic is flawed. Translating your loop in pseudocode gives
something like this:
if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
    stop
} else if (PIR does detect AND right sonar is in range) {  // cond. 2
    turn right
} else if (PIR does detect AND left sonar is in range) {  // cond. 3
    turn left
} else if (PIR does detect AND center sonar is in range) {  // cond. 4
    go straight
}

Notice that, if condition 1 is false, then that means that the PIR does
detect AND ALL of the sonars are in range. Which implies that condition
2 is necessarily true. Which implies that the following elses have no
effect. Your code can then be optimized (and the compiler probably did
optimize it) into
if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
    stop
} else {  // cond. 2 is true if cond 1. is false
    turn right
}

You should rethink your problem asking yourself the following questions:

under what conditions should the robot turn right?
under what conditions should the robot turn left?
under what conditions should the robot go straight?
under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions
holds true. In other words, the conditions should be mutually exclusive
and cover every possibility. One you have the answers, the coding should
be straightforward.

Edit: Your updated code still contains logic flaws. For example, if
the PIR senses the person and BOTH the left and right sonars are in
range, then you are asking the robot to BOTH turn left and turn right.
Unless it's a quantum robot evolving in an Everett's multiverse, it
won't be able to comply. To the risk of repeating myself, you must
decide on one and only one action for every possible situation.
If you are struggling with that concept, I suggest you start by filling
the truth table below. On each of the 16 lines of the table you should
fill the last column with one (and only one) action among: allStop,
turnRight, turnLeft and straight. Yes, I know it's tedious to
consider all the possible situations one by one, but you must do that
before starting to write the code. Otherwise you end up with completely
broken logic.
+--------+----------+----------+----------+-----------+
| PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
| senses | in range | in range | in range |  action   |
+--------+----------+----------+----------+-----------+
|  no    |   no     |   no     |   no     |           |
|  no    |   no     |   no     |   yes    |           |
|  no    |   no     |   yes    |   no     |           |
|  no    |   no     |   yes    |   yes    |           |
|  no    |   yes    |   no     |   no     |           |
|  no    |   yes    |   no     |   yes    |           |
|  no    |   yes    |   yes    |   no     |           |
|  no    |   yes    |   yes    |   yes    |           |
|  yes   |   no     |   no     |   no     |           |
|  yes   |   no     |   no     |   yes    |           |
|  yes   |   no     |   yes    |   no     |           |
|  yes   |   no     |   yes    |   yes    |           |
|  yes   |   yes    |   no     |   no     |           |
|  yes   |   yes    |   no     |   yes    |           |
|  yes   |   yes    |   yes    |   no     |           |
|  yes   |   yes    |   yes    |   yes    |           |
+--------+----------+----------+----------+-----------+

The pseudo-code above is what I want the robot to do. I just can't think how to make it mutually exclusive. I have been looking at your answer and thinking about this most of the day, and I don't know what the next step is. I know you say to rethink the problem and ask myself the questions, but I thought I already had it coded to do just exactly what your questions are. I'm not seeing the logic. Any hints to give me another step in the right direction?

You said, "Notice that, if condition 1 is false, then that means that the PIR does detect AND ALL of the sonars are in range. Which implies that condition 2 is necessarily true. Which implies that the following elses have no effect."  I feel like I'm missing something on the fundamental use of if...else if. Can you help?

@DanielShields: See the De Morgan's laws: NOT(NOT(PIR detects) OR NOT(sonar 0 in range) OR NOT(sonar 1 in range) OR NOT(sonar 2 in range)) = (PIR detects AND sonar 0 in range AND sonar 1 in range AND sonar 2 in range).

I'm not a philosopher or a professional programmer. Can you be a little more specific?

@ Edgar Bonet changed my code above. I now know that you can't have more than one else if statement so those were changed. I tried to think of every scenario and make the code mutually exclusive and cover every possibility. Per your suggestion. Now it does nothing except for the middle and left led flash really quickly.

@DanielShields: You don't need special qualifications to understand De Morgan's laws. They basically say that the negating “It's sunny AND cold.” yields “It's NOT sunny OR it's NOT cold.”. Since you seem to be struggling with logic, I updated my answer with a table for you to fill. Once you are done, you may be able to solve your problem all by yourself. If not, then add the filled table at the end of your question: we will then at least know what your program is intended to do.


text:
5V 1A vs 5V 5A power supply for 6 LED + Arduino
If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with 1A or 5A power supply? Same goes to the Arduino, if I want to power it externally, do I go for the 1A or 5A?

Both will work, but using a 5A one is quite a bit of overkill.

If I'm using 5A, will be voltage drop of the resistor be more or less? Should it be more since it needs to resist more current, hence more voltage drop

@Jason "series limiting resistor" will limit the current.

The 5A refers to the maximum current it can supply. If you draw less, it will supply less. As long as the voltage is the same, there will be the same amount of current flowing through the led.

Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.
Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.

Both will work, but go with 1A!!!
It is more forgiving if a short happens.
A 5A short circuit will make sparks that might be dangerous.


text:
Weird formatting behavior with sprintf function
I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.
But that line:
sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:
3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:
3000;110;291;263;230;0;0;245

Here is my sketch:
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);

  interrupts(); // Allow interrupts.
}

ISR(TIMER1_COMPA_vect){
  if (!interruptFlag){
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag){
    writeAnalogSignals();
    count++;
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;

  if (count >= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;
  }
}

Why are you even using sprintf? What's wrong with just printing the values direct to serial?

I was just using sprintf to format data instead of using concat or «+», it seems more efficient to me. But hey, I'm open to improvement. My C is far far beyond me! Is this a best practice to do multiple acquisitions before sending it on the Serial or I can send it on each iteration?

Serial is way slower than your acquisition. It depends if you want a block of data followed by a delay while it sends, or a smooth sending of values over time. Either way using strings to store the data isn't good - it's a huge waste.

What are you proposing for storing the data instead of string type?

An array of ints if you really must store it. However, unless you have a requirement to do a block of high speed sampling followed by sending then don't bother storing - just write the values out as you sample them. You're not making the sending any faster by storing them, and that is by far the slowest operation.

Have you tried replacing \r with \r\n at the end of your strings? it is possible that the serial console on your computer uses \r to return to the beginning of the line without going to a new line, then the latest content will override the previous one.

@jfpoilpret that don't work

As mentioned by @jot your x is 4 bytes but sprintf expects it to be 2 bytes because you used %d in the format string. If you want to keep x as a long, then replace the first %d with %ld and that should fix it; otherwise declar x as int. Please accept @jot answer if that fixes your problem.

Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.
When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.
For a data rate of 50Hz, I suggest to raise the baudrate to 115200.
Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the BlinkWithouDelay example and use 20ms as an interval.

Thanks @Jot. In my first implementations, I used delay().The use of interrupt came off along the way while I tried to optimize my code. I will try another baud rate.

Ok, performance is much better at 115200 bauds!


text:
Make Arduino Executable File
On a Pi, to execute a C++ code, you'll need a Makefile.
Is there an equivalent with the Arduino? Where I have some valid C++ files to upload without the IDE's help, but instead with an executable?

See also http://arduino.stackexchange.com/questions/32998/how-to-convert-arduino-example-sketch-to-a-complete-c-project

On a Pi you absolutely do not need a Makefile to execute C++ code. Regarding building an executable from C++ code on Pi, you may want to use a Makefile to help you do it, but having a Makefile is in no way mandatory.

You can find several Makefile solutions for Arduino on Internet. Some of them are listed in this question: http://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control Now since I am using NetBeans IDE for my Arduino projects (check out https://github.com/jfpoilpret/fast-arduino-lib/blob/master/ArduinoDevSetup.docx for a description of my setup), it automatically creates Makefiles for me.

Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file.  This is a text file describing the data to load into the flash memory.
You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).
A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the make program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.
There are many Arduino Makefile projects out there that do it all for you.

Take a look at platformio.org. It Provides a simple CLI environment to compile, upload and monitor.


text:
Can't upload new sketch
Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:
> avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.
Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.
(BTW: Yes I've set the settings to the correct board, port etc...)

Thanks for any solution attempts!

Clean the board up using solder wick -- if there are shorts like those mentioned in Jot's answer, it may clear them up.  Also, if you need an Arduino to solder into a circuit, just start with one that doesn't come with pins soldered on already -- eg, a Nano or Micro.  You can buy half a dozen of each for the cost of the time to take the pins off an Uno.

If I may suggest, there are "minimal" boards around you can buy for a couple of dollars that just have the basic processor on them. This could be a better solution than heating up your Uno (probably quite a lot) to get rid of the existing pins.

Removing there pin headers should not cause any sketch upload issue. I have done it many times.
You did try uploading BEFORE unsoldering the headers right ?
However looking at the desoldering job you did, my guess is that you applied too much heat or cut a trace on the PCB while doing it.
Can you upload a high resolution of the back side of the board?
What I would try is to take a known good 328p chip and replace the one on this board with it and try uploading again.

Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.

Checking the schematic, the TX/RX leds are driven directly by the atmega16u and are not connected to the TX/RX lines of the 328p.  That would seem to indicate the 16u has a problem so it's a good place to double check. The lines that run to the TX/RX of the 328p run from pins 8 - 9 of the 16u. I assume that this ran previous to the fatal 'surgery'? I don't suppose you loaded something simple, like the led flash program before surgery?  Just curious, are you hard wiring it to something?

Try to unplug the IC and the plug it again.
I think that you have removed the IC off of the board. If it doesn't work then buy a new ATmega328P IC and replace it with the old one and then try again.


text:
'content' is not captured
I try to make a variable that can be modified from the server, using and ESP8266.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

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

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
    digitalWrite(led, 1);
    server.send(200, "text/plain", "hello from esp8266!");
    digitalWrite(led, 0);
}

void handleNotFound() {
    digitalWrite(led, 1);
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
        digitalWrite(led, 0);
    }
}

void setup(void) {
    pinMode(led, OUTPUT);
    digitalWrite(led, 0);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {
        Serial.println("MDNS responder started");
    }

    String content = "Basic";
    content += "<form action='action_page.php' method='POST'>
";
    content += "User:<input type='text' name='USERNAME' placeholder='user name'>
";
    content += "<input type='submit' name='SUBMIT' value='Submit'></form>
";

    server.on("/led", [](){
        server.send(200, "text/html", content);
        Serial.println(USERNAME);
    }

    server.on("/", handleRoot);

    server.on("/inline", [](){
        server.send(200, "text/plain", "this works as well");
    });

    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
}

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

When I compile it, it says

'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.

@jwpat7 This code is (in most of its part) took from other examples from libraries and I am not (very) good at this so I can't figure out what do you mean by corecting it.

Possibly  Lambda of a lambda : the function is not captured will be more useful than my previous comment.

And that would be used here like : " server.on("/led" , content{..... " ?

Something like that -- But I'm not familiar enough with C++ lambda syntax to say, perhaps someone else will know.

Ok , I am not in a hurry anyway. Many thanks !

Let's look at a simpler example:
void setup ()
{
  String content = "Basic";

  attachInterrupt (digitalPinToInterrupt (2),
                   []()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

This gives the error:
/tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
sketch_jan25a:8: error: 'content' is not captured
     Serial.println(content);

Why? Because you are using a local variable content in a lambda function which runs at global scope. That is, content is not available to it, because it is inside setup.
To capture it, you can put it in the capture list:
  attachInterrupt (digitalPinToInterrupt (2),
                   [content]()  // capture content

However I found that my example doesn't compile even then.

I think the reason for that can be found here: Lambda Functions in C++11 - the Definitive Guide

How are Lambda Closures Implemented?
So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to attachInterrupt because there is a hidden *this variable that needs to be passed to class instances, and ISRs don't do that.
Now your example isn't an ISR, but probably the same remarks apply.

I don't think there is an enormous amount of point of using lambda functions here. If you must, move content inside the lambda, since that is where you are using it.
Or failing that, make it global scope.

The closest I could get to something that compiled was:
void setup ()
{
  const int content = 42;

  attachInterrupt (digitalPinToInterrupt (2),
                   [=]()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

Honestly though, I think using lambda functions here just makes your code obscure.

I wrote led instead of lcd. What I am trying to do is : calling a page from the esp8266 that gives me an input box and a submit button. I want to print on the lcd what is written in that box.

Thanks , it solved my error , but , now I have another one : 'void setup()':
lcdWirelessPrint:69: error: expected ')' before 'server'
server.on("/", handleRoot);
^
exit status 1
'User' was not declared in this scope
Another question is , how/where do I declare the name of the variable that I want to have the name of the input .

This sounds like a different question. I suggest you start a new question and post this new code.

Ok , I didn't wanted to open too many , thought it would be anoying.

Are you looking at the last compiler error ? The first one is the most most important one. In the preferences, the compiler output can be turned on to show more. Then scroll up to see the first compiler error. The compiler has troubles with the `` at the very end of your sketch.

They are normal " , they changed when I pasted here. I'll check it tomorrow anyway.

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


text:
Error: "invalid use of non-static member function" while calling a function from my own class-method
I'm having a bad time trying to call a correctly-working expression (ultra[currentSensor].ping_timer(echoCheck)) from an own class method (myclass::run) instead of from void loop().
I'm getting the following compiler error:
"invalid use of non-static member function".
If I call ultra[currentSensor].ping_timer(echoCheck) directly from void loop() it gives me no error, so I may be missing something.
Here's the (shortened) piece of code which is generating the error:
#include <NewPing.h>

#define ULTRA_NUM      3
#define MAX_DISTANCE 200

class myclass {
  public:

    void run();
    void echoCheck();

    unsigned int distance[ULTRA_NUM];
    uint8_t currentSensor = 0;
};

NewPing ultra[ULTRA_NUM] = {
  NewPing(4, 5, MAX_DISTANCE),
  NewPing(6, 7, MAX_DISTANCE),
  NewPing(8, 9, MAX_DISTANCE)
};

void myclass::run() {
// ....
      ultra[currentSensor].ping_timer(echoCheck);  // Compiler error
  }

void myclass::echoCheck() {
  if (ultra[currentSensor].check_timer())
    distance[currentSensor] = ultra[currentSensor].ping_result
}

ping_timer() is defined as it follows:
void NewPing::ping_timer(void (*userFunc)(void), unsigned int max_cm_distance) {
    if (max_cm_distance > 0) set_max_distance(max_cm_distance);

    if (!ping_trigger()) return;
    timer_us(ECHO_TIMER_FREQ, userFunc);
}

I hope any of you can help me!
Thanks in advance,
Eduardo

Edit:
What I am trying to do is to adapt this example (from NewPing Arduino Library) so that the sonar ping (sonar[currentSensor].ping_timer(echoCheck)) is done from a class method, and not from void loop().

This might help. There is a discussion about calling a class function from an ISR.

The problem is that echo_check isn't void echo_check() but void echo_check(myclass *this) because it's a member function of a class.
You can make the whole thing static (along with run()) by:
class myclass {
    public:
        static void run();
        static void echo_check();
};

static void myclass::run() {
    ....
}

void myclass::echo_check() {
    ....
}

And then you call:
myclass::run();

instead of instantiating an object.

mm seems to solve the problem, but I'm getting now compiler errors wherever the class members are used (and also inside the class definition): "invalid use of member 'Ultrabot::_xxxxxxx' in static member function"

A static function can only call other static functions or global normal functions, or functions of other classes that are defined as static members.

So now I have compiling functions which can't make what they are supposed to? :/

I don't know since you never bothered to show us your real code, only some tiny snippet.

It's not about bothering to do it or not, it's about trying not to bother you with all my partially built code. I hope it's more clear now with the edit.

Well, the answer I gave addresses the question you asked. Since that then breaks unspecified code in some unspecified way then I cannot help you further.

The edit doesn't make anything any clearer at all, no. That is precisely what I assumed you were doing. You need to either re-work your code so it can be all static, or re-work NewPing so it can accept the right kind of function as a callback and not have any of it static. Take your pick.

Solved:
I moved the event handler out of the class, and made it static void.
Then the code compiled properly
D

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


text:
Moving average sticks in fictitious zeroes for the first readings. This delays accuracy
My 9/10 Moving Average inserts zeroes for the first 9 readings. For example, if the first voltage reading is 100, the first moving average given is 10. That is the average of 9 zeroes and one 100. How can I get the moving average to only use actual readings from the adc? Or how can I get the moving average to wait until at least 10 readings are finished before starting its calculations?
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262; // class

float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  volatile int i, data;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) {
    // monitor Data   ready(DRDY pin)
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // read 6 bytes conversion register
    Responsebyte = true;
  }
  if(Responsebyte == true) {
    for(i = 0; i <5; i++) {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }
  if(SPI_RX_Buff_Count >= 5) {
    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];
    // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];
    uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|        ads1262_rx_Data[3]);
    //get the raw 32-bit adc count out by shifting
    sads1262Count = (signed long) (uads1262Count);
    // get signed value
    resolution = (double)((double)VREF/pow(2,31));
    //resolution=  Vref/(2^n-1) , Vref=2.5, n=no of bits
    volt_V = (resolution)*(float)sads1262Count;
    // voltage = resolution * adc count
    MovingAverage = (9*MovingAverage + volt_V)/10;
    Serial.print(MovingAverage,8);
  }
  SPI_RX_Buff_Count = 0;
}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Why are almost all variables volatile? Why do you have two variables called i (one global and one in loop)?

There are essentially two ways of initializing a low pass filter. The
first is to let it initialize itself “naturally” by feeding it data
until it reaches its steady state. This is the approach of jwpat7's
answer, and it works really well with FIR filters, like a plain
moving average.
Your exponentially-weighted moving average, however, is an
IIR filter. Given constant input, it converges asymptotically to its
steady state. After feeding it 10 values, it will only have reached 65%
of the steady state (exactly 1 − 0.910), thus you
may want to feed it significantly more than 10 points. E.g., you should
give it 22 points if you want it to be 90% initialized.
The other approach is to provision a specific initialization procedure
that sets the internal state of the filter to what it would have been
had it processed an infinite stream of constant values. This is actually
really easy to do with this particular filter, as we only have to set
the output equal to its first input. Here is the self-initializing
filter written as a function (this keeps the code cleaner):
static float movingAverage(float x)
{
  static bool initialized;
  static float output;

  // Initialize the filter as if this input had been on forever.
  if (!initialized) {
    output = x;
    initialized = true;
  }

  output += 0.1 * (x - output);
  return output;
}

You loose the benefit of the averaging on the very first data points,
but in return you have a simple to use self-initializing filter.
Unrelated to your question, I looked at your code and fond so many
confusing and useless statements that I felt compelled to remove all
that cruft. I did not test the simplified version though:
#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

static float movingAverage(float x) { ... }  // as before

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                      | (uint32_t) buffer[2] << 16
                      | (uint32_t) buffer[3] <<  8
                      | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(movingAverage(voltage), 8);
}

Thank you Edgar, your simplified codes works fine. I'm obviously no expert on coding. The lesson on filters is very interesting. I'm still playing around with what will work best with this weigh scale project. I plan to try a precision voltage reference instead of the Arduino 5 volt source. I know there is a method of connecting the B+ to other adc inputs and checking B+ continuously to achieve more stability and precision. I'll probably be back to this forum again, this is great!

Edgar, could you please show me how to slow the sample rate in your simplified sketch?

@Rico: Simplest thing would be to add a delay() in loop(). Cleaner would be to conditionally take the samples, on the condition “it's time to do so”. The approach is clearly explained in the Blink Without Delay Arduino tutorial.

Perhaps the easiest way to take in at least 10 readings before beginning to output results is to set a counter to 10 and count it down, as illustrated in following code.
byte startup=10;
void loop() {
  stuff_to_await_DRDY_and_compute_volt_V();
  MovingAverage = (9*MovingAverage + volt_V)/10;
  if (startup)
    --startup;  // Don't use MovingAverage during startup cycles
  else {        // Now we are done with startup...
    Serial.print(MovingAverage,8);
    other_stuff_with_new_data();
  }
}

As hinted at in a comment to the question, declaring all your variables volatile isn't necessary.  You should declare variables that are shared between threads, or between an ISR and loop(), volatile, but to declare other variables as volatile is in general a coding-style error that will confuse whoever maintains the code.  Spurious volatile declarations also may increase code size slightly, as it prevents one-time evaluation of expressions that are used exactly the same way multiple times, and it prevents code motion like moving constant expressions out of loops.
The following code rewrites severak parts of your sketch.  It uses some pointer arithmetic to avoid the tedious assignments and shifting found in your code.  It removes several extraneous casts because many of the type promotions and conversions coerced by your casts happen automatically anyway.  This code has not been tested; if it has problems, please point them out and I'll edit accordingly.
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>
#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)
ads1262 PC_ADS1262; // class
float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
byte SPI_RX_Buff[10];
byte SPI_RX_Buff_Count = 0;
char *SPI_RX_Buff_Ptr;
void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

byte startup=10;
void loop() {
  double resolution;
  long *ads1262Count;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) { // Is data ready?
    resolution = (double)VREF/pow(2,31);  // Vref/(2^n-1), Vref=2.5
    // Get address of 6-byte conversion-data buffer
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // Copy address of SPI_RX_Buff_Ptr[1] to ads1262Count
    ads1262Count = SPI_RX_Buff_Ptr+1;
    // Dereference ads1262Count pointer to get 4-byte signed value
    volt_V = *ads1262Count * resolution;
    MovingAverage = (9*MovingAverage + volt_V)/10;
    if (startup)
      --startup; // Don't use MovingAverage during startup cycles
    else {       // Now we are done with startup...
      Serial.print(MovingAverage,8);
      other_stuff_with_new_data();
    }
  }
  SPI_RX_Buff_Count = 0;
}

You do need to move the bytes around: according to the OP's code, the ads1262_Read_Data() method returns the data MSB first, whereas the Uno stores numbers in memory LSB first.

Thank you, your counter method works fine. The lesson on volatiles is very helpful also. I tried your trimmed down code, it showed an error with the void loop line, "ads1262Count = SPI_RX_Buff_Ptr+1;" and the error was "cannot convert 'char*' to 'long int*' in assignment".

@rico, I forgot to cast it ... s.b. ads1262Count = (long int*)(SPI_RX_Buff_Ptr+1); instead.  However, if Edgar Bonet is correct about byte order, copying the bytes is needed anyway.  Will edit answer if I get a chance to check.

The simplest method is just to go "I have only taken one reading, therefore I only need to look at one reading".  I.e., after your first reading you have 100/1. After your second reading you have (100+100)/2. After your 3726482374th reading you have (100+100+100+100+100+100+100+100+100+100)/10.
I have a fully templated library that works in exactly that way - it returns the rolling average (amongst other things) of only the samples you have actually fed it.

https://github.com/MajenkoLibraries/Average


text:
I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module
I can send AT commands to the ESP8266 - 01 but I am not able to upload the sketch.
I have connected TX-RX of module to TX-RX of Arduino, GND to GND, CH_PD, RST and VCC to 3.3V.
Here is the code I'm trying to upload -
#include <ESP8266WiFi.h>

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

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
    Serial.println("Connected to ");
    Serial.println(ssid);
  }
}

void loop() {
  Serial.println("Hello, Internet");
  delay(1000);
  Serial.println("IP Address");
  Serial.println(WiFi.localIP());
  delay(2000);
}

Here is the error I am getting.
Arduino: 1.8.1 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 225921 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 31864 bytes (38%) of dynamic memory, leaving 50056 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Please suggest something.

In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.
(I have a push button attached to my proto board for this purpose.)

Every implementation that I've seen connects TX->RX & RX->TX when going between devices. :)


text:
Can't able to detect Square wave from 74HC14
In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.
For that, I made Square wave with help of Arduino.
Here, it's code.
int kPinSqrOut = 13;

void setup()
{
   pinMode(kPinSqrOut, OUTPUT);
}

void loop()
{
  digitalWrite(kPinSqrOut, HIGH);
  delay(1000);
  digitalWrite(kPinSqrOut, LOW);
  delay(2000);

}
This is just simple HIGH and LOW one pin of arduino and we get Square wave.
Oscilloscope output :

Now based on this, I'm getting Square wave which length can be able to vary.
Here, it's code.
const uint8_t button_pin = 2;
const uint8_t kPin = 3;

void setup()
{
   pinMode(button_pin, INPUT_PULLUP);
   pinMode(kPin, OUTPUT);
   Serial.begin(9600);
}

void loop()
{
   static int last_button_state = LOW;
   static unsigned int push_count;
   static unsigned long last_press_time;
   int button_state = digitalRead(button_pin);
   unsigned long now = millis();

  // Record when the button is pressed.
  if(last_button_state == LOW && button_state == HIGH)
  {
    push_count++;
    last_press_time = now;

    digitalWrite(kPin, HIGH);
    delay(20);
    digitalWrite(kPin, LOW);
  }

  // Report when the button is released.
  if(last_button_state == HIGH && button_state == LOW)
  {
    unsigned long push_duration = now - last_press_time;
    if (push_duration < 10)   // discard bounce
    {
        push_count--;
    }
    else
    {
       Serial.print(F("pushes: "));
       Serial.print(push_count);
       Serial.print(F(", duration: "));
       Serial.print(push_duration);
       Serial.println(F(" ms"));
    }
  }

  last_button_state = button_state;
}

And Serial Monitor output :
pushes: 1,    duration: 1001
pushes: 2,    duration: 1000
pushes: 3,    duration: 1001
pushes: 4,    duration: 1002
pushes: 5,    duration: 1001

ve
So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.
Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.
Oscilloscope output :

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.
Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

So, give me some suggestion.

The main thing that's different between your two signals is the frequency. An incredibly low frequency signal works. A higher frequency signal doesn't. Maybe that's a clue to your problem? Maybe you should look at frequency counting and duty cycle measurement techniques that don't use digitalRead().

Oh, and using delay() in generating your output waveform is going to kill the reading of the input waveform completely.

@Majenko Ok, that means I have to replace delay() with something else which work same like delay means provide square wave with desired ms.

Personally I would use either interrupts or Input Capture to measure the incoming duty cycle in the background, and also write a non-blocking square wave output routine using millis() (or micros() if you want faster).

@Majenko Yes, I think that is also one solution. Just using interrupt, detect HIGH state of Square wave and when it detect just write non-blocking square wave output using millis() because I need readings on milliseconds. Thanks for this suggestion, let me try it out.

For your code use of Interrupt will solve your problem.

The only issue in your code is due to the delay in the pin control. You can solve it this way:
void loop()
{
    static int last_button_state = LOW;
    static unsigned int push_count;
    static unsigned long last_press_time;
    static bool kPinPressed = false;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if(last_button_state == LOW && button_state == HIGH)
    {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        kPinPressed = true;
    }

    if ((kPinPressed) && ((now - last_press_time) >= 20))
    {
        digitalWrite(kPin, LOW);
        kPinPressed = false;
    }

    ...
}

So you turn on the output, then after 20ms you turn it off.
There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?
And most important... What is the time scale? Is it really 10ms/div?

In last picture, Lower one waveform mean yellow trace is RPM waveform from auto rickshaw. And Upper one mean pink trace is waveform which filter out by RC circuit & passed through 74HC14. So as an output from 74HC14, I got this pink trace mean upper one waveform.

I think may be some noise present on that. That's why.

In serial interface, the reading you see is length of square wave which is generated by arduino. Length is in ms.

10 ms/ div ? I can't understand what this mean.

@Hasan ok, so there is an RC + 74HC14. Show the actual circuit, and please show also WHAT you expect from as output and what you get

Your code. Is designed to work with slow inputs and you are feeding it a much faster input than it can handle.
Solution 1. Use interrupts.
Solution 2. Speed up the main loop execution if you insist on polling.


text:
Confusion on array definition at Arduino website
See the below explanation about Arrays from Arduino's official site:

Creating (Declaring) an Array
All of the methods below are valid ways to create (declare) an array.
  int myInts[6];
  int myPins[] = {2, 4, 8, 3, 6};
  int mySensVals[6] = {2, 4, -8, 3, 2};
  char message[6] = "hello";

You can declare an array without initializing it as in myInts.
In myPins we declare an array without explicitly choosing a size. The
  compiler counts the elements and creates an array of the appropriate
  size.
Finally you can both initialize and size your array, as in mySensVals.
  Note that when declaring an array of type char, one more element than
  your initialization is required, to hold the required null character.

I have the following problems to understand:

Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.
Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

The last sentence answers your second question.

1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.

So "hello" is actually "hello\0".

You wrote "So "hello" is actually "hello\0". This \0 also is required in C or only in Arduino?

It's standard C. The only thing that Arduino provides is advanced helper functions and macros such as digitalWrite(). EVERYTHING else is either C or C++. Arduino does not have its own language. It is merely a library.

So you mean in plain C if I declare: char message[5] = "hello";  Is this wrong? since there is \0 at the end? If so strange that I never noticed this before.

Yes, that is wrong. That would end up with functions like Serial.print() failing and printing lots of junk.

By convention, in C, character strings (not "String" objects) are terminate with a \0. \0 is not otherwise a valid character, so it is used to mark the end of the text. The alternative is that you'd always have to pass not only the string, but it's length as well, which gets cumbersome and is an opportunity to make errors.

To be clear, it's a convention that is imposed by the standard C library (in that all functions that work with strings expect it), and is supported by the compiler (in that it will terminate string literals with NULL while compiling for you).


text:
Run 2 loops side by side
Let's say I have 2 loops LED() and IR() with a print statement in my Arduino loop() function. Basically I want my IR() loop to be always running so that at any point in time I provide a signal to the receiver, it will print something. I currently can only run LED() first and then once LED() is finished, only then the IR() will run. So if I send a signal let's say while LED() is running, nothing is showing up. Thanks!
EDIT: Updated with code
void loop() {
  single_Check(); // delay of 500ms
  if (irrecv.decode(&results)) {   //IR code
     Serial.println(results.value, HEX);
     irrecv.resume();
  }
}

The single_check() function basically turns on 6 LED one by one and check the voltage of the LED and prints them out. However, this code takes time to finish because I put in delay(500). So only after 500ms, the IR code will run.

Run the functions one after the other. If they are fast enough, you should be fine. If they are not, you are probably doing something wrong, (using delay() maybe? Seen Blink Without Delay?).

Maybe you should look into interrupt timer and set to timers for LED and IR http://www.instructables.com/id/Arduino-Timer-Interrupts/

You could use a scheduler and run the 2 loops; https://github.com/mikaelpatel/Arduino-Scheduler

The updated question essentially contains the answer to your problem: you are using delay(). Solution: read the Blink Without Delay tutorial (did you notice I linked to it in my first comment?), then rewrite single_Check() without delay().

Run 2 loops side by side easy: have two arduino, each loaded with one of the loops. put the two arduino side by side and turn on the power. done.

Arduino and like Arduino hardware run only a sequential Flow, Because they usually have only one core.
For running 2 loops side-by-side you have some solutions.

A flow to test flags and execute specific code.
Use a timer
Use a RealTime OS, like FreeRTOS

try never use delay

Your outer loop needs to only decide whether the IR or the LED needs service. If/when one of them does, call a function that services that device. The service functions should be brief and without delay() calls.
If a service function needs to do something/delay/do something else, it should do it by parts; only do the first something and let the main loop decide when it is time to do the something-else.
If this is all you are doing - two devices and their service routines, you may not need anything more. If you need to extending this to n-devices with n or more service routines, and the servicing is time-based (such as the LED probably is), look the SimpleTimer library. Then your outer loop would only call the timers' .run() function frequently, and the timers routine would take care of calling each service routine when necessary.
You'll probably end up with something like:
SimpleTimer Timers;  // set of timers

void setup(){
   // some set-up stuff here
   Timers.setInterval(long 10L, LedService);  // call LedService 100x/sec
}

void loop(){
   Timers.run();
   if( IRTest() )
      IRService();
}

void LedService(void){
   // manage LED here
}

bool IRTest(void){
   // return true if IR needs service
   // or false otherwise
}

void IRService(void){
   // manage IR sensor here
}

On Arduino (and on most other micro controllers for what it matters) you CANNOT do two things at the exact same time, so forget about running two loops in principle.
What you can do is: run two separate piece of code one after the other, fast enough that they look to be running in parallel or run one continuously and run the other when an event occurs.
In your case the first option is not applicable, so you have to revert to the second option and you are lucky because the event we are talking about is actually handled by the Arduino MCU pretty well: it is called an interrupt.
Arduino Uno (actually the MCU at its core, the ATMega328) is capable of handling interrupts on pins 2 and 3 (so you can have 2 interrupt routines attached at the same time).
Using interrupts you can have a piece of code (the IR related part) being enabled only when pin 2 goes LOW (or HIGH).
BEWARE though and use interrupts in the proper way: millis() does NOT work within an interrupt routine and also nothing else will be enabled while executing the interrupt routing, including counting time (that's the reason millis() does not work).
The latter part practically means you should limit your interrupt routine to capture the IR code and return, having the printing being done within the loop() function whenever the IR has been decoded.
Hoping all that makes sense to you, here are some references:
interrupts()
Interrupts
attachInterrupt()

millis() does work inside an ISR, you should just not expect it to increment. Which doesn't matter, because you would never write an ISR that takes a full millisecond to run anyway.

@EdgarBonet well, if millis() keeps returning the same value I wouldn't say it does work, at least functionally speaking, but you are right nonetheless: it technically works but it doesn't report any change. About ISRs, I have seen code using delay() within ISRs, so don't put any limit on the misuse of interrupt routines :-D