text:
Arduino Mega Serial2 seems to stop functioning mid-sketch
thanks in advance for the advice.
I've got an Arduino Mega talking to a Cavro XL-3000 pump. After a lot of time I got the arduino successfully controlling the Cavro. However, the big problem I have now is after my Mega sends about a dozen commands, communication breaks down between the two. The Arduino sends commands and gets no response back from the Cavro. I've written code that, when the Arduino gets no response, it tries twice more before terminating the program.
For a while I thought the problem to be pump related. After all, my test code (the vast majority of my code is in a library I created to have the Mega talk to the Cavro pump) simply tells it to move the Cavro between two different positions interminably. But when I reset my arduino, it starts working again. Not when I reset the pump.
Finally, I hooked my logic analyzer up. It turns out that, when I get no response from the pump, it's because no command is reaching the Cavro. I am definitely successfully creating a command packet and sending it using Serial2.write(packet,packet_length).  And though the Arduino is calling these lines of code and thinks data is going out, nothing is actually going out on the TX line. It's like Serial2 gets tired after about a dozen calls and stops shifting out data even though I'm calling Serial2.write.
I'm pretty stumped. I'm clearing the receive buffer after each response, so no overflow there. Each time I send a command I wait until it is fully shifted out before moving on, so no overflow on the write buffer either. If I get no response back from the pump I try two more times. On the last try, I shut down Serial2, begin it again, and wait until it is connected (while(!=Serial2)). But even after I do all this, Serial2.write isn't actually sending out data. My logic analyzer isn't picking anything up.
A simple reset of the Arduino and commands are actually going out again. Logic analyzer picks them up immediately. After about a dozen or so commands (it seems fairly random but never lasts very long), the same thing happens. I swapped out Arduino megas and the same thing occured.
So.

It seems to be a code issue (repeatable on multiple arduino megas)
It does not seem to concern the pump or the rs232 converter
A push of the reset button fixes it temporarily
My logic analyzer snoops in between the arduino and rs232 converter.
Serial2.write(packet, packet-length) is definitely being called.
I have no idea what's happening.

Here is a schematic. Any advice would be appreciated!

Here is my test code:
#include <Hydro.h>

Hydro pump;
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pump.InitComm(0,true,"right");
  Serial.println("Communication initialized");
  delay(5000);
}

void loop() {
//  Serial2.begin(9600);
  //long mil = millis() - 10000;
//while(true){
  //if(millis() > mil + 10000){
    //Serial.println("Sending command...");

    //byte datastuff[10]={0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27};
    //Serial2.write(datastuff,10);
    //Serial.println("Sending command...ONE");
    pump.AbsoluteMove(0,4000);
    delay(10000);
    //Serial.println("Sending command...2");
    pump.AbsoluteMove(0,9000);
    delay(10000);
    //Serial2.write(new byte[10] {0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27}, HEX);
    //mil = millis();
}

Here is my library.
/*
Hydro.c - Library created for OEM communication with Cavro XL-3000 Pump.

11/23/2016
Written for Mega using Serial2, can we tweaked.
*/

#include "Arduino.h"
#include "Hydro.h"

Hydro::Hydro(void){}

const byte LineSynch = 0xFF;
const byte StartByte = 0x02;
byte seq = 0x31; //confirm this
const byte ETX = 0x03;
const byte EX = 0x52;
int length_total = 0;

//Initializes communication and then sets it to Fine (12000 steps) Control.
void Hydro::InitComm(int addr, boolean fc, String initdir){
    Serial2.begin(9600);
    Initialize(addr,initdir);
    delay(2000);
    FineControl(addr,fc);
}

//Top Level Send Command. First Queries the pump to make sure it's ready for a command.
//If Pump is ready, passes along actual command to MidCommand.
void Hydro::SendCommand(int addr, String command){
    byte status = Query(0);
    while(status==false){
        Serial.println("Query: Stat Error: Wait till Pump No Longer Busy.");
        delay(10000);
        status = Query(0);
    }
    Serial.println("Query: Pump Not Busy.");
    MidCommand(addr, command);
    ReadData(false);

}

//Executes the actual command by calling command.
//If no response received (command != true), tries again twice.
void Hydro::MidCommand(int addr, String command){
    bool response = Command(addr, command);
    if (response == true){}
    else if (response == false){
        //resend
        Serial.println("Command Failed. Resending.");
        bool response2 = Command(addr, command);
        if (response2 == false){
            //shut off
            Serial.println("Second Command Failed.");
            Serial2.end();
            delay(2000);
            Serial2.begin(9600);
            while (!Serial2){
                Serial.println("Waiting for S2 to Connect.");
                delay(1000);
            }
            Serial.println("Connected.");

            bool response3 = Command(addr, command);
            if (response3 == false){
                Serial.println("Final Command Failed.");
                while(true){}
            }
        }
    }
}

//Send a Command.
//Returns True if a response is received from the pump.
bool Hydro::Command(int addr, String command){
    command.concat("R");
    byte address = 0x31+ addr;
    int length = command.length()+1;
    byte dat[length];

    Serial.print("Command: The string command is: ");
    Serial.println(command);
    command.getBytes(dat,length);

    //Serial.println("Data----");
    //for (int i = 0; i < length; i++){
        //Serial.print("i equals: ");
        //Serial.println(i);
        //Serial.println(dat[i], HEX);
    //}
    //Serial.println("----");
    //Serial.print("Dat Length is: ");
    //Serial.println(length);

    //line sync, stx, add, seq, etc, checksum. 6. 6 + (length.data) == length.
    //Decided to ignore Line Sync. Pump seems to have no problem without it. So 5+length.data.
    length_total=5+(length-1);
    byte packet[length_total];
    int p = 0;

    //packet[p++] = LineSynch;
    packet[p++] = StartByte;
    packet[p++] = address;
    packet[p++] = seq;

    for (int i = 0; i<(length-1); i++){
        //Serial.print("i equals: ");
        //Serial.print(i);
        packet[p++] = dat[i];
        //Serial.print(".  Inserting Data: ");
        //Serial.println(dat[i], HEX);
    }

    packet[p++] = ETX;
    byte checksum = StartByte;

    for (int i = 1; i<length_total-1; i++){
        checksum = checksum^packet[i];
    }
    packet[p++] = checksum;
    int x = Serial2.write(packet,length_total);
    Serial.print("bytes written: ");
    Serial.println(x);
    seq++;

    //print out packet to verify.
    Serial.println("Packet----");
    for (int i = 0; i < length_total; i++){
        Serial.println(packet[i], HEX);
    }
    Serial.println("----");

    //Waits for packet to be fully shifted out.
    //Serial.flush could be used instead.
    while(Serial2.availableForWrite() != 63){
        Serial.println("Command: Waiting to finish sending command...");
        delay(1000);
    }
    Serial.println("Command: Finished Sending.");

    unsigned long time = millis();

    //looks for a response from the pump.
    //returns true if received.
    while(Serial2.available()==0){
        Serial.println("Waiting for Response...");
        delay(1000);
        if (millis() > (time+5000)){
            Serial.println("Resend Command.");
            return false;
            }
    }
    Serial.println("Command: Response Received.");
  return true;
}

//Both initialize at half force.
//Init with volve output to Right or Left.
void Hydro::Initialize(int addr, String dir){
    if (dir == "right"){SendCommand(addr,"Z1");}
    else if (dir == "left"){SendCommand(addr,"Y1");}
}

//If Fine Control is True (active), Resolution is 0-12000.
//Else If Fine Control is False (deactivate), 0-3000.
void Hydro::FineControl(int addr, boolean control){
    if (control==true){SendCommand(addr,"N1");}
    else if (control==false){SendCommand(addr,"N0");}
}

//See Fine Control for Integer Values
void Hydro::AbsoluteMove(int addr, int move){
    String mc = "A";
    mc.concat(move);
    SendCommand(addr,mc);
}

void Hydro::Execute(int addr){
    SendCommand(addr,"R");
}

//Sends a Query for Status.
//Returns true if Status byte is 60, ready for command.
bool Hydro::Query(int addr){
    MidCommand(addr,"Q");
    if ((ReadData(true)) != 0x60)return false;
    else return true;

}

//True to print out data, false to not.
//Grabs and returns the Status Byte.
byte Hydro::ReadData(bool print){
    byte status;
    int i=0;
    if (print == false){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
            }
            else Serial2.read();
            i++;
        }
    }

    else if (print == true){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading (s): ");
                Serial.println(status, HEX);
            }
            else {
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading: ");
                Serial.println(Serial2.read(), HEX);
            }

            i++;

        }

    }
    return status;
}

I'd start with moving string literals into the Flash memory. Who knows how much memory it uses.

