text:
How to convert an hex string to an array of bytes?
How to convert the char array to Byte array? I tried every method but it doesn't work.
char CardNumber[8] = "B763AB23"; // Length is 8, basically it's in Hex
                                 // B7 63 AB 23

I need to convert it into Byte array to byte CardNumberByte[4];
So basically, it should be like :
CardNumberByte[0] = B7;
CardNumberByte[1] = 63;
CardNumberByte[2] = AB;
CardNumberByte[3] = 23;

I am unable to find any solution for that.

"B763AB23" is actually 9 bytes. You forgot the null terminator. And B7, 63, AB, 23 are not valid hexadecimal integer literals. They should be 0xB7, 0x63, 0xAB, 0x23.

Related: convert String Hex to Hex byte

There are indeed many methods (and they all work if done right).
Is it always a lenght of 8 ? That means it is 32-bit unsigned long number.
The strtoul can convert it to a long. Use '16' for the base. If you need the seperate numbers, you can shift the unsigned long and convert to bytes or use a union.
It is also possible to do with a for statement can convert each character of the input to a value: forum.arduino.cc: convert HEX (ASCII) to a DEC int
[ADDED]
Thank you @goddland_16 for providing a full sketch. I could not stay behind and wrote a sketch with strtoul.
char *CardNumber = "B763AB23";
byte CardNumberByte[4];

void setup()
{
  Serial.begin(9600);
  Serial.println("With strtoul");

  // Use 'nullptr' or 'NULL' for the second parameter.
  unsigned long number = strtoul( CardNumber, nullptr, 16);

  for(int i=3; i>=0; i--)    // start with lowest byte of number
  {
    CardNumberByte[i] = number & 0xFF;  // or: = byte( number);
    number >>= 8;            // get next byte into position
  }

  for(int i=0; i<4; i++)
  {
    Serial.print("0x");
    Serial.println(CardNumberByte[i], HEX);
  }
}

void loop()
{
}

Note that this is limited to 0xFFFFFFFF, or 4 bytes.

Here is a simple solution to your question. I took each character, checked against its hexadecimal character and returned as a combination.
char CardNumber[] = "B763AB23";
byte CardNumberByte[4];

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

void loop() {
  for(char i = 0; i < 4; i++)
{
  byte extract;
  char a = CardNumber[2*i];
  char b = CardNumber[2*i + 1];
  extract = convertCharToHex(a)<<4 | convertCharToHex(b);
  CardNumberByte[i] = extract;
  Serial.println(CardNumberByte[i], HEX);
}

  while(1);
}

char convertCharToHex(char ch)
{
  char returnType;
  switch(ch)
  {
    case '0':
    returnType = 0;
    break;
    case  '1' :
    returnType = 1;
    break;
    case  '2':
    returnType = 2;
    break;
    case  '3':
    returnType = 3;
    break;
    case  '4' :
    returnType = 4;
    break;
    case  '5':
    returnType = 5;
    break;
    case  '6':
    returnType = 6;
    break;
    case  '7':
    returnType = 7;
    break;
    case  '8':
    returnType = 8;
    break;
    case  '9':
    returnType = 9;
    break;
    case  'A':
    returnType = 10;
    break;
    case  'B':
    returnType = 11;
    break;
    case  'C':
    returnType = 12;
    break;
    case  'D':
    returnType = 13;
    break;
    case  'E':
    returnType = 14;
    break;
    case  'F' :
    returnType = 15;
    break;
    default:
    returnType = 0;
    break;
  }
  return returnType;
}

That is very kind of you to provide a working sketch. I hope you don't mind that I have a few positive comments. You give CardNumber a string of 9 bytes (with the zero-terminator it is 9 bytes) and CardNumber has only 8 bytes. The switch-case statement is long, when there is an error in there, it can be overlooked. Therefor a short calculation would be preferred.

yes, no problem. I only provided a simple working copy, not necessarily compact. Yours is a good one though.

A char array is a byte arrray. No difference whatsoever
What you are attempting to do is a conversion of hex string to byte. For that you have to determine if you are scanning left to right or right to left.
After that convert a char in the string to a half byte.
From there you shift the half byte left and or it with the next half byte until the whole string has been exhausted.

This is a great explanation. Now we just need to see you do it in code. Then, I'll upvote it.

Keep in mind you need to make sure to also convert from ASCII chars to hex/binary. A 0 in ASCII is a decimal 48 or hex 30, so you must subtract 48 from it to be a true hex zero. You must do this for all the ASCII chars, taking care to also account for the fact that you might see the ASCII "hex" chars in lower or uppercase A through F, and lowercase must be handled differently from uppercase since they are different decimal values.


text:
4WD rover not moving
I am trying to make a 4WD vehicle. I have uploaded the code, all connections are OK and I have used L298N and HC-05. But when running the Bluetooth app, the motors do not rotate. I tried with both an Uno and a Nano and nothing happens. Could anyone help me spot the errors?
I used this code in Arduino Uno:
#include <SoftwareSerial.h>

SoftwareSerial BT(0, 1); //TX, RX respetively
String readvoice;

void setup() {
  BT.begin(9600);
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
  while (BT.available()) {  //Check if there is an available byte to read
    delay(10);              //Delay added to make thing stable
    char c = BT.read();     //Conduct a serial read
    readvoice += c; //build the string- "forward", "reverse", "left" and "right"
  }
  if (readvoice.length() > 0) {
    Serial.println(readvoice);

    if (readvoice == "*forward#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*back#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      delay(100);
    }
    else if (readvoice == "*left#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(800);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*right#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(800);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*stop#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*keep watch in all direction#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*show me Garba#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);

      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
    }
    readvoice = ""; //Reset the variable
  }
}

This is the wiring diagram of the rover:

First try it without the bluetooth.  What power source are you using for the motor?   The L298 is a horribly lossy part and you'll need an extra AA cell or two just to offset its losses.  Meanwhile the small 9v batteries wouldn't have the current capability for a motor project.  And where are the other two motors to make this 4wd?

Sir i have used a 9v battery and i have connected the other 2 motor with the other motor and connected their positive and negative terminal together and please also tell me that the code is correct or not and if there is problem with L298N then what should i use..

Do not use 9v batteries for motor projects.  Try 6 or 7 AA cells - with the absurdly lossy L298, maybe even 8 AA's.

Thank you sir it worked without bluetooth but what is then the problem coming with bluetooth connection.???

Well, for one, you shouldn't use software serial on pins 0 and 1, those are hardware serial.  Did you decide to do that on your own, or are you following directions written by someone who didn't know what they are doing?

I tried it myself sir and then where to connect the tx and rx pins instead of 1 and 0 serial pins.....

Possible duplicate of Arduino 4wd rover

If you have the wiring right, which you have probably checked 100 times by now, then its probably the fact that you aren't supplying enough current to break the stall of the motor. Search the web for the motor's datasheet and look up the "Stall current" then see if you are supplying enough current.
Have you checked the motor without the gearbox attached, if that's possible?
The motor will have both voltage and current requirements. You are using a 6V motor but we also need to know the running current and stall current so you can workout if your batteries are capable of supplying that. Are you trying to run one motor or 4? Get one motor working first and then move up to 4 when you need to supply 4 times the power.
Also can I just check that you have the batteries in series (to give you 7.4V). This probably isn't enough if the motors require exactly 6v because of the 2V drop through the IC.
Measure the voltage into the bridge and into the motor, as shown in the web page. Also measuring the current would help, but you will have to search to see how best to do that.

Sir i have also used a 3.7 volt battery with 7800Mah for the gear motor....

Yes sir I have tried without gear and it still vibrates....

Please can you check the rest of the things in the answer too?

source: Stack Exchange

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

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

sort: votes


text:
Decimal numbers sent over Serial get split and sent over multiple ticks
Here is my Arduino sketch:
#include <HX711.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
HX711 hx(9, 10, 128, 0.002229);
LiquidCrystal_I2C lcd(0x27,16,2);

void setup() {

  Serial.begin(9600);
  hx.set_offset(-9635);
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  lcd.begin(16,2);

}
void loop() {
  if(digitalRead(0) == LOW){
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("tare recieved");
    hx.tare();
  }

  double sum = 0;
  for (int i = 0; i < 10; i++) {
    sum += hx.bias_read();
    if(sum < 0) {
      sum = 0.00;
    }

  }
  sum = sum/10;
  lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Weight");
  lcd.setCursor(5, 1);
  lcd.print(sum);
  lcd.print("g");
  Serial.println(sum);
  delay(10);
 }

Here is an example output as seen on the Arduino Serial Monitor:
150.34
150.39
150.40
150.37
150.38