I'm not a C++ guy, but I have looked at the code and fail to find where some of the index's are set to the proper values (whatever that is.) Some of it may occur during instantiation, but...  Most of these I've seen are index related (out of bounds), so.. As an example, the code sequence of
for (int i = 0; i < (length - 1); i++)
    packet[p++] = dat[i];

Seems to me, if the bytes (length) of 'dat' is 6 assuming 6 bytes, then the loop will run from 0 to 4.  That would seem to lose 2 bytes? Some of the array indexes are difficult to track for their value, not knowing what you were thinking.
My suggestion is
1.) ensure indexes stay within bounds
2.) ensure every function call (related to problem) is checked for it's expected return status
3.) attempt to ascertain the number of operations that occur before failure.  This may give you a clue about indexes or lead to discover of other problems.
I don't think you have a hardware problem. Intermittent hardware doesn't do this either. This is a software bug, and it's sounds repeatable. Step three may be useful.
Best of luck :)

Difficult to say, but if your last trace is "Final Command Failed." , you are probably stuck in the following infinite loop.
if (response3 == false){
    Serial.println("Final Command Failed.");
    while(true){}
}

as @Jack says, you might as well have problems with your bound arrays. You have a lot of "length+1, length-1" scattered everywhere, this is really hard to follow.


text:
RF24 communication between Leonardo and Micro not responding
I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.
I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.
Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?
Here are the sketches:
PS some additional channels are left to see what I expected from working sketch.
Receiver module:
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  while (radio.available()) {
    char theMessage[13];
     radio.read(&theMessage, 13);
     Serial.println(theMessage);
     if(theMessage == "testingsend"){
       //this is removed in nano
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
     }
  }
}

And the sender:
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openWritingPipe(addresses[channel]);
}

void loop() {
  // put your main code here, to run repeatedly:
  char theMessage[13] = "testingsend";
  radio.write(theMessage, sizeof(theMessage));
  memset(theMessage,0,sizeof(theMessage));
  delay(300);
}

Have you tried using the ICSP header on the Micro? Since it's unlikely that your code is the problem, try other combinations to pin-point the issue like, Leonardo-Nano and Micro-Nano.

Currently I test with micro-nano, changed pins on micro to ICSP and nothing happens. I'm reading about Leonardo/micro and i read that the SS pin works different but I don't know if it's issue here.

Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF

Where did you have a capacitor?

source: Stack Exchange

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

sort: votes


text:
GSM and NFC not working together
I have an Arduino Uno board, Seeed Studio NFC shield v2.1 and, an Arduino GSM shield stacked UNO -> NFC -> GSM, therefore, all the wires are going into pins in the GSM.
I have successfully created a program that measures various sensors on my attached breadboard and then prints them to serial and sends text depending on conditions. I have today added the NFC shield to the middle of the stack (so as to avoid unplugging all the pins in the GSM), now when I run any NFC program, the default ones provided on the serial I get the message "Didn't find PN53x board". However, if I unplug the GSM from on top of it the NFC programs run fine, reading and writing tags.
Is it just that the NFC and GSM will not work together or am I missing something.
Main code
// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

int buttonPin = 13;
int buttonState = 0;
int buttonPressed = 0;
int trigPin = 11;
int echoPin = 12;
long duration, cm, inches;
int greenLED = 6;
int redLED = 8;
int buzzerPin = 10;

int pressurePin = A5;
int force;

const int inputPin = A0;
unsigned int inputSample;
const int inputWindow = 100;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(inputPin, INPUT);
  startUp();
  //setupText();

}

void loop() {
  button();
  delay(100);
  if (buttonPressed == 1)
  {
    pressure();
  }
  else if (buttonPressed == 2)
  {
    distance();
  }
  else if (buttonPressed == 3)
  {
    sound();
  }
  else if (buttonPressed == 4)
  {
    pressure();
    distance();
    sound();
  }
}

void sound()
{
  // two variables for minimum and maximum values in window
  unsigned int inputMax = 0;
  unsigned int inputMin = 1024;

  // loop for the window
  for (unsigned int i = 0; i < inputWindow; i++)
  {
    // read in a single value
    inputSample = analogRead(inputPin);
    // get the minimum and maximum value
    inputMin = min(inputMin, inputSample);
    inputMax = max(inputMax, inputSample);
  }
  // send the values on serial
  Serial.print("Min: ");
  Serial.print(inputMin);
  Serial.print("  Max: ");
  Serial.print(inputMax);
  Serial.print("  Diff: ");
  int Diff = inputMax - inputMin;
  Serial.print(Diff);
  Serial.println();
  if (Diff > 30)
  {
    alarm();
    sendText();
  }
  delay(250);
}

void pressure()
{
  force = analogRead(pressurePin);
  Serial.print("The force is: ");
  Serial.println(force);
  delay(250);
  if (force > 400)
  {
    alarm();
    sendText();
  }
}

void distance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  int echo = pulseIn(echoPin, HIGH);
  int trig = pulseIn(trigPin, HIGH);
  Serial.println(duration);
  Serial.println(echo);
  Serial.println(trig);
  cm = (duration/2) / 29.1;
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(100);
  if (cm < 5)
  {
    alarm();
    sendText();
  }
}

void alarm()
{
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
}

void button()
{

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH)
  {
    buttonPressed ++;
    digitalWrite(greenLED, HIGH);
    noise();
    delay(2000);
    digitalWrite(greenLED, LOW);

  }

  Serial.println(buttonPressed);
}

void startUp()
{
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  loop();
}

void noise()
{
  tone(buzzerPin, 1000);
  delay(1000);
  noTone(buzzerPin);
}

void sendText()
{
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("MESSAGE SENT");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    delay(4000);
//  char remoteNum[20];
//  Serial.println(remoteNum);
//  // sms text
//  char txtMsg[200];
//  Serial.println("SENDING");
//  Serial.println();
//  Serial.println("Message:");
//  Serial.println(txtMsg);
//
//  // send the message
//  sms.beginSMS("07123456789");
//  sms.print("HELP");
//  sms.endSMS();
//  Serial.println("\nCOMPLETE!\n");
}