The Problem is when the data reaches node-serialport the value is split up on multiple lines.
 comport.on("data", function (data) {
    console.log(data.toString());
 }

When i log the data... it comes back like this:
1
50.4
5
150.
49
15
0.47
150.
48
15
0.45

Is there anyway to have Arduino only send the data if it is the full value and not the split up values?

There is no such thing as "the full value". Serial works in characters. That's what serial means. It's up to you at the receiving end to combine the individual characters up into full strings.

As explained in Majenko’s comment, the serial link is not packetized: it
transmits individual bytes and nothing else. If you need to convey a
notion of “data packet”, or “full message”, you will have to devise a
way to signal the message boundaries. This is called message “framing”.
Your Arduino is sending ASCII data. In this case, the most common way to
frame messages is linewise: each message is a single line, and each line
is terminated by an “end of line” sequence. The standard end of line
sequences are CR (carriage return, i.e. 0x0d or '\r'), LF (line
feed, i.e. 0x0a or '\n'), and the pair CRLF (CR followed by LF, or
"\r\n").
Actually you are already doing that: you are using Serial.println(),
and this method automatically appends CRLF at the end of whatever it
prints. So now you just have to parse that at the other end: you put
all the incoming characters into a buffer until you see that incoming
CRLF. Then you know you have a full line, which you can report as an
entire message.
This procedure is very common and there is a standard Node.js module for
it. It once was part of the serialport module, but it seems to have
split into a separate module. It is called parser-readline, and you
would use it like this:
const Readline = require("parser-readline"),
      parser = comport.pipe(new Readline({ delimiter: "\r\n" }));

parser.on("data", data => console.log(data.toString()));

C.f. the documentation of
ReadLineParser.

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


text:
Storing an array of objects
I followed the instructions of this post: Storing an array of function pointers.
To show my problem I shorted my code extremely but the problem is still there.
My classes are defined as followes:

class MyBaseClass
{
public:
  MyBaseClass(String functionName);
  String functionName();
private:
  String _functionName;
};

class MyDerivedClassA : public MyBaseClass
{
public:
  MyDerivedClassA(String functionName);
};

class MyDerivedClassB : public MyBaseClass
{
public:
  MyDerivedClassB(String functionName);
};

MyBaseClass::MyBaseClass(String functionName) {
  _functionName = functionName;
}

String MyBaseClass::functionName(){
  return _functionName;
}

MyDerivedClassA::MyDerivedClassA(String functionName) : MyBaseClass(functionName) {}

MyDerivedClassB::MyDerivedClassB(String functionName) : MyBaseClass(functionName) {}

The test method is this:
void test(){
  MyBaseClass *_elements[1000];
  int _elementCount = 0;

  for (int i = 0; i < 2; i++){
    if (i == 0){
      MyDerivedClassA tmp("MyDerivedClassA");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );

    } else if (i == 1){
      MyDerivedClassB tmp("MyDerivedClassB");

      _elements[_elementCount] = (MyBaseClass *)&tmp;
      Serial.println( _elements[_elementCount]->functionName() );

    }

    Serial.println( _elements[_elementCount]->functionName() );

    _elementCount++;
  }

  Serial.println("count: " + String(_elementCount));
  for (int i = 0; i < _elementCount; i++) {
    Serial.println("loop: " + String(i));
    Serial.println( _elements[i]->functionName() );
  }
}

When the code is running I get the following at the serial monitor:
MyDerivedClassA

MyDerivedClassB

count: 2
loop: 0

loop: 1

I dont understand, why the first call of "_elements[_elementCount]->functionName()" inside the first loop returns the correct value and the second only an empty string. Inside the second loop it again returns an empty string. I think it's the same problem like inside the first loop.
And there is the problem, that my NodeMCU crashes if the code is executed.
This is the output while it carshes:
Soft WDT reset

ctx: cont
sp: 3ffffd20 end: 3fffffd0 offset: 01b0

>>>stack>>>
...
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

Where is my problem?

You allocate 1000 pointers, aka 1000*4 Bytes on the stack. That kills the thread. (MyBaseClass *_elements[1000];)

ok, this was a really stupid mistake... Setting "MyBaseClass *_elements[10];" solved the crash problem. But the output at the serial monitor is still the same...

Your  tmp variable doesn't survive the { } it is placed in. It is de-allocated when it exits the }. Move the temp variables to an outer, greater scope or new and delete them.

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


text:
How to add indicator lights to button sketch
I would like to add leds to each button switch in the first code, The first code sends midi messages to a DAW I would like it to also turn on a led as an indicator light. The switch needs to turn the light on if off and off if on. The second code is an example that does this, it works well with one button. I would like to have the 3 buttons on pins 0, 1, 2 and the leds on pins 3, 4, and 5.

#include <Bounce.h>

const int channel = 1;
Bounce button0 = Bounce(0, 5);
Bounce button1 = Bounce(1, 5);
Bounce button2 = Bounce(2, 5);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
}
void loop() {
  button0.update();
  button1.update();
  button2.update();

  if (button0.fallingEdge()) {
    usbMIDI.sendNoteOn(60, 99, channel);  // 60 = C4
  }
  if (button1.fallingEdge()) {
    usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4
  }
  if (button2.fallingEdge()) {
    usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4
  }

  if (button0.risingEdge()) {
    usbMIDI.sendNoteOff(60, 0, channel);// 60 = C4
  }
  if (button1.risingEdge()) {
    usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4
  }
  if (button2.risingEdge()) {
    usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4
  }
  while (usbMIDI.read()) {
  }
}

Second sketch:
/*********************
Simple toggle switch
Created by: P.Agiakatsikas
*********************/

int button = 0;
int led = 13;
int status = false;

void setup(){
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
}

void loop(){
//a) if the button is not pressed the false status is reversed by !status and the LED turns on
//b) if the button is pressed the true status is reveresed by !status and the LED turns off

if (digitalRead(button) == true) {
  status = !status;
  digitalWrite(led, status);
} while(digitalRead(button) == true);
  delay(50); // keeps a small delay
}

Your "Simple toggle switch" code toggles the button status on/off on each button press. Your MIDI sketch is more like an organ key, where the note plays as long as the key is held down, and stops playing when the button is released. Do you want the LEDs to toggle on/off on each button press even though that is not how the MIDI note behaves?

This is not a code writing service. You should attempt to edit your code yourself, and post questions if you have trouble.

The midi sketch is used to to switch things on or off not for playing notes, I don't know why but this is the only sketch I found that works. I have tried to change the note on/off  to cc messages but it does not work. The midi sketch will turn on a parameter in Ableton (for example) the record function and and it will stay on until pressed again. which is exactly what I need the lights to do. I am not asking anybody to wright the complete code for me Just an example how to do it.

I'd suggest creating an array of MIDI button structs. For each entry you'd have a button object, an LED pin, and a BOOL to track the state of thate button.
Write a function that loops through the array of structs, checks the state of each one, and does the work to play/stop the notes and toggle the LED states based on the state of each button.


text:
XBee using Serial rather than SoftwareSerial--how to fix
So I have a couple of XBee S2Cs, and I have configured them properly--they can in fact communicate with each other. I am using them with Arduino Unos and this shield: https://store.arduino.cc/usa/shield-xbee-without-rf. I am attempting to interface with the XBees with SoftwareSerial, but for whatever reason, they are instead using just regular Serial. Anything I put on the SoftwareSerial appears to be ignored entirely, while anything I put on Serial appears in my serial monitor and also is transmitted to the other XBee. I have this code for transmitting:
#include <SoftwareSerial.h>
SoftwareSerial xbee (2, 3);
void setup() {
    Serial.begin(9600);
    xbee.begin(9600);
}

void loop() {
    xbee.println("hello");
    Serial.println("world");
    delay(5000);
}

And this code for receiving:
#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3);

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

void loop() {
    if (xbee.available() > 0) {
        Serial.println("xbee: " + xbee.readString());
    }
    else {
        Serial.println("no xbee data");
    }

    if (Serial.available() > 0) {
        Serial.println("serial: " + Serial.readString());
    }
    else {
        Serial.println("no serial data");
    }
    delay(5000);
}

Every 5 seconds, I get this output through the serial monitor on the transmitting side:
world

and this on the receiving side:
no xbee data
serial: world

I also get the string world when I connect a third XBee to my XCTU console.
So I have a couple of questions:
First off--how is this happening? I'm no Arduino expert, but as far as I can tell from what I've read, if the XBee is capturing my serial output, then I shouldn't also be able to see it in the serial monitor.
Second off--how can I get the SoftwareSerial to work? I could theoretically just use Serial forever, but that would make debugging way more trouble, and would probably create a code-maintenance headache later. If I had to guess, I might need to use different pins for my shield, but I have no idea how to find out what pins are the right ones to use.
Update: Based on what I've seen and read, it looks like the particular combination of the Uno with this shield leaves me with no options but to use the hardware serial. A different shield or Arduino board would grant me options to separate my serial output from my xbee output, but that does not appear to be an option here.

If that shield has the xbee wired to the hardware serial pins (0 and 1) then no amount of creating software serial instances is going to rewire it.  There isn't much information on that shield in the link, is there a way to change what pins it is using?

That could be the case. I have no idea how I would change that--I haven't found much info on the shield either, and I'm not enough of an electrical guy to delve into it without.

The big lesson may be, "Always check for documentation BEFORE plunking down your money."   No matter how cool some device might seem, if it doesn't come with some sort of instructions then it is pretty much useless.

What position are the jumpers in?  Read this: https://www.arduino.cc/en/Main/ArduinoXbeeShield

To debug the sketch with SoftwareSerial, remove the jumpers from JP2 and JP3 and wire (with jumper wires) the middle pin of JP2 and JP3 to SoftwareSerial pins of your choice.
Middle pin of JP2 is TX of the Xbee so wire it to RX of SoftwareSerial. Middle pin of JP3 is RX of XBee.
On that particular board, JP2 is the jumper closer to the middle of the board, while JP3 is closer to the edge.
shield's schematics

You will need an xbee breakout board Xbee breakout board or this one from Sparkfun to do that...
Make sure you check if the board comes with headers as they are not always included. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the 2mm headers required for xbee and regular 0.1" headers required for connection to a breadboard or jumper wires etc.
Actually, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, but it is not connected to pins 0 and 1.
The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.
So on Leonardo, you can do Serial.println("Debug msgs"); and Serial1.println("xbee messages"); (note the digit 1 in Serial1). Of course other platforms such as Mega also can be used in the same way.
I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.
FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.
As soon as i moved to leonardo, it worked like a charm.


text:
Arithmetic mean for sensor
This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.
int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

void setup()
{
  Serial.begin(9600);
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
}

void loop()
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal > tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  }
  else if (tempreal < tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  }
  else if (tempreal >  tempMin && tempreal <  tempMax)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}

Edit by Edgar Bonet – The OP added in a comment to my answer:
“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”
Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:

You could use a moving average. It will update at each cycle whenever you take a new reading. Suppose you want to average over N readings:
double moving_average(double old_average, double new_value) {
    double new_average = old_average;
    new_average -= old_average/N;
    new_average += new_value/N;
    return new_average;
}

I edited the function above. I had typed one of arguments incorrectly.

it is not going to work.

Please elaborate why it will not work

I took the liberty to fix your code, as you forgot to declare new_average. The usual meaning of “moving average” is the one given in @DavidJ's answer. What you are proposing here is instead an exponentially weighted moving average. Essentially an implementation of @dannyf's answer. But note that the OP's problem cannot be solved by averaging: see the updated question.

"Please elaborate why it will not work" quite simple: both the old and new code suffer from one problem - you need to track the old_average exogenous, which is most of the challenges in such an implementation. you could have made that indigenous so your user only need to feed the code with the new_value and it will yield an average with one call.

Are you saying the code will not work because the call has to be made with two arguments?

My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work.

I had a similar problem. It turned out that I was reading writing and transmitting too fast. It means that since it seems that reading and writing can be interrupted during "their job", when you read a variable and in the same time someone is writing on that you're reading garbage. In my opinion this can be fixed by the application of "semaphores" or mutex or reducing the call of the reading. Randomly it would happen again but less frequently.
An idea can be found here
https://forum.arduino.cc/index.php?topic=132813.0
Best
Gian Maria

See Arduino Tutorials Smoothing
https://www.arduino.cc/en/tutorial/smoothing
Create an array to hold a series of readings. And a variable to hold the sum.
Incrementally cycle through the array, subtracting the oldest value from the sum and replacing it in the array with the current reading. Divide by the number of readings for the average.
Remember to allow for a delay in each reading as is appropriate for the sensor.

No need here for a moving average: it's simpler to just take N readings and get their average, as in my answer. But note that the OP's problem cannot be solved by averaging: see the updated question.

A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.
You can achieve similar results via exponential smoothing.
Yn = (1−α) Yn−1 + α Xn
Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.
With some thoughts, it can be done with integers and without loss of precision.
edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.
the sampled data is a simulated sine wave:
1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.
So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.

the window I picked is 4.
As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.

Memory is not a big issue if you are only averaging 5 values. And the OP's problem cannot be solved by averaging: see the updated question.

@dannyfI tried what you suggested but im getting real measurements too slow, it takes 10-15 sec to value stabilise. It looks more like this but it's too slow. link edit: maybe i shoud change alpha value?