void setupText()
{
  // initialize serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

Code to be added when at a later date
#include <SPI.h>
    #include "PN532_SPI.h"
    #include "PN532.h"
    #include "NfcAdapter.h"

    PN532_SPI interface(SPI, 10); // create a PN532 SPI interface with the SPI CS terminal located at digital pin 10
    NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object

    void setup() {
        Serial.begin(9600); // begin serial communication
        Serial.println("NDEF Reader");
        nfc.begin(); // begin NFC communication
    }

    void loop() {

        Serial.println("\nScan an NFC tag\n");
        if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
        {
            NfcTag tag = nfc.read(); // read the NFC tag into an object, nfc.read() returns an NfcTag object.
            tag.print(); // prints the NFC tags type, UID, and NDEF message (if available)
        }
        delay(2000); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
    }

Edit: Added code

What do you use for GSM / NFC - I2C mixed with SPI? Can you post the code?

I've had a quick google of I2C and SPI but don't fully understand them, to be honest with you, I have code reading a pressure sensor and reading an ultrasonic sensor then a separate sketch I intend to integrate into the first reading NFC tags. Apologies for the rubbish reply I'm very basic.

I have the Uno plugged into my mac via the serial port, then the NFC shield on top of that and the WiFi shield on top of that with the pins from the breadboard in it.

If you use I2C for NFC your nfc initialization will reflect that. I2C is IIRC a bus where each device is addressable 0, 1, 2, ... - haven't used SPI much. One thing about I2C I know is that one must keep the wires fairly short... <1m. Can you not share at least the init bits of your code?

Added the code, thanks. BTW all wires are extremely short < 10cm

That's SPI for the NFC. I don't know what the GSM uses. Try to use both with I2C. I used my PN532 in SPI mode, but switched to I2C to achieve less wire clutter. Is there a hardware conflict? I guesstimate you have something trying to use the same resource.

Why on earth are you calling loop() from startUp()?

Do you have "wires" plugged in to your breadboard "sensors" that connect to the same pins as the NFC shield? That is, D9-D13?

@Majenko I know that is poor practice, I did it while following what my code did during a debugging and haven't tidied it up since. In answer to your questions I have pins in D10, D11, D12 and D13.

You have a resource conflict between your breadboard sensors and the NFC shield.
int buttonPin = 13;    <= This is SCK
int trigPin = 11;      <= This is MOSI
int echoPin = 12;      <= This is MISO
int buzzerPin = 10;    <= This is chip select

You will have to use different pins for your sensors.

Majenko is in fact a cybernetic supercomputer comprised of a thousand chimpanzee brains, and several billion atmega368p's running on solar power in Area 51.

@user400344 Actually that's not entirely true any more. I replaced the several billion ATMega's with a single PIC32MZ. Next year I hope to start a big upgrade programme gradually replacing the chimpanzee brains with orangutan brains.

It is comforting that you're not a rasperry pi.

@user400344 I live in fear of being replaced by a small perl script...

Haha, perlNet will rule the earth and outlast humanity

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


text:
What programming practices should be adopted while coding sketches for Arduino?
What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?
From the link: https://www.arduino.cc/en/Products/Compare
I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.

First off, I'd consider NOT using Arduino library and directly use AVR C library, as Arduino adds a lot of code to simplify programming, but not necessary once you know AVR MCU. This is what I'm trying to achieve in https://github.com/jfpoilpret/fast-arduino-lib optimized library

Paul covered the most important points. This answer is intended to be a
complement to his.
First, you should keep in mind the general rules, which are more
important than the more specific ones. The general rule for saving RAM
is: be aware of what you are storing, and do not store anything you do
not really need. The general rule for saving flash is: be aware of what
you are doing, and do not do anything you do not really need.
Now, a few specific tips:
Use the const qualifier for declaring constants (e.g.
const int ledPin = 13;). The compiler will optimize-out the storage of
the constant and use immediate addressing instead.
Use PROGMEM for arrays of constants.
Whenever possible, use static memory (globals and static locals)
rather than heap allocation (malloc() and new). This will prevent
memory fragmentation and make the memory usage more predictable (only
the stack holds dynamic memory): you know at compile time, rather than
run time, whether you are low in RAM.
For the same reason, prefer C strings (char *) over String objects.
Use the C99 types int8_t and uint8_t whenever 8 bits are enough for
your integer variables.
Use the static qualifier for functions that will be used only in the
same source file, especially for functions that are called only from one
place. This gives the compiler more optimization opportunities.
If you need to optimize,
use avr-nm to know what is
consuming your precious RAM.

just out of curiosity @Edgar , is 'const int ledPin = 13' use the same memory size as const char ledPin = 13' ?

@dhimaspw: In my tests, yes, the size and the generated assembly are the same. In both cases, digitalWrite(ledPin, HIGH); compiles to ldi r22, 1 $ ldi r24, 13 $ call digitalWrite. Here, ldi means “load an immediate value into a register”, i.e. the value given as the second argument (1 for HIGH or 13 for ledPin) is part of the instruction itself.

Keep in mind that RAM is even less. 32KB is a fair lot of code, since C/C++ is highly efficient. "Don't save **** in RAM."
If you need to load images into a display, save the images on an SD card. And "stream" it to the display. You can read and transmit the bytes one by one, or 10 by 10 or something.
Also, if you need long strings, you can use the "flashStringHelper" to store the string in flash memory. For example: println(F(”Error message: Couldn't connect to server));. By using F() around the string, you save valuable bytes.
Not using Arduino code, but pure AVR-C/C++, can save you a little also. (Will also save the bootloader piece of memory, if you program directly with a programmer.)
If you use Arduino, know how it works. The Arduino serial library uses ~256 or 500 bytes (I believe) as a buffer. You can change this if you need it for other applications.
Keep in mind that your saving technique depends on what resources are low. If you need to do a lot simultaneously, it's better to write non-blocking code.
But also remember: Don't optimize unless it's actually needed! Or, actually set measurable and realistic requirements, optimizing something to be "as fast as possible" can take infinite amounts of time... Run a google search on "premature optimization" as the old folks in the field like to call it.

I agree with part premature optimisation is mother of all evils , I have read it before however the point of start looking into optimisation comes when you start seeing low memory warning while uploading to Arduino

@Ciastopiekarz That's complete nonsense, I am afraid. A mis-quote of a partial excerpt from a perfectly good quote. Good software design includes a certain level of optimization right from the start. What is "evil" is spending many man hours doing pointless micro-optimization of small bits of code. When that statement was first quoted "optimization" meant something completely different to what it does today, yet it is still erroneously spouted as a reason to not bother doing any optimization at all, and you end up with Windows applications.

Windows application

@Ciastopiekarz Have you ever noticed how things like Office run at about the same speed with a modern version on a 3GHz i7 as old versions ran on a 33MHz 486? They spread to fill the available space, but there hasn't been much change in functionality... Bloat is a blight. Interesting article: http://ubiquity.acm.org/article.cfm?id=1513451

@Ciastopiekarz If you share and explain your sketch (and the debug output, which states how many bytes have been used from what memory) we could try and point out where it could be optimized. Often, it's just the whole approach that is ineffective/inefficient.

Like using NeoPixels; to color them, you'll have to save the whole ledstrip in  RAM, using 3bytes per pixel. Which is a 3.000bytes for a 1000pixel strip. The library is heavily optimized, but it performs like sh*t and only causes issues on other platforms. But still they're heavily popular...

Using a ledstrip that can work with SPI, allows you to set the pixels one-by-one. So you can calculate what your next color will be inbetween setting the colors. Making nice rainbow effects with virtually endless amounts of pixels. And they're bound to work flawless on other architectures (Raspberry Pi, ESP8266) since they don't require strict timing. Using only one pin more to indicate the timing... they deserve more hype ;D
My point is; optimize where it makes sense. If something proves to be inefficient, you may check to replace it instead of spending hours of optimizing it.

Well,  my question is more in general, the reason is  while programming in python I am strictly trying to confine to PEP rules. And now just recently I have stepped in writing  Arduino sketch so I am wondering if there is something for Arduino programmers too

@Majenko I believe you maybe that's why they stopped IE and came with Edge , but its been I have used windows now

PEP rules don't really "optimize" code afaik. Arduino is based on C/C++, and there are an awfull lot of styleguides in C++. But you should pick one that matches your problem as well, the JSF C++ styleguide is very interesting, since it's aimed on military aviation and thus extremely strict. http://www.stroustrup.com/JSF-AV-rules.pdf but using it in an Arduino hobby project is a bit overkill ;) You can check through it, since it's rather interesting though.

Also, IMHO, now web developers also have to worry about Edge AND Internet Explorer, which isn't a very nice effect.
Majenko meant that, given better hardware, software is likely to get "worse" (optimized). Since the new Word versions run no faster on new PC's as the old versions did on old PC's.

@Paul  I will put a code review once I am done and share the link on this page


text:
How do I use the Arduino Mega as a 16-bit SPI slave?
I have to interface an Arduino Mega as a slave with a SPI master running at 1 MHz SCK. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in acc and return local data ret, which is simply an integer to be incremented every transaction.
However, while the master data is stored in acc (verified through serial output), the data returned to the master is not the value in ret. Instead, the first response byte is correct (MSB of ret) and the second response byte is just the first byte received by the Mega, which was the value already present in SPDR.
How do I send the second byte of ret as the second byte of the response? What am I doing wrong?
// SPI Slave

#include <SPI.h>

// return to master
volatile unsigned int ret;

// accept from master
volatile unsigned int acc;

// MSB/LSB indicator
volatile byte SB;

void setup(void)
{

  ret = 0;
  SB = 0;

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // set CPOL, CPHA modes
  // byte dataMode = 0;
  // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR << 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret >> 8;
  }
  SB = (SB + 1) & 0x01;

}

void loop(void)
{
  // interrupt processing only
}

Edit Changed SCK from 16 MHz to 1 MHz

Have you done the timing math yet?

I don't know which timing you're asking for. Are you saying that the ISR is too long?

I'm late to the party, but...
I experienced exactly the same issues having a Arduino Uno as a SPI slave communicating to a Arduino Mega as SPI master. My conclusion is that the slave must take some time to process the SPI transfer of the first byte (your code in the SPI interrupt handler), but the master is not waiting for it. So the transfer of the second byte starts before your handler is completely executed, so the master receives the same byte again.
In my case, I fixed this with an ugly sleep in the master before sending the second byte:
SPI.beginTransaction(spi_settings);
word input = 0;
digitalWrite(spi_devices[port].pin_ss, LOW);
input |= SPI.transfer(output >> 8) << 8;
delayMicroseconds(20); // Must give time to slave to read first byte
input |= SPI.transfer(output);
digitalWrite(spi_devices[port].pin_ss, HIGH);
SPI.endTransaction();

Not elegant, but it works.

You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

In SPI Slave mode, the control logic will sample the incoming signal
  of the SCK pin. To ensure correct sampling of the clock signal, the
  minimum low and high periods should be: Low period: longer than 2 CPU
  clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).
Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!

The master is running at 1 MHz. I'm sorry for the wrong info. Corrected the question.

Great! Now you need to show how you have verified the code. Please remember that Serial output in an ISR is not a very good idea.

I did use Serial output within the ISR for verification, but the final code is what I posted. The bytes returned to the master were extracted on the master side, which were the same in both cases with or without Serial.


text:
How does Arduino determine whether the given condition provided to it is true or false?
I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg:
if (someVariable > 50)
{
  // do something here
}

Then how does Arduino determine if the value that I put in `somevariable' is larger than 50 (as apposed to less than or equal to 50)?

It's not clear to me what you are asking.  Could you find another way to phrase it, please?  Do you want to know what machine instructions it uses to evaluate (someVariable > 50)?  Or something else?

In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.
In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.
If you are comparing A to B then you subtract B from A and see what happened by examining the flags.
For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.
If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.
If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (a > b is the same as !(a <= b) for instance).
Of course, some architectures have actual comparison instructions (often CMP) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

CPSE - Compare, Skip if Equal
CP - Compare
CPC - Compare with Carry
CPI - Compare Register with Immediate

CPI would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):
CPI $r3, 50

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

BRLT - Branch if the result of the previous comparison was A < B
BRLE - Branch if the result of the previous comparison was A <= B
BRGT - Branch if the result of the previous comparison was A > B
BRGE - Branch if the result of the previous comparison was A >= B
BREQ - Branch if the result of the previous comparison was A == B
BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons.  You can read up all about them in the AVR instruction set manual.

Just to complement Majenko's answer with an example, I tried the
following:
volatile int someVariable;
void do_something_here();

void foo()
{
    if (someVariable > 50)
    {
      do_something_here();
    }
}

and the compiler generated the following assembly (comments mine):
foo:
    lds r24, someVariable      ; load variable into registers, LSB
    lds r25, someVariable + 1  ; and MSB
    sbiw r24, 51               ; subtract 51
    brlt .L1                   ; if (result < 0) goto .L1
    jmp do_something_here      ; do_something_here()
.L1:
    ret                        ; return

The sbiw instruction means "subtract immediate from word". It
subtracts a 6-bit immediate value from a 16-bit value contained in a
register pair (r25:r24 in this case). It is one of the very few 16-bit
instructions of this mostly 8-bit CPU.
As you see, the compiler did some optimization and changed the code to
something looking more like:
if (!(someVariable - 51 < 0))
{
    do_something_here();
}

It is also worth noting that the brlt instruction (branch if lower
than) tests the sign flag of the status register, which is the exclusive
OR of the negative flag (result < 0) and the overflow flag. This way the
result of the comparison is correct even if the subtraction overflows.
Note also that this is only an example. The generated assembly would be
different if you use another type than int (a wider or smaller or
unsigned integer), or an explicit constant greater than 62.


text:
How to use breakpoints for debugging
Breakpoints are a great way to see how the compiler runs to your code. Now my question is, is there a possibility to use breakpoints when you debug your code?

As noted in Majenko's answer, the Arduino IDE doesn't provide a breakpoint  mechanism but Atmel Studio does support breakpoints.[*]
However, if you have a switch and an LED, you can track the progress of your program in a way that provides some of the benefits of breakpoints.  You would add a subroutine, say BPReport(), that via serial output or an LCD reports values of critical variables, then lights the LED and waits until the switch has been pressed and released, with debounce.  Call your BPReport() routine whereever you want an unconditional breakpoint.  For conditional breakpoints, you can have a routine BPReportIf(cond) which calls  BPReport() if cond is true.  If you don't want to output via serial, you might use several LEDs or an LCD, and you might use several switches if you want external break controls (for example, cond could be a test of one of the extra switches).
[*] Some hardware debuggers modify downloaded code each time breakpoints are added, changed, or removed.  That usage will wear out flash memory more rapidly than just occasionally downloading to it.  If a chip has been heavily used for such debugging, don't use that chip in a production system.

Though Majenko his answer is correct there are some other options.
As to the real hardware debugging as stated by majenko I would say:

Install and use a real IDE, such as Atmel Studio or the arduino eclipse plugin called sloeber (I'm author), and
Use a full hardware debugger or hardware that has it on board like the Arduio zero or hardware using other debugging technology like the ESP8266 that allows USB debugging

An other debugging option from a completely different category is to organize your code so that decision logic (hardware independent) and action (hardware dependent ) are completely separated.
Then compile your sketch as a local program and debug the "decision logic" on your local machine. This method does not allow for "hardware debugging". This method also enables unit testing.
Note that your local machine is probably a 32 or 64 bitter and most Arduino's are 8 bitters which will result in differences in data types which is an extra attention point when using this method.

The Arduino-Debug library provides a simple on-target debugger for Arduino sketches. Debug command are added directly to the sketch. A debugger command shell is started on break-points and assertions.

The screen-shot above shows the example sketch run on an Arduino Mega with Serial output monitor used by application and Serial1 used for the debugger shell.
Sketch Debug Commands

ASSERT(cond)     Check assert condition. If false the debug shell is
called. The sketch cannot continue.
BREAKPOINT()     The debug shell is called.
BREAK_IF(cond)   The debug
shell is called if the condition is true.
CHECK_STACK(room)    Check
that there is room (bytes) on the stack. If false the debug shell is
called.
DEBUG_STREAM(dev)    Use the given stream device for debug session. Typically Serial.
OBSERVE(expr)    Print the expression to the debug stream.
OBSERVE_IF(cond,expr)    Print the expression to the debug stream if
the condition is true.
REGISTER(var)    Register a variable for access
from the debug shell. Debug Shell Commands

Debug Shell Commands

?VARIABLE  Print variable address and value.
@VARIABLE  Print pointer variable address and reference value.
backtrace  Print simple call-stack.
commands   Print list of commands (see also help).
data   Print contents of data area, i.e. global variables.
go     Leave debug shell and continue execution of sketch.
heap   Print contents of heap, i.e. dynamic allocated data.
help   Print list of commands.
memory Print memory status.
quit   Stop sketch.
stack  Print contents of stack, i.e. call frames, arguments, return addresses.
variables  Print list of registered variables.
where  Print source code file and line where debug shell was called.

All debug shell commands can be abbreviated to single character commands. Please see the README for further details; installation details, example sketch and benchmarking.

Mikael's donated library lets you set conditional breakpoints, print variables' values, memory status, call traces, & examine-and-change variables at a breakpoint. Pro: Doesn't need hardware ($$), doesn't beat-up as hard on the Flash (as setting and removing breakpoints with a hardware debugger would). ....

.... Con: Higher impact on the program's code-space, some RAM space, & possibly run-time, if examining time-critical code; some learning curve to compile in (and later, remove) the library calls; the need to anticipate break-point locations or re-compile them in when you discover where you need them. The Cons are not a criticism of Mikael's work; they come with this technique.

@JRobert Nice Pro-Con summary! I have tried to address some of the Cons by allowing the debugger to be tailored. There is a set of defines that will allow footprint sensitive applications to reduce the debug shell to a minimum. As any debugger for embedded systems it is difficult to debug time critical (continuous) code with break-points. The only alternative is observation points. These could be optimized by using a trace buffer and remove serial output in time critical code.

Not in the Arduino IDE.
You need to:

Install and use a real IDE, such as Atmel Studio, and
Use a full hardware debugger

There is no provision for debugging through the UART/USB interface using the bootloader.


text:
Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors)
Reason for question:
My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!
Question:
What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?
Background on project:
The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.
We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.
https://en.wikipedia.org/wiki/Motherboard

"interface board" is perfectly fine terminology

On Arduino contexts, these are often called shields. I kinda dislike this, because every dev board tries to have its name (HATs, Capes, Shields, etc etc..).

Thanks for the quick responses. I spent at least 6 hours over 4 days reading articles and books for this info with no luck. After researching both terms (interface board and shield), they both seem to work good for our purpose. We will probably go with "Interface Board" just because it is easier to grasp (think marketing), although "Custom Shield" is probably more "correct" when specifically talking about Arduino. Thanks again!

No, "custom shield" is nowhere near correct.  In the terms of professional EE,  "custom shield" means something like this.  Don't fall for the cute marketing-to-amateurs slang.

I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.
The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.
Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?
I made up a radio-controlled car, see photo:

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.
This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.

Thanks. This answers my questions as noted by alex.forencich and wesleylee. Note although I agree with you that we should not get too caught up in the terminology (specially as hobbyist), this is for a judged science fair project where the research paper carries more weight than the built product, so having the correct terminology is crucial. I'll tell my son to call it an interface board and to find a peer reviewed reference from the library (these kids now a days even have to add doctoral references in all research - it's good, but insane at the same time). Thanks again.

In the Arduino ecosystem these boards are called 'shields'.
Arduino describes a shield as:

Shields are boards that can be plugged on top of the Arduino PCB
  extending its capabilities.

For example, there is an Arduino Motor Shield which sounds very similar in purpose to the board that your son is making.

"Interface board" works as a general term, as @alex had mentioned already.
The word "motherboard" would work if it's larger than each of the components that plug into it.
The word "daughter board" would work if it's smaller than what it plugs into.
Please don't use the word "shield" when referring to extension boards, interface boards, daughter boards, and such.  The word "shield" in this connection was popularized by Arduino marketing.  (More detailed discussion about "shield" in connection with Arduino.)

I didn't know this terminology had discussion about it. Makes sense that EEs dislike the term, it doesn't really mean anything.

Depending on what is being done, the claim here may be a highly erroneous rant.  If the board being designed plugs into the Arduino in the fashion of what are known as "shields" then that is the term that should be used since that is the term everyone recognized for such a board, regardless if they like the term or not.  If it has some other physical arrangement, use a descriptive term.  Ultimately, making such a board is probably a waste of money anyway - either hand wire it in the Arduino form factor, or replace the Arduino with a more compact and hence cheaper custom circuit.

@ChrisStratton Agreed. If you're specifically talking about a board that's made to plug into the Arduino pinout, calling it an "Arduino shield" is an excellent descriptive term.


text:
Alternative distance-meter, HC-SR04 doesn't work very well
On door to my room there is HC-SR04 that triggers led-wave. The shorter the distance, the faster the led-wave (8 leds).
The circuit works fine in synthetic tests – moving hand or flat object towards the sensor generates gradually accelerating wave.
However, when placed on door to detect approaching persons it generates short correct (<=170 cm) impulses and the wave starts and immediately stops, again starts, etc. I guess HC-SR04 isn't good enough to detect people.
Are there any alternatives to this sensor that will correctly detect human approaching?

You should run some tests that show the calculated values. You may want to filter out any values that are extremely high (and disregard them).

Are you powering it differently in your tests vs on the door?

The typical HC-SR04 code uses pulseIn() with a default 1 second timeout. If there is nothing for the sound to reflect off in range (i.e., a wall within a couple of meters) the pulseIn() will cause massive delays in your operation.

https://arduino.stackexchange.com/questions/39388/hc-sr04-returning-incorrect-distances Use the code in this link to solve your problem.

Try to find where the error comes from.
I suggest loading up a piece of code that outputs the measurements to through the serial terminal.

You should typically filter out any values that are > 200cm (since it's out of range).
You should take the average of a few readings, to be more accurate and less error-prone.
Find why some readings are weird, is the object fuzzy (may absorb the ultrasound)?

If all fails, you may look at IR distance sensors (SHARP) like:
https://www.adafruit.com/product/164
or
https://www.adafruit.com/product/1568
Alternatively, you could use a combination of (multiple) IR and ultrasonic sensors. But I doubt you really need that mount of accuracy.
You could also go for a Raspberry Pi + camera and openCV, but that's a whole other matter.

I've had to take not average, but minimum value, from last 7 values (distances) – it looked like the sensor was returning correct distance to the moving object mixed with distance to the wall behind the person. Also, NewPing beautifully fixed pulseIn() lags

Yes, it may be that the sensor sometimes doesn't see the object, this may be of various reason, such as the sound not bouncing back into the "receiver". If the wall is at 200cm, you could filter out values that are below it, so that you automatically only sense when there is someone.
But good that you've found out a method that works for your case :D

In general the HC-SR04 is controlled using pulseIn().
When there is nothing within range for the sensor to detect it usually has to wait for pulseIn() to time out. That can take up to a second by default.  While that is happening the rest of the sketch cannot do anything.
You can reduce the timeout in the pulseIn() function, but it's still not going to be perfect - you'll still get a delay which will interrupt your LED sequences.
The ideal way will be to create a "free running" distance sensor system - use a timer to periodically start a ping, and use the Input Capture module of the ATMega to measure the time between the start and end edges of the returning pulse. Everything will happen asynchronously to the rest of your sketch then.
I am not aware of any libraries for Arduino boards, but I have one for the PIC32 based chipKIT boards that I use. It can't ever work on AVR based boards, but you can use it to see the general concepts and how things fit together.

Good points, I had a hard time distilling what the problem was, since the question isn't that clear. But this could indeed also be a problem. One should always try to make his code non-blocking :) Using hardware timers directly, may make the project unportable to other Arduino devices. You could use millis() and code based on a statemachine.

@paul You could, though you would be hard pressed to get the timing resolution you need for ultrasound work with that - you're working with microseconds, not milliseconds.

Ah, indeed, I was thinking for planning the periodical scanning. 'micros()' is also a thing, but I'd rather not?


text:
RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]
I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.
Here's my main code:
#include <RFM69.h>
#include <SPI.h>
#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      1   // My node ID
#define TONODEID      2   // Destination node ID
#define FREQUENCY     RF69_915MHZ
#define ENCRYPT       true // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
#define RFM69_CS      10
#define RFM69_IRQ     2
#define RFM69_IRQN    0  // Pin 2 is IRQ 0!
#define RFM69_RST     9
#define IS_RFM69HCW   true
#define USEACK        true // Request ACKs or not
#define LED           9 // LED positive pin
#define GND           8 // LED ground pin
#define PULSEPIN      0 // Heart Rate Monitor at pin A0

RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
String pulsearray;
bool recHR = true;
unsigned long oldtime = 0;
int interval = 5000;
static int readtime = 3000;
static int sampletime = 10; // 1000/this is the thing
static int txinterval = 1000; // delay between transmissions

void setup() {
  initSerial();
  initLed();
  initRadio();
}

void loop() {
  unsigned long newtime = millis();
  if (!recHR && newtime - oldtime >= interval) {
    recHR = true;
    oldtime = newtime;
    Serial.println("recording HR now");
  }

  while (recHR) {
    unsigned long newtime = millis();
    if (newtime - oldtime >= sampletime) {
      readhr();
    }
    if (newtime - oldtime >= readtime) {
      recHR = false;
      oldtime = newtime;
      Serial.println("stopped reading HR");
    }
  }
}

And the function I'm using:
void readhr() {
  for (int i = 0; i < 20; i++) {
    int pulse = analogRead(PULSEPIN);
    pulsearray = pulsearray + pulse;
    pulsearray = pulsearray + '\n';
    Serial.println(pulse);
  }
}

The library function sendWithRetry() requires the following arguments:
bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.
Using a string as my buffer doesn't work when I try to transmit the first n (<60) characters in the String. I've also tried using a char[ ] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:
exit status 1
no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'

Do you have a specific question?

@sa_leinad my apologies, I should've been clearer.
I've edited my post to reflect my question.

You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.
If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).
So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:
int values[10];
// whatever to fill the array
RFM69::sendWithRetry(20, values, 20, 4, 1000);

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use sizeof() to get the size in bytes:
RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

As long as you receive at the other and using the same type of buffer it should be completely transparent.
To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of int use int16_t which is always 2 bytes and signed on every platform everywhere:
int16_t values[10];

Or use uint16_t if you want it unsigned.


text:
Arduino Sending faster/more data to a web server
I'm working on a project that reads vibration on a building using an accelerometer and displaying it's data on a web server. The plan is to read 10 samples/second from the accelerometer and send that data every 5 seconds to a web server using arduino yun.
So there would be 10(samples/sec) x 5(seconds) x 3(3 axis - x,y,z) = 150 data points that will be sent to the webserver, I tried this with the client.get() command but it cannot send that much data to a web server, I also tried POST request but i've had trouble with the sending it multiple times since it needs to have a delay.
What are the other options that I can do in order to achieve this? Any suggestion would help and please if you think my question is bad or not stated properly don't report me, I'm still new here in stack exchange. Any help/suggestion is much appreciated
Arduino Code for POST request
#include <Bridge.h>
#include <HttpClient.h>
#include <YunClient.h>

//IPAddress server(192,168,1,200);
byte php_server[] = {192,168,1,9};

YunClient client;
String data = "", datax="", datay="", dataz="";
unsigned long ts_0 = 0, tr_0 = 0, t_read = 100;
int counter=0;

void setup() {
  // put your setup code here, to run once:
  Bridge.begin();
  Serial.begin(115200);

}

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

  if((millis()-tr_0>=t_read)) {

    if(counter<49) {
      counter++;
    }
    else if(counter == 49) {
      //Serial.print("sent");
      String dat = "0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12";

      send_to_ws(dat);
      Serial.println(dat);

      counter = 0;
    }
    tr_0=millis();
  }
}

void send_to_ws(String data) {
  if(client.connect(php_server, 80)) {
    Serial.println("Connected");
    client.println("POST /arduino/add.php HTTP/1.1");
    client.print("Content-Length:");
    client.println(data.length());
    Serial.println(data.length());
    Serial.println(data);
    client.println("Connection: Close");
    client.println("Host:192.168.1.9");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(data);
  } else {
    Serial.println("Connection error");
  }
}

Serial monitor output when running this sketch, It prints it in the serial monitor but only blank data is being pushed in the database of the server

Its not clear from your question, are you sending 150 POST requests or one request with 150 points of data?  What are the minimum and maximum values of the points and who many decimal places are you using?

one request with 150 points of data, i think the maximum value wouldn't exceed the 10 so probably between +/- (0.00 - 9.99) considering i will have 2 decimal places,

Could you show us your code? As in principle both method would work. There is probably something in the code, like e.g. a buffer, that limits the amount of data that can be send.

@Gerben I haven't really integrated all the things i wan't to do in a sketch, but what i did was sending a request and hardcoded the data that i want to send. I found out that it is too large especially using the client.get() method of the httpclient library since sending a small string can be done without a problem but when i try to increase the size (up to 60 data points) it can still send but it takes so much time sending the data, approximately 20 sec and when I'm using POST request which uses delay i dont know how  i can still read every 100 ms while having a delay for 1-2 sec in sending

Could you show us your code? I don't care that it isn't finished. It's even better like that, as there is no other code that can have side effects. Why does POST use delays? That makes no sense.

@Gerben sorry for the late reply, when you said using delays in POST makes no sense, i tried removing it and it still works, the code is attached above and I hardcoded 150 data points but it seems like no data is pushing through my server

data.length() returns 0. There might be a problem there. Does it work when you use a shorter string? It might also be a good idea to use the F("text") macro to save some memory. Lastly the data string isn't x-www-form-urlencoded, so your PHP script will have to get the raw POST data instead. So there might also be a problem at the server's side.

no problems when i send shorter data length like 186, it sends every 5 seconds but when somewhat longer than that like 400+ it can still send data but it cannot send every 5 seconds, instead it reaches up to 20 sec for each request to be made. Where should I apply F("text") in the client.println(data)? or in my serial.println(). Oh yeah I forgot to edit that though, but I edited it already in my code. thanks! Any thoughts on how to make this possible?

Option 1.
Send a single message from the client to the server.  This message should contain all 150 points of data.
Option 2.
Send the data in a format other than as a string.  Base64 encoding of the raw numeric values would be ideal, but its going to add extra load to the CPU.  Depending on the range of the data (0-359) and the resolution (use 2 DP) you might be able to use just 4 bytes for each data point.  Because you are using a fixed length value to represent each point you no longer need separators in you data so a single reading goes from 21 bytes to 12 bytes.
Option 3.
Hand off the data to a second processor that is dedicated to sending the data.  The Yun would write the data into a shard circular buffer and the other processor (possible another Yun or an ESP8266) would read the data from the buffer, convert it and write it to the server.
I can't say which is best, because I don't know enough about you system, but if you could expand on your details we should be able to narrow it down.

After reading you answer above.  If you ranges are 0-10 with two DPs then I would look at option 2 first.  If each reading can range from -9.99 to +9.99 you take the absolute value and multiply by 100 and write that as a 2 digit hex number to your message body.
uint8 number = ((reading < 0) ? 0x80 : 0x00);  // Set the high bit for negative.
number += (abs (reading) * 100);
messageBodyString += String (number, HEX);

That will give you 2 bytes per point, and a 300 byte (+overhead) message should be transferable within 5 seconds.

Here is some quick code to explain the encoding and decoding
unsigned int Encode(const float& value)
{
    unsigned int result = (value < 0) ? 0x80000000 : 0x00000000;// Work out and set the sign bit
    result |= (unsigned int)abs(value * 100.0);             // Get the absolute value (ignore sign) and multiply
    return result;
}

float Decode(const unsigned int& value)
{
    const bool isNegative = ((value & 0x80000000)  != 0);       // Get the sign bit
    float result = (float)(value & 0x7FFFFFFF);                 // To remove the sign bit
    result /= 100.0;                                            // Divide to return to the original number of dps.
    if (isNegative)
        result = 0 - result;
    return result;
}

sorry for the late reply, was having a hard time absorbing what you're saying since I'm a newbie. I did option 1 already but yun cannot send that much data using the client.get() function from HttpClient library.
After deep thinking on your code I understand it already, or somewhat at least. So first is the number should have a high bit (i guess it is also the msb?) to know if it's positive or negative, then I convert the decimal reading to an int, or remove the decimal place and then convert it to a string? I will definitely give this a try thank you so much for the answer!

hello, will i need a separator for this to change it back to decimal numbers? since other hex values are only one character and others are 2 characters.

also another one, how would i check if the hex value reflects the negative number? because when i tested it the same number having opposite signs printed the same hex value, thank you so much for the help

If the most significant bit is set then the number is negative.  That's what the 0x80:0x00 is for.  You then have 15 bits to hold the value, which is ... oh bugger it isn't enough.  You need 2 byte numbers, which give you 4 characters.  Sorry.

because this data is going to a web server developed in php, so i should check in php if each hex values has most significant bit then it is negative? I'm a little confused with your statement that i need 2 byte numbers which gives me 4 characters, I'm sorry I can't comprehend that well :(

now I understood what you meant by 2 byte numbers, that means i should use uint16_t right? because the values are greater than 255 (8 bit decimal), but now I don't know how to change this back to decimal when it is a negative number for it has an additional of 128 decimal value

Ralph, I've edited my answer with rough encode and decode functions.

hey I just found out that there are some values that doesn't get the right value in encoding, like when the value is -0.53 it returns the result as 52 instead of 53, but it works fine with others, why is this happening? even when I hard code -0.53 it still returns 52 but when I put -0.54 etc it works fine.

That's not my fault :) Its to do with the way floating point values are stored in memory.  A floating point number should have an infinite range of values between 0 and 1. Obviously you can't us binary to store this infinite range so you have to have make a compromise and this is where the resolution comes into play.  Write a little program in visual studio and add const float a = 0.53f;  printf("a = %2.5f\n", a);  printf("b = %d\n", (int)(a * 100));  You will get the output 0.53\n52\n!!!  If you put a break point in there you will see a == 0.5299999714F.

If you need accuracy then you could either user more digits or make a look up table of values that don't work so you can correct them.

Personally for this kind of frequency of data I wouldn't even consider sending it via HTTP. The extra bulk of the HTTP protocol makes the transfer way too slow.
Instead I would set up a UDP-based gateway server which accepts UDP messages from your sensor system and stores the data directly into the database (or wherever you are storing the data) for the website to display it at its leisure.
Yes, it is more complex to create since you need to write the UDP server gateway software. However you then completely remove the massive overheads of a text-based bulky protocol like HTTP.

You can use 2d Array for this and send all data at once in 5 Sec. It Read all 3 Axis data each 100Ms and make a matrix of 50 X 3 = 150 Values and then Print it in Serial Port. You can use this in your code to send data to server in desirable format.
int Xaxis=A0;
int Yaxis=A1;
int Zaxis=A2;
int axisMatrix[50][3];
void setup(){
    Serial.begin(9600);
    pinMode(Xaxis,INPUT);
    pinMode(Yaxis,INPUT);
    pinMode(Zaxis,INPUT);}

void loop(){
        for (int i = 0; i <= 50; i++) {
            axisMatrix[i][1]=analogRead(Xaxis);
            axisMatrix[i][2]=analogRead(Yaxis);
            axisMatrix[i][3]=analogRead(Zaxis);
            delay(100);}
        for (int i = 0; i <= 50; i++) {
            Serial.print(axisMatrix[i][1]);
            Serial.print(",");
            Serial.print(axisMatrix[i][2]);
            Serial.print(",");
            Serial.print(axisMatrix[i][3]);
            Serial.print(",");
            Serial.print("\n");
        }}


text:
How time intensive or how long can an ISR be?
I would like to code my ISR to be time intensive or interrupt the main program for atleast 1 or more seconds. My goal is to verify that if I am reading a sensor in the main loop, would it stop reading the sensor when the code is interrupted and for how long. I have trying to call various functions from the ISR like to turn on the motor but everything is instantaneous.

Please explain what it is you want to achieve. It sound like you are trying to use ISR for something, while there might be a much better solution.

Putting it simply, I am trying to design a position controller. I have an input which drives a motor. Hall sensors read the revolutions. Trying to determine which of the above, input or hall sensor output should be used as an interrupt

Could you please post your code?

Use a pin interrupt for the hall-effect sensor. That way, whenever the hall-effect sensors triggers, you get an interrupt. Then you can calculate the speed using the difference in millis between this interrupt and the previous one. The main loop will act based on the current speed you've written to some variable. None of these things should take a lot of processor-time.

How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.
That includes things that rely on other interrupts to function, such as serial communications, millis() and delay(), etc. That means using such functions from within your interrupt handler is a big no-go.
It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.

Thank you. So between a rotary encoder reader and an input signal, I would assume based on the fact that the main loop is suspended, the encoder reader is better suited as an interrupt. Is that right?

Rotary encoders work well with interrupts, yes. React to a change in one of the signals and work out which way it has been turned. You need very rapid responses to a rotary encoder since the signals can change quite fast.

Great, I guess that simplifies things. Thanks for your help

@Vignesh I'm not sure why you are treating this as an either/or situation. They can both be interrupts. All the interrupt has to do is make a record of the new input or increase a count of the number of pulses and set a flag indicating that the value has changed. The main loop then looks for those flags and does all the slow work in the background. Just make sure you code the main loop so that it can cope with the possibility that the data may get changed half way through. e.g. make a copy of it and work from the copy.

Does the delay() function not work for you? It should halt all other processing, whether in ISR or not; so if you call it inside your ISR, your ISR would remain active for as long as the delay.
Of course, ISR should not be long like this. Perhaps there is a better way to code your test. Perhaps a variable that the sensor-reading code checks; if it's set to 1, don't read the sensor, and if it's 0, it's okay to read the sensor, etc.

Thank you. I think the delay() function does not work as it depends on the timer which is suspended when an ISR is called. Will check it either way.

The main goal is to see which aspect of the program should be an interrupt. The rotary encoder reader or an input signal

use delayMicroseconds(), then.

delay() does not work if called from within an ISR. 2) When called from main code, delay() does not halt ISR processing.


text:
Is the analogread function averaging the samples taken by the ADC?
In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port. But the data speed I see on the serial port by HyperTerminal or Serial monitor is much slower than the sampling rate.
Lets take Arduino as an example. As far as I understand the analogread() function samples an analog input at 10kHz rate. It means 10000 samples taken per second.
But when I use the Serial Monitor it seems the data speed which we see as upcoming/flowing line by line per second on Serial Monitor is much slower.
Is that because the analogread() is averaging the samples before the data is sent to the serial port?

analogRead() doesn't send the samples anywhere. I think you need to look at some example code and then revisit your question.

ok i edited to: "Is that because the analogread() is averaging the samples before the data is sent to the serial port?"

That function only reads the ADC value, it doesn't do anything else. The 10KHz you mention is related to how often you can call that function, it has nothing to do with what the rest of the code is doing with that data.

"In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port" I've yet to see one that does this unless you write a program to do so. "Lets take Arduino as an example" So are you talking generally or just Arduino? Since this is a software question the answer will depend on the exact software used.

It can sample at 10kHz, doesnt mean it does. When you analogRead and serialPrint, it does it once and prints once. If you want some sort of running average you have to implement it, there's nothing obscure running in the background.

@WesleyLee No indeed I dont want averaging. But when I see the readings in Serial Monitor it is much much slower rate. Let me put it this way. If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC. But the serial monitor shows muc much less lines than that. Why is that happening?

Given a sample frequency is 10kHz. Assumed the ADC is 8-bit. You'll need to transfer et-least 800kbit or 100kB a second. Because serial is much slower then the ADC you won't get the 10kHz sample rate until the communication can keep up.

So what do I see at the Serial Monitor then? It is not all the samples, it is not the average. It is what then? :(

We can't tell what you are seeing on the Serial Monitor because that varies from firmware to firmware. I'll repeat myself: if you use analogRead then Serial.print in a loop, you are seeing all the samples.

@WesleyLee thanks for the last clarification. that was what i was asking about.

If you have a loop that calls analogRead() to take a reading, and then serialPrint() to send the reading, each pass through the loop will take at least the sum of the time for those two functions calls together.
When you first call serialPrint(), it returns in uS, as it doesn't actually send data, but puts it into the 64 deep transmit buffer, to be sent in the background. If the transmit buffer is emptying slower than you are filling it (at 9600 baud, it's sending roughly one character per mS, so you can send at most 100 off 10 character messages per second) then eventually when called, it will find not enough space in the transmit buffer for the whole message, and will Block, that is not return, until there is enough space. Each call to serialPrint() will now take 10mS (assuming 10 characters at 9600 baud). That's what slows your loop down.
To send faster, choose a higher baud rate, and reduce the number of characters in the message.

void loop()
{
val = analogRead(analogPin);    // read the input pin
Serial.println(val);             // debug value
}

it is sad that using analogread as above code in a loop we will never know the exact sampling rate right?

The sampling period is the time it takes for a loop to complete. So the rate would be 1/looptime.

@WesleyLee last question. can we trust each loop time will ve equal? thanks

I'm not sure since I don't know how Arduino deals with jamming stuff on its serial buffer.

I've told you, it has a 64 long buffer, it returns fast when there's buffer available, it blocks when there isn't. I had my 'scope on a debug pin last week timing a serialPrint(), so I know which orifice I'm talking out of!

@user16307: “Can we trust each loop time will be equal?” No, you can't. Sending “1000” takes longer than sending “999”: one more byte to send. And then there is the timer 0 interrupting your code roughly every millisecond: each time it's interrupted, the loop takes ≈ 6.25 µs longer to complete (assuming an AVR-based Arduino). If you want constant sampling rate, forget analogRead() and read the datasheet: the ADC can be auto-triggered by a timer, or even by itself (free running mode).

As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at once per invocation. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then the code is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.

Let me ask the same question to you. When I see the readings in Serial Monitor it is much much slower rate. Let me put it this way. If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC. But the serial monitor shows much much less lines than that. Why is that happening?

Because your understanding of how analogRead() works is completely and irredeemably broken.

@user16307 -- "If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC" That assumption is wrong to begin with, any reasoning based on that will be wrong.

If during that second you call analogRead once, you will have one sample.

Imagine analogread is in a loop and sampling 5kHz per second. Now we use a watch and start and stop sampling for 1 second. At the serial monitor you will see much much less lines of voltage readings. But actually the samples are 5000

You get one sample per call. Ever. Always.


text:
Web Page doesn't load when data is being received from Xbee
I have an Arduino Mega I am using as a simple web server. Right now the web page is two simple lines of text. There is an XBee radio attached to the unit to receive data from another unit. However, when the server unit is receiving data the web page will not start up. There's a switch on the shield to switch it into Micro for the radio, or USB. If I reset, or power on, the server unit with the switch in USB mode it loads fine; then once the web page loads I can flip it on Micro and it will refresh fine even while receiving data. However, if I try to power on the unit, or reset the unit, with the switch on Micro it will not load the web page. Any ideas on why this is happening?
Schematic:
Server Unit: Ethernet shield with HanRun HR911105A 13/15 ethernet jac placed on Mega ADK. There is a Wireless Proto Shield with XBee Pro 538 radio placed on the ethernet shield.
Remote Unit: There is a Wireless Proto Shield with XBee Pro 538 radio placed on the Mega ADK.
setup():

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);

    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);//, gateway, mask);
    server.begin();
}

loop():
void loop() {
    // Listen for incoming clients
    client = server.available();
    if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
        if (client.available()) {
            char c = client.read();

            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {

                // Send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");  // the connection will be closed after completion of the response
                client.println("Refresh: 5");  // refresh the page automatically every 5 sec
                client.println();
                client.println("<!DOCTYPE HTML>");
                client.println("");

                client.println("
");
                client.println("");
                client.println("");
                client.println("My WebPage");
                client.println("
");
                client.println("Web Server and Radio Receiver ");
                client.println("
");
                client.println("version November 30, 2016");
                client.println("
");
                client.println("");
                client.println("");
                client.println("");

                break;

            }
            if (c == '\n') {
                // you're starting a new line
                currentLineIsBlank = true;
            } else if (c != '\r') {
                // you've gotten a character on the current line
                currentLineIsBlank = false;
            }
        }
    }
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}

Could you provide the schematic and both setup() and loop() functions that will manage both Micro and 'USB` links ?

@J.Piquard I just posted my Arduino set up, as well as the code.

In your source code, close to the example WebServer.ino, you have assigned in loop() the client = server.available(); with certainly EthernetClient client declared before setup() meaning that another client has been created before. Try to declare EthernetClient client = server.available(); inside the loop().

@J.Piquard I tried your suggestion but it unfortunately didn't solve the problem

@J.Piquard I tried moving Serial.begin(9600) to be the last line of setup() and now the web page loads when reset while receiving data, but it still won't load while receiving data when first powered on

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


text:
Mega 2560 & smoking/burning 5v requlator, probable cause?
Problem: board seriously fried.
Desired outcome: measures to take in future.
Background:
This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion.  It sits on a shelf with others of the same ilk.  Nothing is touched unless I need to plug in USB cable for update.
The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds [normally off, used to flag specific conditions, each in series with 470 ohm resistor.
The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.
Steps leading to failure:
Plugged in USB cable [no other physical changes, nothing else touched, power jack remained connected]. went to Arduino s/w to make minor changes, would not upload to Arduino.  While scratching my head, smelled something burning, then saw smoke coming from the shelf.
Post failure:
Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary.
Visual wiring inspection revealed no obvious problems.
Input to power jack measured at 10.06v.
Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port [just in case of ?, seen ancedotal posts of possible conflict; a clone after all].  Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in.
Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.
Seeking:
Words of wisdom from others far more knowledgeable and experienced than I.
Could the dual connection of USB and power jack, be the root cause?  Never experienced this with UNO clones.
I do not want to put more boards at risk in the future.

Maybe they tried to save a few cents and not include the the opamp and mosfet, that would turn of usb-power if the jack is present. I think what happened, is that the mega was trying to supply 5V back into the USB port, back into your PC. This would happen if the 5V of your PC is below the 5V the regulator is supplying. Just don't plug in both at the same time, seems like a good solution. Other that reverse engineering the clone, and see what's different from the original.

You said it yourself: a clone after all...

Sometimes the big decoupling caps you put around the regulator have a low voltage limit on clones; I have seen board with a grilled cap. If regulator is also a cheap brand, not up to specs, then you are at risk. The first wise thing to do is to buy genuine boards.

It could be the board, but don't assume it is - could also be a problem like a hot ground or excessive ripple with your power supply or even your computer.

I suggest pulling out your multimeter and measure that you don't have a short between 5V & GND and 3V & GND. I also suggest checking these 10 possible causes: http://ruggedcircuits.com/html/ancp01.html

The "rugged circuits" page is in my reference library, and I had read it. It is good that you mentioned it because I had intended to, but did not. Including the reference may be beneficial to others reading this posting.

They are using the same SOT223 LDO as every other product.  These have a very low limit of output current when run from an input voltage such as 12V.  If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant).  The PDF linked below shows a comparison between the LDO and drop in switcher.  Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.
https://www.sugarsync.com/pf/D3258881_07979653_7526812


text:
`servo.attach()` paralyzing (one) motor on L298N
I have 2 DC motors (well, 4; but each pair is controlled by the same "signals") connected via a L298N, which is connected to the Arduino. In addition, I have a servo motor connected to the Arduino.

When I run the following program (in reality, it's a bigger program; however, I've managed to chiseled it down to the following):
#include <Servo.h>

const int servoPin = 3;
Servo servo;

const int LMotorsSpeedPin = 5;
const int RMotorsSpeedPin = 10;
const int LMotorDirectionBit1Pin = 7;
const int LMotorDirectionBit2Pin = 6;
const int RMotorDirectionBit1Pin = 8;
const int RMotorDirectionBit2Pin = 9;
const int MotorSpeed = 150;

void setup()
{
  // 1
  pinMode(servoPin, OUTPUT);
  servo.attach(servoPin);

  // 2
  pinMode(LMotorsSpeedPin, OUTPUT);
  pinMode(RMotorsSpeedPin, OUTPUT);
  pinMode(LMotorDirectionBit1Pin, OUTPUT);
  pinMode(LMotorDirectionBit2Pin, OUTPUT);
  pinMode(RMotorDirectionBit1Pin, OUTPUT);
  pinMode(RMotorDirectionBit2Pin, OUTPUT);

  // 3
  digitalWrite(LMotorDirectionBit1Pin, LOW);
  digitalWrite(LMotorDirectionBit1Pin, HIGH);
  analogWrite(LMotorsSpeedPin, MotorSpeed);

  // 4
  digitalWrite(RMotorDirectionBit1Pin, LOW);
  digitalWrite(RMotorDirectionBit1Pin, HIGH);
  analogWrite(RMotorsSpeedPin, MotorSpeed);

  // 5
  delay(10000);
}

void loop() {}

1 Sets up servo.
2 Sets up L298N pins.
3 Sets up left motor data.
4 Sets up right motor data.
5 Tests the code above for 10 [s].

I assume that you'll need some experience with the L298N; however, here's the gist.
*MotorsSpeedPin sends each motor what speed (MotorSpeed 0-255) they must go (via PWM).
Data into a pair of *MotorDirectionBit*Pin tell each motor what direction to go (i.e. back 01, stop 00 11, right 10).

When I run the program above, only the left motor runs. However, if I comment out 1 (which essentially renders the servo useless), both left and right motors start to work.
I find this problem quite odd. What does the servo code have to do with the motor code (and only one at that!)?

The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.
However, pins 9 and 10 also use Timer 1 to create the PWM signal.
It can't do both.
As soon as you start using the Servo library you lose PWM on pins 9 and 10.
So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.

What's "Timer 1"?

A bit of hardware in the chip that counts real fast.

Thanks. Are you aware of any good sources that explain timers and other topics like it?

The datasheet for the ATMega328p is the source of all the information you could ever need.


text:
How to make battery last for months?
I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.
When no person detected, sleep longer:
LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

When person detected, sleep shorter (so that diodes can be often turned on/off):
LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

Without LowPower use – delay() used instead – the current taken is 15 mA. This is with diodes off. After using LowPower – it's still ~15 mA. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?
Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short delay() before the calls, then they don't block execution.
#include <LowPower.h>
#include <NewPing.h>

#define trigPin 13
#define echoPin 12

NewPing sonar(trigPin, echoPin, 250);

// Defines speed of LEDs traversal
int delayTime = 40;

// Current led
int currentLED = 0;

// Direction of travel over LEDs
int dir = 1;

// Stores the last time LEDs were changed
unsigned long timeChanged = 0;

// Stores the last time sensor was read
unsigned long timeOfQuery = 0;

// LEDs
byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

// Stores if any diodes are on
int leds_used = 1;

// Stores if wave is active
int off = 1;

// 5 last distances, circular buffer;
long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

// Last chosen distance
long distance = 400;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  for (int x = 0; x < 8; x++) {
    pinMode(ledPin[x], OUTPUT);
  }
  timeChanged = millis();
}