Seems too simple. am I missing something?
--- arithmetic-mean.ino.orig    2017-04-27 19:37:01.386458500 +0200
+++ arithmetic-mean.ino 2017-04-27 19:38:14.458114972 +0200
@@ -16,8 +16,11 @@

 void loop()
 {
-  temp = analogRead(tempPin);
-  tempreal=temp * 0.48828125;
+  temp = 0;
+  for (int i = 0; i < 5; i++) {
+    temp += analogRead(tempPin);
+  }
+  tempreal = temp * 0.48828125 / 5;
   delay(1);
   if(tempreal > tempMax)
   {

@najkulime: Then you should rewrite your question. You asked about arithmetic mean, but that's not what you want: you want to sort out the valid from the invalid readings, which is a very different question.

Maybe add a tiny delay after the analogRead. It would be helpful if you could print the values you get to the serial port, and show us that.


text:
Receiving garbled `char` array returned by a function
I return a char[300] array from a function.  If I intialize a char* variable with it, the return is garbled, but not if I append it to a String.  What gives?
  const char* post2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  String postS2 = "";
  postS2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  //const char* post2 = { uploadHourCsv(timeNow,pulseChangeHour) };
  if( debug ) {
    Serial.print("received in loop() as : [");
    Serial.println(post2);
    Serial.print("String : [");
    Serial.println(postS2);
  }

...

char postStr[300] = "";
// populate array
if( debug ) {
  Serial.print("postStrCsv generated: ");
  Serial.println(postStr);
}
return postStr;

postStrCsv generated: 00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;
received in loop() as : [000?⸮@⸮⸮?" ⸮⸮?17.55;9|17.58! @0⸮⸮⸮⸮G% @5~`⸮h⸮?⸮⸮
String : [00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

What exactly does the uploadHourCsv return? Since post2 is declared as a pointer, without any size, the function has to return a pointer to an already allocated string to do this.

char postStr[300] with contents displayed in blockquote.

How is this Arduino specific? Despite two excellent (and upvoted) answers below, I say that such questions 1) belong on https://stackoverflow.com/ and 2) will get better answers more quickly tehre (no offence to those here)

tks.  do you think that we should move this to SO?  flag for moderator attention or flag to close saying "belongs in so"

It's because you're returning a pointer to a local variable.
You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.
When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.
It's pure chance that the data is still available and intact at the point of copying.
In short:

You must never return a pointer to a locally allocated (non-static) array.

Things you can do that are correct:

Pass an array pointer to the function to be populated by the function
Return a pointer to a statically allocated local array
Return a String object (though I wouldn't recommend using String for anything)

My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.
For example:
void myFunc(char *buf, int len) {
    for (int i = 0; i < len - 1; i++) {
        buf[i] = 'A';
    }
    buf[len - 1] = 0;
}

char myBuf[20];
myFunc(myBuf, 20);
Serial.println(myBuf);

--> AAAAAAAAAAAAAAAAAAAA

U da man! UPVOTED and ACCEPTED.  Re use of String: totally agree, unsafe memory allocation in String class.

Following Majenko's invaluable advice and incorporating another similar approach, final working implementation was to treat the function as a method to operate upon the char[300] array as "out parameter".
char postStr[300] =  "";
uploadHourCsv(timeNow,pulseChangeHour,postStr) ;
...

void uploadHourCsv(int unixtimeEvent, int pulseChange, char* postStr) {
  // prepare data and variables
  strcat(postStr, stationId);
  strcat(postStr,";3|"); // chuva hora
  strcat(postStr, dtostrf(rainHour,6,2,charDummy));
  ...
}

If you make the first strcat a strcpy instead, you can avoid initializing the array first.  (And note that the way you initialize it in the caller fills the entire length with zero bytes, not just the first element, so that takes a lot longer than necessary unless it gets optimized away.)


text:
Interfacing ADS8319 with Arduino UNO
I am using Arduino UNO and trying to interface 2 16-bit ADS8319 ADCs with it via the SPI interface.
I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15).
I am using the following code to get the values from the ADCs.
#include <SPI.h>
#define CONVPIN 7
#define SELPIN 8
#define SELPIN2 4
#define MISOPIN 12
#define SCLKPIN 13

int adcvalue;
byte byte1; byte byte2;
const float aRefVoltage = 5;
float volts = 0;

void setup() {

  // put your setup code here, to run once:
  pinMode(SELPIN, OUTPUT); // ADC's selection pin
  pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin
  pinMode(CONVPIN, OUTPUT); // ADC's conversion pin
  pinMode(SCLKPIN, OUTPUT); // ADC's clock pin
  pinMode(MISOPIN, INPUT);  // ADC's data out
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(CONVPIN, LOW);
  digitalWrite(SELPIN, HIGH);
  digitalWrite(SELPIN2, HIGH);
  digitalWrite(CONVPIN, HIGH);
  digitalWrite(SELPIN, LOW);

  delay(1000);

  byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8
  byte2 = SPI.transfer(0x00);  //transfer (read) the second 8 bits. D7-0

  adcvalue = (byte1 <<8) | (byte2 & 0xff);  // combine the 2 bytes to make our 16 bit word
  Serial.print("Voltage Value: ");
  Serial.println(adcvalue,BIN);
  volts = (adcvalue*aRefVoltage/65535);
  Serial.print(" Sensor Volts: ");
  Serial.println(volts,5);
  delay(1000);
}

However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.
Below is the screenshot for my schematic :

Your helpful suggestions and comments would be appreciated !
Thankyou.

Thanks for the sketch, it helped writing one for ADS8830.

Can you share complete circuit diagram, i want to do work on similar project but with different ADC

After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.


text:
Does blinking an LED with no resistor for a few seconds harm my Arduino?
I am new to Arduino and I just made my first LED blink. I connected the LED to ground and digital pin 13 without resistance (for only a few seconds). Does this harm my Arduino?
Hilmi

If you try it again with the proper resistor in place, and the pin still works, then no, you probably haven't damaged it. It may have stressed the pin driver some but if it passes the above test, I think you're still good to go.


text:
What does this notation stands for? Wire.read() <<8 | Wire.read()
I'm using the Arduino's site test code for getting raw values from a MPU-6050 accelerometer + gyro. In the loop, there are this lines for getting the next data from its registers:
Wire.requestFrom(MPU_addr, 14, true);  // request a total of 14 registers

AcX = Wire.read()<<8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read()<<8 | Wire.read();  // 0x41 (TEMP_OUT_H)   & 0x42 (TEMP_OUT_L)

GyX = Wire.read()<<8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

Hex numbers indicates, of course, the address of each register. However, I can't get how, if the first instruction only requests from the MPU_addr (constant), it changes to the consecutive registers. Is it that <<8| makes something like a sum or a logic OR to switch the register to read?
Regards!

Left shift 8 bits, then bitwise OR. Turns two 8-bit values into one 16-bit value.

Just trying to find the duplicate I know is there (cus I answered it). Closest I can find right now is: http://arduino.stackexchange.com/questions/19243/and-syntax-in-arduino/19244

One important thing to note though is that the use of Wire.read() inside the shifting and ORing like that is not good. There is no guarantee that the Wire.read() functions will be called in the right order. You should read into variables first then work with those variables. http://en.cppreference.com/w/cpp/language/eval_order

I see, it's a point I'll have to considerate with my own design. Though, actually, I prefer to work with variables instead of functions. Thanks for the advice!

@Majenko, are you sure ? I tried to read that page about the the order of evaluation, but it is very hard to understand for me. Since it is the same function called twice and it is I/O function, the compiler should understand that there is a order. The origin of the code is here: http://playground.arduino.cc/Main/MPU-6050#short

In practice it is usually ok, but there is no guarantees. And what works in one version of the compiler may stop in another. Also Arduino playground isn't the most reliable of sources for good quality code.

Just adding a couple of points to Michel Keijzers's answer.
The expression Wire.read() << 8 takes the value returned by
Wire.read(), which is an int, and shifts it 8 bits to the left,
which is equivalent to multiplying by 256. If you are using a 32-bit
microcontroller (e.g. an Arduino Due), this is safe. However, most
Arduinos are based on an 8-bit AVR chip. On them, an int is 16-bits
and can only hold values up to 32767. If the initial value is larger
than 127, then the bit shift causes a signed integer overflow, which in
C and C++ is undefined behavior (read: “illegal operation”). It is
likely that everything runs fine and you get the expected result, but
it is unwise to ever rely on undefined behavior in C or C++.
The proper way to do the shift is to cast the initial value to an
unsigned data type, which is always safe v.s. overflows, and then do the
shift, like in
((uint16_t) Wire.read()) << 8

You may omit the outer parentheses if you know your operator priorities.
The second point is about the already mentioned fact that the order of
the reads is not specified. The simplest fix is to do one read per
statement, as in:
AcX = (uint16_t) Wire.read() << 8;  // first read MSB
AcX |= Wire.read();                 // then LSB

It is worth noting that the first statement has an implicit cast from
uint16_t (the result of the shift) to int16_t (the type of AcX).
This can also overflow if the shifted value is larger than 32767.
However, an overflow happening during a conversion in not undefined,
but rather implementation defined behavior. This means that the
authors of the compiler must decide and document what happens. Arduino
code is usually compiled by gcc, and the gcc docs document this
behavior as

• The result of, or the signal raised by, converting an integer to a
  signed integer type when the value cannot be represented in an object
  of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).
For conversion to a type of width N, the value is reduced modulo 2^N
  to be within range of the type; no signal is raised.

This is exactly what we want here, and since it is the most efficient
choice on a two’s complement architecture, it seems unlikely that
another compiler would make a different choice.

Such a great explanation!

1 << 3 means the value 1 shifted 3 times to the left. So 1 in binary is 0000001, shifted left 3 places is 00001000. And 0001101 << 3 will be 1101000.
The | command is a logic or (where bits will be 1 if one of the bits is 1, e.g. 001100 | 001001 = 001101.
Probably every Wire.read() gives the next byte.
For the first line: Acx = Wire.read() << 8 | wire.read() means one (mostly the first byte) is read, it is shifted to the left one byte and the other (mostly next byte) read is placed in the right. So it results in the first two read bytes to be positioned in AcX. It is semantically the same as Wire.read() * 256 + Wire.read(), but normally a bit shift is easier for a computer, same as | and the + operator.

I got it, it seems as you said that it composes a word with those two bytes,  because item's datasheet indicates that in each pair, one register has the high bits and the other one the low bits. Thank you.

You are welcome, and yes, the high 8 bits go into the first part of the pair, and the next (low) 8 bits go in the second part.

“For the first line: Acx = Wire.read() << 8 | wire.read() means the first byte is read, it is shifted to the left one byte and the next byte read is placed in the right” is incorrect.  It should instead say, “For the first line: Acx = wire.read() << 8 | wire.read() means that two bytes are read, one of them is used as MSB, and the other as LSB”.  That is, according to the C standard N1570 §6.5.2, without parenthesization it is undefined which wire.read() is first and which is second.  Of course it often is the case they are used in the order you mentioned, but it's undefined here.

@jwpat7 yes you are right ... I will update the answer


text:
Loop code without manually pressing the button
In a piece off code I am modifying I have a button connected to start the code and then it resets its self afterwards. Is they a way to make the arduino loop that code without manually pressing the button again?
This is a section off the code:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN 6
#define BUTTON_PIN 9

Adafruit_NeoPixel strip = Adafruit_NeoPixel(120, PIN, NEO_GRB + NEO_KHZ800);

bool oldState = HIGH;
int showType = 0;

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from high to low (button press).
  if (newState == LOW && oldState == HIGH) {
    // Short delay to debounce button.
    delay(20);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);
    if (newState == LOW) {
      showType++;
      if (showType > 9)
        showType=0;
      startShow(showType);
    }
  }

  // Set the last button state to the old state.
  oldState = newState;
}

void startShow(int i) {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
  resetFunc();  //call reset
}

Thanks Reece

https://pastebin.com/BULf5CfQ

Remove the loop() function, and rename void startShow(int i) as void loop().

Move startShow(showType); to just above   oldState = newState;. That way it get called al the time, and the button still changes the showType.

Could you describe more clearly what you want to happen please? Do you want to wait for the button to be pressed then do the LED stuff forever?

Yeah that is correct I want to wait for the button press then for the led's loop forever.

If you want the led stuff to loop forever, why are you resetting the board at the end of that function?  Why not just let loop call it again?

As pointed out by Delta_G, there is no point in resetting your program.
What you should do is think your program in terms of the Arduino logic:

You put in setup() the code you want to run when your program
starts.
You put in loop() the code you want to run over and over again.

In this case loop() is fairly simple, as the stuff you want to run
over and over again is the animation, thus:
void loop() {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

Note that I removed the call to resetFunc().
The stuff you want to do at startup is the initialization. Oh, wait. In
a comment you wrote “I want to wait for the button press”. So this also
has to be done before the program starts looping. Hence your setup()
should initialize stuff, then wait for the button press:
void setup() {
  // Initialize the strip to all piwels off.
  strip.begin();
  strip.show();

  // Wait until the button is pressed.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  while (digitalRead(BUTTON_PIN) == HIGH)
      ; // do nothing
}


text:
Is there a test framework for Arduinos?
I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.
EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.

afaik there is not such thing ... for some libraries I created my own 'stubs', with some smarter than others to test my specific application.

You could simulate an Arduino, sure, but that will be of little to no value. You need to simulate the entire system, including external stimuli. And that system is unique to you - so who would write a simulator for that...?

Yes ... I mimiced the use of a DMX library to show all the to-be-connected lights to be shown on a PC instead as sets of pixels turning on and off ... so in your case you might have to stub it in such a way that is appropriate for you.
A good start is to write all libraries NOT related directly to the Arduino or hardware and test them on a PC and when working correct, copy them to the Arduino project.

In the PlatformIO there was some --target test, but I haven't investigate how it's meant to be used or so...

Why don't you use any common C++ unit testing framework, and provide a simulated/faked/mocked-up version of the Arduino libraries? After all, you don't have direct hardware access with them.

@thebusybee because the Arduino IDE uses a custom C++ compiler that does not have most of the C++ libraries available in other C++ compilers (e.g. g++). This includes CPPUnit and object oriented error handling (try, catch, throw statements and error objects). While the assert library is available, it's not ideal. Also, most of our libraries do have direct hardware access.

I don't mean to run the tests on the Arduino. Use your PC. You want to test your code, not the compiler. -- So you want not only the application tested, but mainly the libraries that use direct hardware access. Well, that has nothing in common with Arduino.

It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.
Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?
Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.
Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


text:
How to Run Stepper motor through Serial Communication
I am trying to run a Stepper motor from my c++ application, from which I sent commands but its not running not sure why would it not run, outside serial check it run but inside serial check it not run.
Here is my code, not sure what am doing wrong, my first time with Arduino.

#include <AccelStepper.h>

#define BAUD 9600

// CNC Shield V3  Step and Dir pins on Mega 2560
#define step_pin_x 2
#define dir_pin_x 5
#define MOTOR_X_ENABLE_PIN 8
// Drive A4988
#define motorInterfaceType 1

AccelStepper stepper_X = AccelStepper(motorInterfaceType, step_pin_x, dir_pin_x);

void setup() {
  Serial.begin(BAUD);
  pinMode(53, OUTPUT);   // for red led it pin # 53
  pinMode(MOTOR_X_ENABLE_PIN, OUTPUT);  // for X stepper motor

    stepper_X.setMaxSpeed(1000);
    stepper_X.setSpeed(500);
}

void loop() {
    String input;
  //If any input is detected in arduino
  if(Serial.available() > 0){
    //read the whole string until '\n' delimiter is read
    input = Serial.readStringUntil('\n');

    if (input.equals("ON")){
       digitalWrite(53, HIGH);   // Turn ON RED LED
       stepper_X.runSpeed();      // Suppose to run stepper motor .. but not working
       Serial.println("X Motors:: "+input);

    }else if (input.equals("OFF")){
       stepper_X.stop();
       digitalWrite(53, LOW);    // Turn OFF RED LED
       Serial.println("X Motors:: "+input);
    }

  }else{
  //  stepper_X.runSpeed();      // if uncommented stepper motor will run
  }
}

Update
so it seems its code blocking issues
i update my code according to tut : https://majenko.co.uk/blog/reading-serial-arduino
    char buf[80];

    int readline(int readch, char *buffer, int len) {
        static int pos = 0;
        int rpos;

        if (readch > 0) {
            switch (readch) {
                case '\r': // Ignore CR
                    break;
                case '\n': // Return on new-line
                    rpos = pos;
                    pos = 0;  // Reset position index ready for next time
                    return rpos;
                default:
                    if (pos < len-1) {
                        buffer[pos++] = readch;
                        buffer[pos] = 0;
                    }
            }
        }
        return 0;
    }

void loop() {
   if (readline(Serial.read(), buf, 80) > 0) {
   if(strcmp("n", buf) == 0){
          digitalWrite(53, HIGH);
         stepper_X.setMaxSpeed(1000);
         stepper_X.setSpeed(500);
          stepper_X.runSpeed();
          Serial.print("All Motors:: ");
          Serial.print(buf);

        }
    }
}

now its working ok
Update 2 : c++ sending command via Serial
    std::string input_command = "ON";
    //Creating a c string
     char *c_string = new char[input_command.size() + 1];
     //copying the std::string to c string
     std::copy(input_command.begin(), input_command.end(), c_string);
     //Adding the delimiter
     c_string[input_command.size()] = '\n';

// using this serial lib : https://github.com/manashmndl/SerialPort
   writeSerialPort(c_string, MAX_DATA_LENGTH);

Have you checked, if the data get's correctly transmitted by echoing it back and showing it in your application?

@chrisl ya data reached correctly even i get reply from Arduino like X Motors ON  , OFF etc

Are you sure you are sending "ON\n" rather than "ON\r" or "ON\r\n"?

@EdgarBonet  Yes am Sending "ON\n"  .... the red LED turn ON and OFF with ON/OFF command which mean that if (input.equals("ON"))  check become valid also i get reply that X motor :: ON

Per the documentation of the AccelStepper’s runSpeed()
method:

You must call this as frequently as possible, but at least once per
  step interval,

It appears the AccelStepper library is not compatible with blocking
code. Not a big deal, blocking code is almost always bad practice
anyway. However, Serial.readStringUntil() is a blocking function: it
will prevent the program from doing any useful work.
You have to read the serial port in a non-blocking fashion,
use the commands to set the motor speed, and always call runSpeed() as
frequently as possible.

Botne , thanks for valuable information , one another Question i have , i noticed serial communication is slow , i mean it take about 2 sec to arduino to get message and the motor start moving , so can you tell how to make it robust , i mean something like real time communication , as am working on SMT project so i will need to move stepper motors to their locations fast as soon as possible  but this is slow it take about 3 sec to get response and then motor move

@user889030: Slow communication is most commonly the sign of a Stream input method timing out. For example, readStringUntil() times out when it can't find the terminator character in the input stream (are you sure you send the '\n'?). The default timeout duration is one second. See here the list of timeout-based Stream methods. You shouldn't have this problem if you do send the terminator character, or if you parse the input stream as in Majenko's tutorial.

Botnet  ya ma sending '\n'  with it , you can see i added some c++ code  , thanks


text:
ESP8266 - Webserver not working in loop
I have simple example, where in loop is called webServer to handle clients and also text drawing on display.
The thing is that webServer is not responding, but when I remove second part of loop - drawing text to display then web server starts to work normally.
Server does not respond:

 void loop() {
      server.handleClient();
      unsigned long timeNow = millis();
      if ((timeNow > screenChangeTime))  {
          display.clear();
          display.setFont(ArialMT_Plain_16);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
           display.drawString(12, 20,"Loaded: "+String(particles));
           screenChangeTime= timeNow + delay;
           display.display();
      }
    }

Server responds:
void loop() {
      server.handleClient();
}

it is possible that the watchdog triggers because the loop() was taking to long.

Your way of handling the milliseconds is not correct; at the roll of the millis counter you will have problems. Better to use the usual way (if ((millis() - previousTime) >= screenChangeTime) { previousTime += screenChangeTime; ... })

@frarugi87 while that may be an issue in the long run (in about 49 days 17 hours after power-up) it is unlikely to be the issue here.

@Phil if the screenChangeTime variable is not unsigned long (even if I doubt that it isn't) it has problems much sooner. In any case, I know it is not the issue here, and in fact it was a comment, not an answer.

I have seen this kind of problem on Arduino capable devices like Adafruit Trinket when running out of memory.  I get that you are using the ESP8266 chip but still check to see if you have memory constraints.

My guess is, that you're wasting too much time within the drawing-part.
What is the value for delay? I guess you have a number too low chosen here. And you should really set this new time after you have updated the display by display.display();.
Your webserver doesn't respond because he's not called often enough inside this code.

The purpose of the if statement is to not draw every time, it's also not a blocking function.


text:
How do you debug SPI connected devices?
EDIT: Changed the title to better express what I'm after.
I've been dabbling in connecting two Arduino Nano 3's with the RFM69HCW breakout for the past 5 days.. but got nowhere.
I've followed the official hookup guide at first, after that didn't work, I've tried the code samples from a Adafruit post, and still nothing.
By 'nothing', I mean that I compiled and uploaded the code to two separate Arduinos that are literally 5cm apart, tried sending messages, broadcasting messages.. etc. but without any success.
Here they are - on two breadboards, but the layout and connections are symmetrical:

Yeah, the bottom one is quite confusing to look at because of the wires, but I lent most of them to friends - so I had to improvise.
To clarify the picture, I connected the Arduino as follows:

D2 -> INT(Interrupt)
D10 -> SS
D11 -> MISO
D12 -> MOSI
D13 -> C(Clock)

One of the codes that I tried: (This is from the official guide, but modified slightly)

#include <RFM69.h>
#include <SPI.h>

#define NETWORKID     0
#define MYNODEID      1 //2 For the other Arduino
#define TONODEID      255

#define FREQUENCY     RF69_915MHZ

#define ENCRYPT       false // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes

#define USEACK        true // Request ACKs or not

RFM69 radio;

void setup()
{
  Serial.begin(9600);
  Serial.print("Node ");
  Serial.print(MYNODEID,DEC);
  Serial.println(" ready");

  radio.initialize(FREQUENCY, MYNODEID, NETWORKID);
  radio.setHighPower();
}

void loop()
{
  static char sendbuffer[62];
  static int sendlength = 0;

  if (Serial.available() > 0)
  {
    char input = Serial.read();

    if (input != '\r')
    {
      sendbuffer[sendlength] = input;
      sendlength++;
    }

    if ((input == '\r') || (sendlength == 61))
    {
      Serial.print("sending to node ");
      Serial.print(TONODEID, DEC);
      Serial.print(", message [");
      for (byte i = 0; i < sendlength; i++)
        Serial.print(sendbuffer[i]);
      Serial.println("]");

      if (radio.sendWithRetry(TONODEID, sendbuffer, sendlength))
        Serial.println("ACK received!");
      else
        Serial.println("no ACK received");

      sendlength = 0;
    }
  }

  if (radio.receiveDone())
  {
    Serial.print("received from node ");
    Serial.print(radio.SENDERID, DEC);
    Serial.print(", message [");

    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);

    Serial.print("], RSSI ");
    Serial.println(radio.RSSI);

    if (radio.ACKRequested())
    {
      radio.sendACK();
      Serial.println("ACK sent");
    }
  }
}

Notes:
Everything is powered by a 5V 2A brick - the RFM69 modules are receiving a stepped down 3.3V from those small thingies connecting two separate breadboard power rails.
Also... I don't have any 915MHz antennas, so I used some 433MHz ones that I had laying around - I'm going to get correct ones later, but right now, for testing them 5cm apart it should be good enough..?
P.S.: I HATE when stuff doesn't have status LEDs, I could really use some on the radio modules.

You want to get yourself a cheap USB logic analyser (you can pick them up on places like eBay, DX, Ali, etc for about $6) so you can see what is actually happening on the SPI bus.

@Majenko Oh yeah, I could do that - probably good in the long run when I will do more complex stuff later on. I'm just curious if anyone could spot any mistakes with my setup, because I have no idea what to do until I get a analyser.

Have your code read and print key registers from the part to verify that the SPI is working.  You'll need to look into the library internals to do this.

I'll look into that, luckily the library has all of the registers defined in RFM69registers.h header. Thanks for the suggestion :)

Did you miss this in the hookup guide: IMPORTANT! Do not power your RFM69 with 5V or connect the data lines directly to a 5V microprocessor. Doing so will damage the device.

Huh, now I feel kinda stupid. I didn't realise that.. and I KNOW that the logic pins are indeed 5V on the Arduinos that I own... welp.. gonna get some 3.3V (like a... LC33) voltage regulators and hope that those things still work.

Unless I can do a resistor voltage divider - though I don't see the current (for logic pins) specified anywhere in the datasheets.


text:
TSX0108 logic level converter not working
Am trying to setup logic level converter with arduino for eps8266 WiFi module. Am using this logic level converter but it’s not working not sure what am doing am not getting any output.
My circuit
Red wire : 3.3v power source
Orange wire : 5v power source
Blue wire : ground.
Yellow wire : arduino TX1 on B2
White wire : output on A2

Multi meter it red wire : 3.3 v showing on display

Multi meter it orange wire : 4.68 v showing on display

Multi meter it yellow wire : 4.36 v showing on display

**Multi meter it white wire : no voltage showing on display ??? **

Update : have set OE pin to enable and swapped red and orange. Still no output for yellow wire

power the 5 V side with 5 V and the 3.3 V side with 3.3 V (swap orange and red wre)

@Juraj i switched orange and red wire  but no output yet , can u check updated image i added

try with a pin set HIGH

@Juraj ya TX RX  pins of arduino are always high , i can get voltage when on multi meter when connect it with yellow wire, but in front of no voltage on white wire.

datasheet of TXB0108: "The A  port is designed to track VCCA. VCCA accepts any supply voltage from1.2 V to 3.6 V. The B port is designed to track VCCB. VCCB accepts any supply voltage from 1.65V to 5.5 V." "The TXB0108 is designed so that the OE input circuit is supplied by VCCA.". did you damage it with 5 V?

hmmmm seems its burned out , i will buy another one then will try

When the output-enable(OE) input is low, all outputs are placed in the high-impedance (Hi-Z) state.  You must connect the OE pin to logic high to enable the outputs.

hmmmm no success i have set OE to high but no output for yellow wire yet , can you check updated image i added


text:
Arduino How to Concat Strings
am stuck with something simple which is concating string not sure what am doing wrong , am getting exception (3 ) error due to it
3   LoadStoreErrorCause Processor internal physical address or data error during load or store

my code
    String HOST = "useotools.com";
    String API_URL = "/iot/api.php";   // API URL
    uint16_t HTTPS_PORT = 4000;  // HTTPS port
    uint16_t HTTP_PORT = 4001;  // HTTP port

void https_request_function(){
String HOST_URL = "http://"+String(HOST)+":"+String(HTTP_PORT)+String(API_URL)+"";

}

when first time https_request_function() is called then HOST_URL is displayed correctly and on 2nd time when this function is called by code it trigger exception(3) which is strange .

see CStringBuilderExample in my StreamLib (it is in Library Manager)

related: https://stackoverflow.com/q/308695/3984613 (as this is not entirely specific to Arduino)

@Ghanima thanks i tired like this but still on 2nd call it print weird boxes
snprintf(HOST_URL, sizeof HOST_URL, "%s%s%s%d%s", "http://",HOST.c_str(),":",HTTP_PORT,API_URL.c_str());

@Juraj that string builder lib not exists in esp boards :(

https://platformio.org/lib/search?query=streamlib

@Juraj thanks :)


text:
Sampling rate of multiple analog pins on Arduino
as I checked on Arduino website, they mentioned all boards: UNO, Nano, Mini, Mega have maximum sample rate 10kHz for each analog pin. So my concern is:
1) is there any difference between sampling rate when reading a single analog pin and multiple analog pins? For example, if we read only 1 analog input, maximum sample rate can reach 10kHz. How about maximum sample rate when we want to read 6 analog inputs? Maximum sample rate will be 10kHz or (10/6)kHz? Can we do analog input reading simultaneously or not?
2) What if I want to get sampling rate at least 1kHz for each Arduino board (assume 5 analog inputs)?
3) In case we need to connect several Arduino boards via I2C or SPI protocol, is sampling rate related to these 2 protocols?

1)  You only have one ADC on board and all the pins run through a mux.  You can only read one pin at time.  If you're willing to give up some resolution then you might can read a little faster but it gets tough.  What's worse is that when you are switching pins really fast it can mess with your readings so that for some things, especially when input impedance is high, you have to read twice and throw away the first reading.  So that essentially cuts your sampling rate in half right there.
2)  That may be doable.  Or at least something close to it.  You'd run in free-running mode and write a tight ISR to read the interrupt when the analog read is finished and record every other value and switch the pin every other time.  Theoretically you should get pretty close to 1kHz with 5 pins.  Maybe a little faster if you give up a little resolution.
3)  Those communications protocols run at light speed compared to the analog read.

What if I need to get sample rate 5kHz for each analog input? Only use 1 analog pin in each Arduino board? Is there any better way?

Get an ADC chip.  They make some really fast ones.  That would make more sense than buying a bunch of Arduino's.

Thanks. By the ways, is there any correlation between baud rate & sample rate? Can you share me a sample code how to do the sample rate settings?

Baud rate is how many bits per second a serial connection sends out.  Sample rate is how many samples per second of a measurement you take.  Thye are two completely different concepts.

I'm sure professor google can find examples of how to run the ADC on the Arduino in free running mode.

Can you suggest me an external ADC chip for 30 analog inputs at sample rate 100Hz? I guess Arduino Mega and 1 ADC chip is ok. Because if we use 2 Arduino Mega connected via I2C, the code maybe more complicated.