void loop() {
  long duration, cur_time, cm;

  cur_time = millis();

  /* Read distance when off, or when some time passed */
  if (off || (!off && (cur_time - timeOfQuery) > 100)) {
    timeOfQuery = cur_time;

    cm = sonar.ping_cm();
    if ( cm == 0 ) {
      cm = 400;
    }

    distances[(++currentDistance) % 7] = cm;
    // At least 1 proper distance?
    off = 1;
    for (int i = 0; i < 7; i++) {
      if (distances[i] <= 200) {
        off = 0;
        // Remember minimum distance
        if (distances[i] < distance) {
          distance = distances[i];

        }
      }
    }
    delayTime = distance;
  }

  if (!off) {
    // Check whether it has been long enough
    if ((cur_time - timeChanged) > delayTime) {

      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }

      // Turn on the current LED
      digitalWrite(ledPin[currentLED], HIGH);

      // Mark that diodes are being used
      leds_used = 1;

      // Increment by the direction value
      currentLED += dir;

      // If we are at the end of a row, change direction
      if (currentLED == 7) {
        dir = -1;
      }
      if (currentLED == 0) {
        dir = 1;
      }

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Shorter delay when sleeping
    delay(5);
    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
    //delay(50);
  } else {
    if (leds_used) {
      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }
      currentLED = 0;
      dir = 1;
      leds_used = 0;

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Longer delay when sleeping
    delay(10);
    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    //delay(200);
  }

  /*
    if (distance >= 200 || distance <= 0) {
      Serial.print(distance);
      Serial.println(" Out of range");
    }
    else {
      Serial.print(distance);
      Serial.println(" cm");
    }
  */
}

Update: The board is Arduino UNO.

Are you using an Arduino board or are you using an MCU directly on a breadboard? Could you mention which board/MCU you are using?

@jfpoilpret: It's UNO

Are your other questions answered? It's allowed to ask multiple questions, but don't forget to accept answers and/or give feedback on your other questions' answers.

Please see http://arduino.stackexchange.com/questions/18759/powering-the-arduino-uno/18760#18760

The Arduino UNO always consumes current mainly because:

it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes only 15mA, on my boards, it is rather near 40-50mA.
Also, a 9V battery is probably the battery with the smallest charge capacity.
I would suggest you:

work on a breadboard with just the ATmega328,
power it with two 1.5V batteries (AA or AAA)
and run @8MHz

That should already reduce current consumption.
You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.
Finally, I highly recommend Nick Gammon's blog on that topic. It includes many good tricks to help you with current consumption.

I work with some radio microphones on a regular basis. We have two sets - old ones and new ones. The old ones use 9V batteries and the batteries often need changing mid concert. The new ones use two AA batteries each, and last for many concerts before they need changing. The difference is staggering.