I don't know any off hand.  I usually just go to Mouser.com and search there.  They've got a nice search filter feature.


text:
SoftwareSerial with ESP8266
I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i programmatically send particular AT commands there is no response.
For eg:
I type AT in serial monitor I get OK
But if i send the following through SoftwareSerial pins
mySerial.println("AT");

there is no response.
Can anyone tell what will be the solution as to how to send AT commands explicitly.
The sketch is
#include<SoftWareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
  delay(100);
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
}//setup

void loop()  {
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
  while (Serial.available()>0 ) {
    mySerial.write(Serial.read());
    delay(100);
  }
}//loop

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.
I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.
Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

How is it wired? What pins are you using? Show your sketch.

Can you confirm that you have it wired with the transmit pin on the Arduino going to the receive pin on the ESP8266 and vice versa?

I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.
If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.
I found, for example, that the AT+CWJAP (join access point) command takes quite a while, like 10 seconds or so.
Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.
If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. OK, ERROR etc.).

Thank you for your insight.                                                                        I have done that too. I have added a specific timeout for each command and checked if the software serial has any response after the timeout, but again there is nothing.                                                                                Regarding checking for the response string I did that. For "AT" after a delay of 1sec, I checked if there was any "OK" but again the efforts were in vain. I tried changing the delay. Nothing happened.

Are you sure it is running at 9600? I found mine was configured to run at 115200 baud. I tried changing the delay. Nothing happened. - please amend your question to show the code which incorporates my suggestion.

Same problem here with this code.
Three step for me to make it work :

Use method write() and not println()
Send newline \n when talking to esp8266
don't wait newline to print the response
esp8266Serial.write("AT\n");
delay(100);
while (esp8266Serial.available() > 0 ) {
  char ch = esp8266Serial.read();
  Serial.println(ch);
}

I hope it helps

It appears to me that when the ESP8266 sends a few characters to the Arduino, the initial version of the code always erases those characters (data="";) without ever printing anything to your serial monitor.
So there is no way to tell whether the ESP8266 is sending anything or not.
To make it easier to debug, try printing every character from the ESP8266 to the serial monitor, whether or not it makes a complete message.
What do you see on the serial monitor with the following code?
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

String data = "";

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

void loop(){
  if( mySerial.available()>0 ){
    char ch=mySerial.read();
    data.concat(ch);
    Serial.print((int)ch, HEX); // debug: print *every* character, in hex.
    if( ch=='\n' ){
      Serial.println();
      // Use "F()" macro as recommended by
      // https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram .
      Serial.print(F("complete message:"));
      Serial.println(data);
      data="";
      Serial.print(F("waiting for next message ..."));
      }
  }
  if( Serial.available()>0 ){
    mySerial.write(Serial.read());
  }
}//loop

Did you make sure that your lines end with \n\r?
Remember you need both newline characters to send over the line from the terminal.

Did you mean to type "\n\r?" Off hand I can't think of what '\l' would be, but it is late… That said, I would expect the newline ('\n') to be sufficient.

The ESP8266 needs 115200 baud.
The example didn't run clean in my case until I increased the baud rate for the Arduino<->Computer (USB) communication to 115200 baud as well. With 115200 on mySerial and 9600 on USB, an AT request of mine did not return an OK in most cases.

in AT firmware you can set the baud rate. SoftwareSerial can't run at 115200 so must lower baud rate be set for AT firmware


text:
NODEMCU vs AT for esp8266
I have recently started working on esp8266 wifi module and arduino uno.
I am a little confused.
I have created a small Web page with esp8266 AT commands.
Now I want use it for receiving data such as changes on the Arduino inputs.
I have seen many similar implementations using jQuery for that purpose,
but I don't know where to place that jQuery file.
Furthermore, is it possible to use NODEMCU firmware and still toggle arduino pins and transmit data to esp8266?
I want to use Arduino for:

reading voltage levels
publish the values read to the Web page
toggle a relay when a button on the Web page is pressed.

Please kindly help me out or point me in the right direction to search

This is quite a huge topic to cover in one answer, but I will do my best.
The NodeMCU can be used in three distinctly different ways.  First is the AT mode, where you have installed the AT firmware.  In this mode the NodeMCU is purely a slave device to the Arduino.  Once you have got the Arduino to configure the NodeMCU in the right way to receive data on a socket it will send that data back to the Arduino verbatim through the serial port with special tags added (indicating what the data is, and which socket it arrived on, etc).  It is then up to you to receive that data, interpret it in whatever way you desire (as a HTTP GET request most likely) and craft the correct response (if any) and send it to the NodeMCU to send back (again using the AT commands).
What you send through the socket is entirely up to you.  By the sounds of things you will be making a simple GET request from a web browser to perform an operation, and maybe respond with some data to display in the web page.  That can be easy, or it can be hard - it's as hard as you want to make it.  The simplest way is to rely on an external web server to serve the main content and structure of the page, then use jQuery or Prototype to make an AJAX call to your NodeMCU and receive back any data there may be.  In this case everything will be on your external web server except the single (or few) URL(s) that perform operations and return data.  That includes the jQuery (which is just Javascript, it's loaded from your web server into the browser and executed), any code for buttons, images, HTML, everything (on the web server, that is).
The other two ways the NodeMCU can operate are both very different to that.  They differ mainly in the language that is used with them.  You can use the NodeMCU with its own LUA language to get it to do almost anything you want.  That includes receiving the HTTP GET request and serving the data for it, all without the help of the Arduino.  In fact, doing that, there is little need for the Arduino any more - the NodeMCU has an analog input and multiple digital IO lines - it also has SPI available for interfacing with external ADC chips if you want more than one analog input.  So you can have everything internal to the NodeMCU without needing the Arduino at all.  If you do want to keep the Arduino then you can interface to it through the serial port (as you would in AT mode) but using your own custom protocol in whatever way you see fit.
The third way is to program the NodeMCU as if it were itself an Arduino.  There is an ESP8266 core for the Arduino IDE (and for UECIDE Beta as well) which allows you to program the NodeMCU in the same language and with a similar API, as the Arduino.  This even more removes the need for the Arduino.  You can get the Arduino core from Github here: https://github.com/esp8266/Arduino
Incidentally, the Xtensa core in the ESP8266 is considerably more powerful than your typical Arduino, being 32-bit, having its own DSP, and with much more RAM and Flash memory.  It kind of makes the Arduino redundant.


text:
Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi
I'd like to assemble a device that could accomplish the following:

Connect to my home wifi (WPA2-Personal)
Connect to my home PC with via Ethernet cable
Able to send WoL signal to the PC when getting a signal over wireless connection
The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).
I have no background in Arduino or Electronics in general. I program well though and learn fast.
Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?

Raspberry Pi sounds like the more appropriate option for you, as said by Mr Kim below. A useful thing about the Raspberry Pi is that you can put a lite operating system on it which makes it a lot easier to do networking stuff and run by itself. It's not that Arduino can't do it in theory, but in practice it isn't designed for that purpose. The latest Rasp Pi (2B+ or something) also has a decent amount of ram, and in general you use an SD card for memory so is more flexible in that sense.

Why do you need both wifi and ethernet. Just connect the arduino via ethernet to your router. You can send WoL packet from anywhere inside the network. You don't need a direct connection to the PC.

@Gerben the PC is connected to the router wirelessly. So will be the device. But the device will be also connected to the PC physically via ethernet, so it will be able to send WoL. Make sense?

Why not send the WOL via wireless as well. That way you don't need an ethernet shield. Also, why does the device need to be near the PC?

@Gerben To receive WoL on wireless, PC need to be powered up. It's the PC that does WPA, not the wireless network card. If PC is shutdown there is nothing that can actually receive and decrypt the wireless signal. Even if you take decryption out of equation (which in any practical set up you really can't) it's still not workable, because unlike Ethernet card a WiFi card need actively "scan" for wireless signals to receive them, and as a rule they do not do this when PC is powered off.

That makes sense. I didn't think of that. Alternatively you could connect the power button to an arduino pin and wake the PC that way. Just an idea.

@Gerben, yep, that would work too, still need WiFi though.

The Arduino might not be a choice for you. The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).
So, if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.
You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.

The Raspberry Pi is definitely the easiest way to do this, however it will use more power.
You can do it within your budget by using Arduino clone hardware from places like AliExpress.
If you don't mind the extra effort, it certainly can be done using the Arduino and a wireless and ethernet shield.
A WiFi shield is around $17, an ethernet shield is less than $6 and an Arduino Uno clone is around $3. Make sure you can combine these shields (I haven't checked). There's also a combined Linux, Ethernet + Wifi Yun shield for around $30.

I doubt if you will do it in that price range. Buying genuine products (as opposed to clones from eBay) you would be paying something like:

Arduino Uno: $US 25
WiFi shield: $US 40
Ethernet shield: $US 45

Prices from Adafruit - other suppliers would have the same or similar for similar prices.
I see there is a Arduino Ethernet which combines the Uno and the Ethernet shield for $US 65.

The whole set up needs to be less than 45USD, desirably much less ...

Maybe someone else can suggest a cheaper option, but I think you will be pushing it here.


text:
Voltage reading problem in Arduino mega based 10 cannel battery capacity tester
I want to make a 10 channels Arduino mega-based battery capacity tester using 4.7 ohms 10w resistors controlling them with IRFZ44n MOSFETs with respected digital pins. An 8.4V battery powers the Arduino (do not consider the buck converter in the picture). I am debugging my project step by step. When I read voltages of individual batteries by corresponding analog pins without turning On 'MOSFET-Gate pins' then Arduino measures the voltages correctly but when I turn on the gate pins then Arduino measures voltage incorrectly. Meaning if I connect
a battery with an analog pin and a multimeter at the same time and the value is pretty much same. Like 3.70 volt for the multimeter and 3.72 for analog pin but when I turn On the gatepin of the MOSFET then Arduino value is like 3.07V and Multimeter value is 3.48V.
Thanks in advance.
Here is the Circuit Diagram of my project:

Simple version to understand:

Code:
long readVcc() {
   // Read 1.1V reference against AVcc
   // set the reference to Vcc and the measurement to the internal 1.1V reference
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
   ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
   ADMUX = _BV(MUX5) | _BV(MUX0) ;
#else
   ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
   ADCSRB &= ~_BV(MUX5);
   delay(2); // Wait for Vref to settle
   ADCSRA |= _BV(ADSC); // Start conversion
   while (bit_is_set(ADCSRA,ADSC)); // measuring

   uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
   uint8_t high = ADCH; // unlocks both

   long result = (high<<8) | low;

   result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000   //1126400L internalRefVolt(1.1) * 1023 * 1000; code can more precse by calculating internalRefVolt(1.1)
   return result; // Vcc in millivolts
}

void setup() {
   Serial.begin(115200);
   delay(3000);
   pinMode(22,OUTPUT);//***Mosfet Gate Pins********
   pinMode(23,OUTPUT);
   pinMode(24,OUTPUT);
   pinMode(25,OUTPUT);
   pinMode(26,OUTPUT);
   pinMode(27,OUTPUT);
   pinMode(28,OUTPUT);
   pinMode(29,OUTPUT);
   pinMode(30,OUTPUT);
   pinMode(31,OUTPUT);

   digitalWrite(22,LOW);//***Initially low the Mosfet Gate Pins********
   digitalWrite(23,LOW);
   digitalWrite(24,LOW);
   digitalWrite(25,LOW);
   digitalWrite(26,LOW);
   digitalWrite(27,LOW);
   digitalWrite(28,LOW);
   digitalWrite(29,LOW);
   digitalWrite(30,LOW);
   digitalWrite(31,LOW);
}

/**********************************Void Loop******************************************************/
void loop() {
   float voltRef = readVcc() / 1000.0;

   digitalWrite(22,HIGH);//*** High the Mosfet Gate Pins********
   digitalWrite(23,HIGH);
   digitalWrite(24,HIGH);
   digitalWrite(25,HIGH);
   digitalWrite(26,HIGH);
   digitalWrite(27,HIGH);
   digitalWrite(28,HIGH);
   digitalWrite(29,HIGH);
   digitalWrite(30,HIGH);
   digitalWrite(31,HIGH);

   float volt0 = analogRead(A0)*(voltRef/1024);
   delay(10);
   volt0 = analogRead(A0)*(voltRef/1024);
   /* if(volt0>3.0){
      digitalWrite(22,HIGH); // High = Mosfet ON
      digitalWrite(36,HIGH); // High = LED Turn OFF

      }*/

   float volt1 = analogRead(A1)*(voltRef/1024);
   delay(10);
   volt1 = analogRead(A1)*(voltRef/1024);

   float volt2 = analogRead(A2)*(voltRef/1024);
   delay(10);
   volt2 = analogRead(A2)*(voltRef/1024);

   float volt3 = analogRead(A3)*(voltRef/1024);
   delay(10);
   volt3 = analogRead(A3)*(voltRef/1024);

   float volt4 = analogRead(A4)*(voltRef/1024);
   delay(10);
   volt4 = analogRead(A4)*(voltRef/1024);

   float volt5 = analogRead(A5)*(voltRef/1024);
   delay(10);
   volt5 = analogRead(A5)*(voltRef/1024);

   float volt6 = analogRead(A6)*(voltRef/1024);
   delay(10);
   volt6 = analogRead(A6)*(voltRef/1024);

   float volt7 = analogRead(A7)*(voltRef/1024);
   delay(10);
   volt7 = analogRead(A7)*(voltRef/1024);

   float volt8 = analogRead(A8)*(voltRef/1024);
   delay(10);
   volt8 = analogRead(A8)*(voltRef/1024);

   float volt9 = analogRead(A9)*(4.95/1024);
   delay(10);
   volt9 = analogRead(A9)*(4.95/1024);

   //*****************************************************************************
   Serial.print("B0= ");
   Serial.println(volt0);

   Serial.print("B1= ");
   Serial.println(volt1);

   Serial.print("B2= ");
   Serial.println(volt2);

   Serial.print("B3= ");
   Serial.println(volt3);

   Serial.print("B4= ");
   Serial.println(volt4);

   Serial.print("B5= ");
   Serial.println(volt5);

   Serial.print("B6= ");
   Serial.println(volt6);

   Serial.print("B7= ");
   Serial.println(volt7);

   Serial.print("B8= ");
   Serial.println(volt8);

   Serial.print("B9= ");
   Serial.println(volt9);

   Serial.println("");
   Serial.println("==========================");
   delay(500);
}

What is the purpose of the resistor and the MOSFET? Why do you need it? When you turn on the MOSFET, more than 500mA will flow through the resistor to the ground, of course your battery voltage will drop!

@hcheung: For estimating battery capacity, the voltage under load is often more relevant that the voltage of the unloaded battery.

I will make a battery capacity tester for that reason discharge the battery current  using the resistor and measure the capacity

Yes i agree with you but if i measure the voltage using multimeter and arduino analog pin at the same time in underload why the value is different so much. Example : Arduino read= 3.07v and Multimeter read=3.48V at the same time.

Where did you connect the negative probe of the multimeter? To the negative terminal of the battery or to the Arduino ground?

Wow! all the time I used the negative probe of the multimeter with the negative terminal of the battery but now I tested with Arduino ground and it gives me accurate value my question is the battery negative terminal is shorted with Arduino GND but why this different result coming out?

The main problem was the battery holder default wire, those wires were have high resistance. After changing those wire the problem was solved. Thank you everyone

Electric wires have resistance. Most of the time this resistance can be ignored, but this is not always the case. Specifically, if the wire is carrying a large amount of current, the voltage drop across it can be significant.
Consider this circuit:

simulate this circuit – Schematic created using CircuitLab
The red wires carry a high current, and experience a significant voltage drop. Wires in black carry almost no current, and are equi-potential. Both voltmeters on the left will measure the same voltage, which is affected by the voltage drops along AB and along DE. The voltmeter on the right measures a lower voltage, because it is also affected by the drops along BC and EF.
In your experiment the problem is compounded by the fact that the ground wire is carrying the current from all the batteries. It is therefore responsible of most of the voltage drop you experience.
The takeaway is that you have to make sure the junction points between the current carrying wires and the measurement wires (points B and E for the voltmeters on the left) are as close as possible to the battery. Otherwise your measurement will be biased.

Love you man!! I am working on this project for 5-6days to find out the problem, I thought I have a problem with the code so I tried to simplify my code to find out where the exact problem coming from but yet don't get any solution. But You actually teach me something that I never knew. Thank you so much, brother. Rally appreciated.

I solve the problem But now  the problem is when I High digital output pin of the arduino to turn on MOSFET-GatePin, Arduino Digital pin voltage drop from 5v to 3v across the gatePin. These thing happening with 7MOSFET and others 3 working perfectly. I changed mosfet and pulldown resistor but no solution.


text:
How to transmit string data using the rc-switch library?
I am using the rc-switch library for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.
send_string("Hello World!");
---------------------------

void send_string(const char *str)
{
int i = 0;

for (char *p = str; *p; p++ ) {
mySwitch.send((i<<8) + *p, 16);
i++;
}
mySwitch.send((i<<8) + 255, 16);
}

And I am receiving is using this Serial.print((char)mySwitch.getReceivedValue()); build in method. But I am getting this message.
H
H
H
e
e
e
l
l
l
l
l
l
o
o
o

W
W
W
o
o
o
l
l
l
d
d
d
!
!
!

Now how can I get my original message?

stop sending characters multiple times

I need to send string. How can I do this?

check your code and remove the duplicate transmit code .... the problem may also be on the receiving end ... you may be printing each received character three times

I need something like this https://stackoverflow.com/a/44749986/5280371

The communication protocol used by this library is unreliable. Thus,
each code word is sent multiple times, 10 times by
default. One solution around this problem is to send
a “byte number” along with each byte you transmit. You would then
transmit 16-bit words, where the MSB (most significant byte) is the byte
number, and the LSB is the actual byte you want to transmit. Something
like this:
int i = 0;
for (char *p = str; *p; p++) {
    mySwitch.send((i<<8) + *p, 16);
    i++;
}

Oh, wait! That's exactly what you are already doing! So it appears that
you are already aware of this issue and you have even implemented a
solution. How come you are asking this question then?
OK, I'll assume in the following that you just forgot to tells us that
the code snippet above is not from you, and that you didn't even
understand what it is doing. And you also forgot to provide a link to
the source of that code. Please, next time read How do I ask a good
question? before asking, and provide all the relevant
information right in the question.
So now the problem is in the reading side. You have to use those byte
numbers to remove the duplicates. One (untested) solution could look
like this:
// Return a received byte, or -1 if none is available.
int receivedValue()
{
    if (!mySwitch.available())  // no byte available
        return -1;
    static uint8_t last_byte_number = 0xff;
    uint16_t code = mySwitch.getReceivedValue();
    uint8_t this_byte_number = code >> 8;
    if (last_byte_number == this_byte_number)  // this is a duplicate
        return -1;
    last_byte_number = this_byte_number;
    return code & 0xff;  // LSB is the byte to return
}

And you could use it to print the data on the serial monitor like this:
int c = receivedValue();
if (c != -1)  // if we really got a new byte
    Serial.write(c);

Many thanks. It's working but when I using Serial.print((char)c); it's not working properly. And how I convert it to String would you help, please?

@ChayanMistry: Don't use String objects. You can get a C string in the same manner as when reading from a serial port.