text:
Splitting a float into bytes for storage in FRAM (like EEPROM)
I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.
This for writing:
float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

This is for reading:
long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;

I solved it with the use of UNION:
//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------

You are using an array in the S_float union but not for the variables f0.  you could use a loop for the fram writes.

A pointer can be used to easily decompose and reconstitute any multi byte type, like a float.


text:
Why is my Serial port not printing the right output?
am working with and Arduino nano and according to this, I can append strings to numbers by doing: stringThree =  stringOne + 123; but
when I do:
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;
Serial.print(x1);

I get this unwanted output!

=gëÙrïË:_³ß»þ™¹Æ3+Ç#ÿ¼¿.Õ[Oû/g¯>ïÿ1þ†lú0

but doing this it works fine.
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;
Serial.print(x1);

"Volt":646

why?

String concatenation uses dynamic allocation, which can be problematic on small-memory devices.  Anyhow, concatentation isn't needed for output -- see eg my answer to questions/33319 for Streaming alternative, and my answer to questions/16122 for another example.

I typically use Serial.println("Volt: " + (String)sensorValue);

In the first example you are adding an integer to the address of a string literal and then converting it to a String.
In the second example you are converting a string literal to a String and then appending an integer.
The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String you end up with garbage.

Pretty nice explanation... it must be maybe some kind of pointer operation behind the scenes...

That is precisely what it is. In C there is no such thing as a "string", only a pointer to some memory location. It's only when you use that pointer that the contents are interpreted as a "string".

source: Stack Exchange

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

sort: votes


text:
"undefined reference to" - C++
Hi fellow programmers,
I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:
SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
collect2: error: ld returned 1 exit status

The code is divided in two files, a *.h and a *.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: *.h: codepad.org/UyLfik6W *.cpp: codepad.org/5KJmraCC). But I will explain the context:
SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.
I hope, I provided all the informations to help you solve this issue.
Thank you for the attention.
PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.

Sorry Bruno but we need to see the code to know whats going on.  Can you post the code around line 141 (130 - 150) if nothing else?  I think it is very stange that it is looking for SensorDeVazao::SensorHandle within the class (unless that is a quirk of the compiler).

I've posted below at @frarugi's comment.

@BrunoHenriquePeixoto Usually it is better to add them directly to the question (just edit the post and put at the bottom the two links) so people coming here will know that they are here

Thank you for the advice. I was not sure about the privilege to add links to the question.

Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
void myfunc() {
    A::i = 0;
}

If you actually declare it the error should go away:
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
int A::i = 0;

void myfunc() {
    A::i = 0;
}

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).
This only applies to static variables.
EDIT: Further explanation.
You should understand the difference between declaration and definition of a variable.
Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement extern int i; defines a variable. All the variables listed in a class are only defined there.
Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.
Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying #include "lib.h"). When writing a library without a class you usually write global variables in this way:
// header file: lib.h
extern int i;

// source file: lib.cpp
int i;

(note: it is better to always define an initialization value, so for instance int i = 0;). The two files (A and B) both have the line extern int i; in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote int i; in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.
Now, for the classes. If you write
class A {
public:
    int a;
    static int b;
}

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).
To deal with this, you have to manually declare it in a cpp file, with the syntax int A::b;. This way you are reserving some space for that variable

Oh, damn, I've been discovered. Haha. Sure, I'll post it, but I'm a little bit skeptical in regard to this definition in *.cpp thing.
*.h:
http://codepad.org/UyLfik6W
*.cpp:
http://codepad.org/5KJmraCC

The header file looks fine at a first glance, so I'm pretty confident that adding SensorDeVazao* SensorDeVazao::SensorHandle = NULL; (or whatever value you should initialize it) before the functions in your SensorDeVazao.cpp file will solve your problem

It worked like a charm. Thank you, Sir! :D But now an explanation is required.

@BrunoHenriquePeixoto I added a small explanation. Keep in mind that I'm not an expert, though, so these info come from what they explained me when I faced the same problem ;) anyway if the answer successfully answers your question, please mark it as accepted so other people looking for this can find a quick answer

@BrunoHenriquePeixoto - I can't see codepad (bloody firewall :() but Majenko's answer's are normally right so I'd go with what he says.

Where do I accept it?

There should be a tick sign or something similar under the votes (on the left of the answer). You can click it to mark it as accepted

Much appreciated. You've excelled in the explanation. :D

@BrunoHenriquePeixoto Well, it was a pleasure to see someone asking for further explanation. Sometimes people come here to just solve their problems, but, IMHO, this is a wrong approach. Understanding why it was wrong is a more correct approach, and, according to your comments, you are the kind of person who wants to understand.. so, my compliments, good attitude :)

Where is my cookie? I demand my cookie! ;P I think asking for how things work is a better way to continuosly learn something new and trick the time about aging. :)

An explanation of what is happening:
When you define a class you indicate what variables will be in it.
When you then instantiate the class (MyClass c;) the variables within the newly instantiated object get allocated.
Static variables never get instantiated. After all - which instance of the class should instantiate them when you create one? And if you never create one? So it's simple: static variables never get created by the class definition or anything else. It is up to you to provide the storage space for that variable, which means statically allocating it in your C++ code as has been demonstrated.

Thank you once more for the clear explanation. This code will work with sensors in the University of São Paulo in Brazil. The students and I are very much appreciated. :)

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


text:
Splitting DOUBLE in byte for save on EEPROM
I'm trying to save in memory (FRAM in this case) DOUBLE value, i try the same method with use of UNION for save FLOAT value, but don't go over the 2nd number after dot, why? Where I'm wrong? thank's for help .
 //---------------------------------------------------------

  union Scomp_double  // si utilizza union x double
  {
    double temp;
    char byte_s[8];
  } S_double;

  //---------------------------------------------------------

double mioDouble = 1234567.12345678;

//-------------------------DOUBLE--------------------------------

  Serial.println("DOUBLE");
  byte d0 = 0;  // contengono i byte del float
  byte d1 = 0;
  byte d2 = 0;
  byte d3 = 0;
  byte d4 = 0;
  byte d5 = 0;
  byte d6 = 0;
  byte d7 = 0;

  S_double.temp = mioDouble;
  d0 = S_double.byte_s[0];
  d1 = S_double.byte_s[1];
  d2 = S_double.byte_s[2];
  d3 = S_double.byte_s[3];
  d4 = S_double.byte_s[4];
  d5 = S_double.byte_s[5];
  d6 = S_double.byte_s[6];
  d7 = S_double.byte_s[7];

  Serial.println(d0);
  Serial.println(d1);
  Serial.println(d2);
  Serial.println(d3);
  Serial.println(d4);
  Serial.println(d5);
  Serial.println(d6);
  Serial.println(d7);

  fram.writeEnable(true);
  fram.write8(11, d0);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(12, d1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(13, d2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(14, d3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(15, d4);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(16, d5);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(17, d6);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(18, d7);
  fram.writeEnable(false);

  S_double.byte_s[0] = fram.read8(11); // si ricompone il double
  S_double.byte_s[1] = fram.read8(12);
  S_double.byte_s[2] = fram.read8(13);
  S_double.byte_s[3] = fram.read8(14);
  S_double.byte_s[4] = fram.read8(15);
  S_double.byte_s[5] = fram.read8(16);
  S_double.byte_s[6] = fram.read8(17);
  S_double.byte_s[7] = fram.read8(18);

  double masterDouble = S_double.temp;
  Serial.println(masterDouble);
  //-------------------------DOUBLE-------------------------------

expected result 1234567.12345678 , result taken 1234567,12

double on Arduino is 4 bytes. The same as a float.

no way for have 4 digit after dot ,nice :) tnks for reply

Why not simple use "fram.write(&aFloatVar, sizeof(aFloatVar));"??

and what for read? tnks

how suggest in the comments, and on Arduino reference DOUBLE website
only on arduino 2 float it's 8 byte.

If you mean on the Due, yes, but readers who don't speak Italian will not automatically map the actual name of the product "Arduino Due" to "Arduino 2" and understand that you are talking about an ARM-based board rather than a traditional AVR-based one where float and double are 4-byte types.

The problem here is the serial output, which by default only outputs 2 decimal places. Solution: Serial.println(masterDouble,8);

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


text:
Arduino Ground Current and DC power jack
I have a project where I'm providing power via the DC jack to my Arduino then accessing the DC power via the VIN pin. According to this http://forum.arduino.cc/index.php?topic=453955.0 I am ok to draw up to 1A from the VIN pin. I have measured 400ma out of VIN, so ok on that front.
But according to this http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations I can draw max 400ma, So I'm a bit confused, which is the correct amount of power VIN can supply if the Arduino is being powered via the DC jack?
If I take the first thread as correct and assume it's ok to draw up to 1A from the VIN pin (from the DC power jack), is it ok to ground that current on the Arduino GND pin ? if VIN can supply up to 1A then I assume that it's ok to ground up to 1A, is this correct?
All help appreciated

Going by the schematic here there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).
The datasheet here indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).
Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.
If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.


text:
How do I find my 1N 4007 diodes?
I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.

Maybe show us some pictures of what you do have...

What is Google?

While the ArduinoStarterKit page at arduino.cc lists “5 Diodes [1N4007]” as part of it, and has a picture where 5 diodes apparently appear slightly left of center in the top row, several other pictures that come up in a google images search for official Arduino Starter Kit apparently don't show the diodes.  Eg, as at arduino starter kit.  But 4 Best Starter Kits for Arduino Beginners does show them.
Note, unless you are working with medium to high AC voltages (eg above 50 V) you can substitute 1N4001 - 1N4004 which have lower PIV ratings but also slightly lower forward voltage drop.  For many beginning projects, 1N4148 signal diodes will be adequate and perhaps less expensive.

1N4007 are usually black with a white stipe indicating the cathode. Use a magnifying glass and you should be able to see the marking.

They are stuck next to a string of resistors.

This is image of 1N4007 diodes. I think now you can find them easily.


text:
Playing WAV file from Arduino Uno using Ethernet R3 Shield
I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is this link, but this is for the Due and I can't figure out how to adapt for the Uno.
The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.

Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that.
In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How%20to%20make%20sound%20with%20a%20PIC%20chip.htm
and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.

Thank you ShunShirou. I'll try out your advice and repost to let you know how it goe


text:
Anything wrong with this code?
Sorry for any grammar mistakes. It's my second language.
I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4.
I connected piezo to power and ground.
When you pressed a button1 then you should hear 'c' tone,
but when I pressed the second button nothing happend and I don't understand why?
Here is my code below:
const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin =  6;

int buttonState1 = 0;
int buttonState2 = 0;

void setup() {

  pinMode(piezopin, OUTPUT);
  pinMode(buttonPin2,INPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == HIGH) {
    tone(6,261.63,500);

  } else {

  }
  if (buttonState2 == HIGH) {
    tone(6,392.00,500);
  } else {

  }

What happens when you press the first button?  I assume you have a final closing brace not shown in your code above. Perhaps try writing messages to the console in each of the button pressed cases to see if it is reading the inputs correctly.

There is a free schematic tool when posting. Use it please.

You should add a debounce in the code for the buttons. And this is a state change code. You should try going to the Arduino website for an example code as a reference. I'm a bit rusty, but I dont think the if/else statements are right. But this is relatively straight forward basic code, lots of help around the web if you look for it.

@Rayray Nothing technically wrong with the if/else statements but the else clauses are empty so they could be removed.

What is your wiring? Do you have any pull-down resistors?

I connected piezo to power and ground -- Not to pin 6 and ground...?

Try calling noTone() after the tone is played. This is a kind of "reset" for the pin.
Also, you forgot a } at the end of your code.
If these didn't solve your code, then it most probably is an electric problem.

I know what was my problem. i was thinking my buttons are upright but they are not.my program is working now.thank you for your help.:-)


text:
FastLed (WS2812B) and IRRemote problem
I am trying to control my WS2812B with a remote control. To archive this, I am using IRRemote library. The problem is that this two libraries doesn't work together.
I did some research and found out that it is a problem with timers.But, inside the IRRemote library file (boarddefs.h) there is a possibility to choose different timer (It uses TIMER2 as default, so I supposed that FastLed uses also Timer2).
So when I change the timer in boarddefs.h file to TIMER1, it is also now working fine for me. I keep recieving random IR codes. When I stop using FastLed library, I recive correct codes.
Some workaround to this problem is to read IR signal only once irrecv is idle:
  while (!irrecv.isIdle());  // if not idle, wait till complete
  if (irrecv.decode(&results)) {
     ...
  }

It makes around 80% of readings correct.
I am using arduino NANO clone. My question is, if there is any way to use IRRemote and FastLed libraries together other than using two arduino NANO (use one to read IR and other to control LEDs)?

update in 2021, similar problem, fastLED causing unintelligible IR codes,
adding that while loop:
while (!irrecv.isIdle());  // if not idle, wait till complete

just before the ir check
worked for me, not 100% of the codes are correct but more than good enough for my use,
you life saver

The WS2812B chips are highly timing-dependent. You have to clock out bits within a range of ±150 ns. This isn't likely to work well with clocking in bits from an IR remote. You are finding errors on the IR codes - that doesn't surprise me.
I suggest you use your idea of two Nanos. One can be reading IR codes. The other can display a stream of pixels and then "ask" the other one (eg. via serial or I2C) if a different command has arrived. That way the timing can be shifted in such a way that both processors are not interrupted when they are busy.

But as I read, Arduino NANO can use two or even three timers. I do not fully understand timer topic, but what I understand is, than I could use timer1 for LED and timer2 for IRRemote - but it does not work...

Yes, but just having timers doesn't necessarily solve your problem. You are clocking out bits to the WS2812B every 350 ns or so. That doesn't give you spare time to read incoming IR bits, timer or not.

I want to add my two cents at the solution posted bt @BenAshmore, that allow to mediate between fast updates and receiving sensible data:
void loop() {

 if(IrReceiver.decode()){
    if( IrReceiver.decodedIRData.protocol == UNKNOWN ){
        wantData=true;
    }else{
        wantData=false;
        Serial.println(IrReceiver.decodedIRData.decodedRawData, HEX);
    }
    IrReceiver.resume(); // Enable receiving of the next value
  }

  if(!wantData || IrReceiver.isIdle() ){
    FastLED.show();

  }

basically if I receive messy IR data I know there is something incoming and just in that case I interrupt the FastLed updating until I read something good.


text:
How to analyse audio and to affect source?
I want to use the audio from my PC and have it going to the speakers and Arduino for some lighting effects. This project is a bit of a struggle because I don't know what the best way of analysing audio is. So for the lights I only want bass frequencies to affect the lights.

You need an FFT for that - and an integer based one, too. And an Arduino that can store enough audio samples to make it meaningful. And ideally a faster system to process it quicker. Basically, while an Arduino could do it, it would struggle and not be wonderful. Better to use an ARM or PIC32 based board with more memory and a fast 32-bit CPU. An FPU as well would help, then you could do it with floats instead of ints (though ints are fine). Even better would be a chip with a DSP in it (such as a dsPIC33), but then you're straying way outside the bounds of Arduino...

While i dont really understand what you mean with the arduino not being able to store enough sample i could try and use my raspberry pi (i think i remember it being something with ARM).

I usually use at least 1024 samples (though you can use less, but you get less FFT buckets). At 16 bits per sample (actually 10, but you there aren't 10 bit data types) that's the entire memory of the Uno. For simple LED control you could get away with maybe 128 samples and sample at a lower frequency, since you aren't interested in the higher frequency range, and it then becomes viable. The fewer samples you have the less frequency resolution you get, but the less memory it uses and the faster it processes.

I have actually just finished a project doing exactly that. I used a frequency analyser chip called an MSGEQ7 (Available from Sparksfun), here's the datasheet.
https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf
These little things are really easy to use. Give me a shout if you would like any help with it such as coding or wiring.

Thanks alot i am currently  loooking into it to see if its what i need :-)

There's many ways of achieving what you want - some in software, some in hardware.
Since you are only interested in the lower frequencies this opens up the possibility of a low pass filter - either a hardware one, or a software one.  The simplest hardware one is just a resistor in series followed by a capacitor in parallel:

simulate this circuit – Schematic created using CircuitLab
(representative component values: increase capacitance and/or resistance to decrease frequency)
Doing it in software is just as simple: you sample at a regular frequency through whatever means are suitable (there's plenty of resources for sampling at a specific frequency on the Arduino - google them), then you average samples together to remove higher frequency components. The more you average the lower your cut-off frequency. Each time you average you halve the frequency range. Note that the frequency range is already half the sample frequency.
For instance: if you sample at 8kHz (say 512 samples) you get a 0-4kHz frequency range in your sample set. Averaging each pair of samples (which results in 256 samples) gives you a 0-2kHz frequency range. Averaging again, for 128 samples, gives you 0-1kHz. Average again, for 64 samples, gives you 0-500Hz. Again, 32 samples, 0-250Hz.  Keep going, until you have your desired cut-off frequency.
Then you can scan the sample set for the maximum and minimum and take that as your peak amplitude for the sample set.
You have to make sure that your sample frequency is at least twice the highest frequency you are interested in (preferably more so that you can do some averaging), and that your sample set is large enough, at the chosen sample frequency, to contain at least one full cycle of the lowest frequency you are interested in.  For instance, at 8kHz sample frequency, if you are interested in responding to frequencies down to 50Hz, you need to sample for at least (1/50) 20ms, which at 8kHz means (8000 samples per second times 0.02 seconds) 160 samples. Since it's usually better to work with powers of 2 that means 256 samples is the next biggest "slot" that would do.
If you want to access more information about the actual frequency content of your sample set so as to light different LEDs when different frequency components are in the signal you need a Fast Fourier Transform (FFT). This converts the sample set into a collection of buckets (exactly half the buckets as you have samples) each representing a portion of the frequency range of your sample set. For 256 samples that gives you 128 buckets, each representing 1/128 of your total frequency range. So at 8000 samples per second, or a 4kHz frequency range, each bucket gives you a 31.25Hz resolution.
The problem with FFT is it is computationally expensive. It also needs more memory than simple averaging.
Depending on the algorithm you use, you will probably find you need 16 bit samples, and each sample should be in the form of a "real" and "imaginary" component, amounting to 32 bits per sample. Most algorithms require powers-of-two for the number of samples. For 256 samples that means you are using 1024kB of memory just for sample storage and processing, which is half of what the Uno has. You certainly won't be able to go over 256 samples on an Uno (the next step up is 512, which would want to use the entire memory leaving no room for any other variables).
There are two basic forms of algorithms for FFT: floating point, and integer. The floating point variant is great on a CPU that has an FPU with it to do the number crunching, but on an Arduino that just isn't possible. So the floating point version would take a massive amount of time to process making your results incredibly jittery. Far from desirable. So you need to find the integer version (one example) which runs much faster.
Calculating an FFT is done in two parts: first it calculates the real and imaginary components from the sample set, and second it converts those two components into a single vector, the length of which is the amplitude of the bucket. Whether or not you are using the integer FFT algorithm that second phase is going to be slow. It involves a square root (it's basically pythagoras: sqrt((r*r) + (i*i));) and that is almost always slow. Getting that to work fast on an Arduino is not at all easy. You can sacrifice accuracy for speed though and write your own square root approximation routine (as I have done before for 3D vector manipulation in a graphics library):
float quick_sqrt(float number) {
    int32_t i;
    float x2, y2;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y2  = number;
    i  = * ( long * ) &y2;
    i  = 0x5f3759df - ( i >> 1 );
    y2  = * ( float * ) &i;
    y2  = y2 * ( threehalfs - ( x2 * y2 * y2 ) );

    return 1.0/y2;
}

That uses a few tricks to do with the way a floating point number is stored to create an approximation of the square root.
With all that you can see that the Arduino can do FFT, but it's not the best solution for FFT. Ideally you need a faster, more powerful, chip with more memory (personally I use a PIC32MZ "EF" variant: 200MHz, 512kB RAM, FPU).


text:
Setting a pointer to NULL in Arduino library - error: ‘NULL’ was not declared in this scope
I am writing my own library for using with my Arduino. In my code, if I set a pointer I have declared to NULL, such as
int *ptr=NULL;

I get the error
error: ‘NULL’ was not declared in this scope

I need to initialize it to NULL as I am using pointers to implement a list.
If I use NULL directly in the program in the IDE, I do not get this error. This seems to be happening only when it is a part of the library code.
How do I correct this? Is there any alternative keyword to use? Or do I have to include some library?
Thank you.

Works fine for me. No need to include anything. It is, actually, part of stddef.h, but that gets included by default anyway, and is used by many other headers, like stdio.h.

@Majenko Thank you. I checked, it works when I use directly. I forgot to mention that this error appears when I use NULL in a definition of a header file which I have written. I hadn't realized that it works otherwise. Edited by question.

I am writing my own library for using with my Arduino.

You should really include Arduino.h, i.e.
#include <Arduino.h>

Not only will that define NULL for you, but you also get the other standard Arduino functions like digitalRead, pin number declarations, and various useful macros.

Thank you. Is there any reason to prefer it over including individual libraries?

Including Arduino.h gives you all the stuff you should need (including the standard libraries). If you ever need something like a port or pin address, or any of the Arduino functions (like analogRead) you are going to have to include Arduino.h anyway.

You should make sure your header includes the stddef.h header, which holds all these standard definitions (hence its name):
#include <stddef.h>


text:
Start/Stop/Reset the melody using buttons
I have 2 buttons.  Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".
How am I going to use the buttons to start/stop/reset the melody?
Here's the code:
#include "pitches.h"

int melody[] = {
    NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
    NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
    NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
    NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
};

int noteDurations[] = {
    8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
};

boolean needtoPlay;

void setup() {
    pinMode(4, OUTPUT);
    pinMode(2, INPUT); //START/STOP
    pinMode(3, INPUT); //PAUSE
}

void loop() {
    for (int thisNote = 0; thisNote < 26; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(4, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.60;
        delay(pauseBetweenNotes);
        noTone(4);

        if (needToPlay == true) {
        }
    }
}

Step one is to make it work without using delay().

this one? delay(pauseBetweenNotes);

That's the only delay there is, yes...

Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.

Easiest way would be to add this to the end of the for loop (inside the loop).  Assuming buttons are pulled up.
//setting pause with pause button
if (digitalRead(pauseButtom) == LOW) {
    //it will not play while in this loop
    while (true) {
      //if the button is pressed again, exit the loop
      if (digitalRead(pauseButtom) == LOW) {
        break;
      }
      delay(10);
    }
}

For the reset, just break;  it will exit the for loop and start again.
Alternately, instead of using a for loop, use a counter and increment / reset it.  You will need to store most variables globally.
if(!paused) {
  //play note
  if (counter < numNotes) {
    counter++;
  } else {
    counter = 0;
  }
}

if (digitalRead(pauseButtom) == LOW) {
  pause = !pause;
}

if (digitalRead(resetButtom) == LOW) {
  counter = 0;
}

You could move those last 2 conditionals to interrupts.


text:
Fastest communication between Arduino and PC
I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.
It is working but I'd like to obtain more speed without any errors.
Can you suggest me the best way to do it? Even changing communication.
Thank you

Which USB serial are you using? The ATMega port or the native USB port?

And what baud rate, and what encoding?  How fast does it currently go, and how much faster do you want (well, need) to achieve?

I am using the programming port.

115200 Baudrate, I would like to obtain the best performances for a semi-real time application. I am currently using Serial.println(value1, value2, value3, ...,value8)\n.  In PC parsing of the datas I sometimes get errors because it sends two different row in the same. Thank you

So, again, how fast does it currently go, and how fast do you need it to go?  At 115kbps, you could in principle, suitably encoded, send 40k 16bit values in about 5.5 seconds.  How long is it taking in your implementation, and how long do you want it to take? Everyone wants the best performance (and the least effort and the lowest cost and the highest reliability). Give us a clue.

Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).
void setup() {
    SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
}

void loop() {
    SerialUSB.println(millis());
    delay(100);
}

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.

seems legit.  How to do it?

SerialUSB.begin(115200); SerialUSB.println("Whatever"). And plug into the other socket of course.

Why the delay? Is to avoid errors or just to simulate stuff?

That is just a simple example so you can see the port working. The delay has no purpose other than to allow your eyes to register what they are seeing before it is gone.

SPI: technically no upper limit so long as both parties can keep up and the wires are good enough. Mbps easily doable.

I am already using SPI for communication between Arduino and an ADC shield. Can I use it anyway and how?

spi targeting is controlled by the _CS pin(s). Multiple spi devices can hang off the same bus - assuming your shield is properly designed.


text:
I need a simple, low power, low cost wireless switch to transmit to Arduino
I'm looking for a very simple wireless, low-power, low-cost switch that can transmit a signal to an Arduino. Ideally, each transmitter would have a signature. For instance, let's say I had 4 different transmitters that are attached to a sensor. When the sensor is tripped, I want to wirelessly send a signal to the Arduino. I've looked at these 433 MHz modules, but it seems like they would also need a microcontroller to send the data, while that's a possible solution, I'm wondering if there is a even smaller, simpler solution.

... ESP8266 ... ?

modify a wireless garagedoor remote.

There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).
There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.

You could use an infrared led and an infrared sensor combined with a simple circuit to send a series of flashes that only your arduino can read. The only downside to this is that infrared can only be used indoors and they don't work if you don't have a direct line of sight.


text:
Checking for multiple values in IF separated by commata
My code is:
if ((minute == 31) && (hour == 4, 6, 9, 11))
{
  digitalWrite(8, HIGH);
}

I want to turn on the LEDs when it is exactly

04:31,
06:31,
09:31,
11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

Yes, the list of values 4, 6, 9, 11 does not mean what you think it does.
if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}

Optionally, you could store the values in an array and go across all of them with some code like this:
int hours = [4,6,9,11];

function isInArray(inputValue, array) {
    boolean isIn = false;

    for ( int i = 0; I < array.length; i++) {
        // "isIn |= statement" is shorthand for "isIn = (isIn || statement)"
        isIn |= (array[I] == inputValue);
    }

    return isIn;
}

if (isInArray(variable, hours)) {
    //do whatever
}

//might be able to do
if (isInArray(variable, [4,6,9,11])) {
    //do whatever
}

Some language may allow you to write that, but not C++, which is the standard language for Arduino.


text:
ESP8266 & Initial State
Has anyone been successful in connecting an ESP8266 to the Initial State IoT platform?
On the platform there is only one example with Cactus ESP. I tried it but it did not work because I have a NodeMCU.
Can you please share your Arduino code?

If you use the Arduino IDE Board Manager to install the support for ESP boards
an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.
This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.
The problem with the HubTest.ino code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor.  You don't have that so all the AT commands are not going to work.
However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example.  You need to look at how that code forms a connection and make HubTest.ino work in that way.  I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.


text:
Arduino Uno: Sensor shield powering multiple servos
I posted this on the electrical side of stack exchange and they said it was off topic, so I think it will be on topic here and they confused me even more. So if you guys could clear up my confusion, that would help.I know there are sources for this, but I am still lost.  Anyways, here is the run down. I want to control multiple servos (12 of them) using a sensor shield. I need to know what kind of power supply I need. Here is the servo's I am using:
https://www.amazon.com/gp/product/B01NA80LUR/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
Here is the sensor shield I am using:
https://www.amazon.com/gp/product/B01ACKVPTW/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
The servos run at 3-7.2V and 750ma-1000ma full load or another person said they ran only 100-150ma. Also, another question is do I plug that power supply, when I get the right one according to what you say, into the dc jack or the external power on the sensor shield board?
Thank you for your time.

Arduino.cc forum topic 229646,  “Arduino Sensor Shield v5 (APC220) manual”, is a thread about lack of documentation for that shield.  However, post #10 in that thread states that pulling off the SEL jumper allows you to use an external power supply to power the devices you attach to the shield.  Also see Sensor Shield (Version 5X) Separate 5V for Servos at yourduino.com.
The Robotics Stackexchange question Wiring & driving TowerPro SG90 servos agrees with the 750–1000 mA current draw of SG90 servos.  You could go with a 5 or 6 V power supply, with say 12 A rating if you expect to drive 12 servos at the same time.  However, as a 12 A supply might be expensive, you probably should attach two or three servos to the shield and measure the current draw.   If, for example, your application rarely draws over half an amp per servo, you might scale back to a 10 A or 8 A supply.
Note that an Arduino Uno or Nano (in general, any based on ATmega328-like MCUs) has six pins that support hardware PWM, so you may need to use a Mega instead, or two Uno or Nano  Arduinos.  (Software-generated PWM signals are another possibility but I doubt it would work well enough if your app is at all complicated.)

Edit 1:  If the system is battery operated, you probably should use a 2S LiPo RC battery, that is, a battery with the voltage of two lithium polymer cells in series (so, 7.4 volts) and whatever number of cells you wish to pay for in parallel, as often used in radio controlled devices.
Some LiPo batteries support 25C discharge rates, ie, can discharge at 25 times their one-hour-discharge rating.  Thus, a 500 mAh battery might work fine – since 25 times .5 A is 12.5 A – if you only need to run your system for up to 2.4 minutes between battery charges.  Or, for example, a $13.49 Turnigy 1000mAh 2S 20C Lipo Pack HobbyKing RC Battery would work ok, even though only rated for 20C.  It could power a 12 A draw for 1/12 hour, or 5 minutes.

For the SEL jumper, look in the lower left corner of one of the pictures from your amazon.com link, as below.  With the jumper (the short-metal-strap-and-black-plastic-shell assembly, next to the letters SEL) removed, connect battery+ and battery- to the screw-down terminals at bottom left in the photo.  Battery+ goes to Vcc, battery- to Gnd.

Regarding a second Arduino, you could split the processing across two of them so that each one only needs to know the current time; or could communicate between them by an SPI, I2C, or RS232 interface; or could move up to a Mega2560 Arduino, which has a lot more PWM channels.
Edit 2:  If battery weight is an issue, you may be able to use lower-capacity (hence lighter-weight) batteries if your software only moves a few of the servos at the same time.  For example, if you move three or four at a time, and if most of the servos are idle most of the time, you might be able to use a light-weight cellphone battery.
Addicore.com has some useful current measurements for the SG90:
Voltage                        4.0V to 7.2V, 4.6V - 5.2V nominal
Running current with 5V supply (no mechanical load)    220 ±50mA
Stall current with 5V supply (horn locked)             650 ±80mA
Idle current with 5V supply                              6 ±10mA
Weight                                                0.32oz (9g)

However, you probably need to make current measurements on your own to see how big the battery needs to be.

Ok, that is kinda what I thought as regards to the power supply. Problem is I can't find a battery with 6v and 12 amps that is not a car battery size...so if you guys can tell me what I can do about that would be appreciated. Secondly, my project is a spider robot, so I kinda need it to be one arduino unless the both communicate somehow? Third, I can't find a "SEL jumper" so could you explain that?

I did mention that I am building a spider robot with these servos that are kinda small, that battery is heavy as I personally do RC cars myself so I know they are too heavy for this project. There must be another way. How do people build a spider robot? Like seriously, this is  hard for getting a power supply that is correct and not to heavy. About the other things, I will change to the mega and for the sel, I have to pull the jumper or what am I suppose to do with that? I can see like a "pin" kinda that might be able to be pulled out? Again, thanks for all the help. I know I'm a noob at this.

@Sean.D, see edit 2 and slight change to Edit 1.  Note, please upvote answer or mark as accepted

I might be able to get it to only run 6 at a time, but have no idea until i build it. I really think it will use at least 6. I will do some measuring on my own and see. I will continue looking for a battery that is suitable. Thanks for your help.

I upvoted but says i need like 15 rep or something, I then hit the check mark and it turned green.

@Sean.D, thanks!  I forgot to mention there are some really small boards (not shields) available with chips on them that develop the PWM there, like  “PCA9685 16 Channel 12-bit PWM Servo Motor Driver I2C Module Robot WC For Arduino”  and  “16-Channel 12-bit PWM/Servo Drive shield module I2C PCA9685 For Arduino NEW D” on ebay.    These can be used ok AFAIK with Uno and Nano.  Nano is ~ 1/3 as big as Uno and draws a little less current

Thanks, I just need a battery that is no to heavy, but I will keep that in mind.

two things make servos fairly easy to control:

they take a slow pwm input; generating pwm is fairly easy on a mcu;
they are generally not that sensitive to the duration of the off state: I have tried from 5ms to 40ms (the longest) and they are fine with that.

so if you combine the two attributes together, it is easy to control multiple servos with from one timer interrupts.
I wrote a few pages on this recently:
1. driving multiple servos on AVR Timer2: https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/

driving multiple servos on PIC: using TIMER0 (https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-pic-timer0/) or TIMER1 (https://dannyelectronics.wordpress.com/2017/02/07/driving-multiple-servos-with-pic-timer1/).

The following is a combination of the two: driving 8 servos independently on PORTB with TIMER1 and another 8 servos independently on PORTD with TIMER2.

the user code is quite simple:
//set up servo controller 1
srvo1_init();                           //reset the servo module
srvo1_setpr(1, 1000);                   //for 1ms
srvo1_setpr(2, 1200);                   //for 1.2ms
srvo1_setpr(3, 1400);                   //for 1.4ms
srvo1_setpr(4, 1500);                   //for 1.5ms
srvo1_setpr(5, 1800);                   //for 1.8ms
srvo1_setpr(6, 2000);                   //for 2ms
srvo1_setpr(7, 2500);                   //for 2.5ms
srvo1_setpr(8, 4000);                   //for 4ms

//set up servo controller 2
srvo2_init();                           //reset the servo module
srvo2_setpr(1, 1000);                   //for 1ms
srvo2_setpr(2, 1100);                   //for 1.1ms
srvo2_setpr(3, 1200);                   //for 1.2ms
srvo2_setpr(4, 1300);                   //for 1.3ms
srvo2_setpr(5, 1400);                   //for 1.4ms
srvo2_setpr(6, 1500);                   //for 1.5ms
srvo2_setpr(7, 2000);                   //for 2ms
srvo2_setpr(8, 4000);                   //for 4ms

Once it is set-up, you can just leave it alone and no addition attention is required. You can change the duration of course, or disable / re-enable output on a given channel.
Total CPU drain is about 150K ticks in a second for 16 channel controller.
works on Arduino as well.
edit: if you port the code to TIMER0 (easily done),  you can control 32 servos independently.
and if you combine this code with making timers out of the output compare functionality, you can shrink them all on one timer.


text:
Powering Arduino through 12V USB communication unstable
When powering Arduino through Japan Jack at 12V USB communication becomes unstable and frequently interrupts/disconnects. Using Arduino Uno R3 and Linux on the connected computer.
Does anyone have any insight why this might be happening?

This is a guess but since 12V is at the upper edge of what the board can accept over its jack is your PSU stable?  If it isn't your regulator should heat up.  You could measure this by monitoring the output from the VIN pin (apparently its bidirectional).
This link might help https://www.open-electronics.org/the-power-of-arduino-this-unknown/

@Matt can you point me to where they say this? according to the arduino page 12V is the upper limit of the recommended voltages, but it can work up to 20V (in fact, the regulator has a maximum voltage of 20V, but there is also a diode). So... Why 12V is the maximum?

@frarugi87 the effective limit is not the maximum voltage the regulator can accept when supplying tiny currents, but rather the voltage at which the heat produced by the difference between accepting power to satisfy the actually needed current at a high voltage and emitting only a much smaller amount of power at a low voltage, is more than can be removed from the device while it remains at an appropriate temperature.  So the actual voltage limit depends on current draw and cooling situation.

@Matt ok, so 12V is not the limit of what the board can accept. According to this blog, the uno draws 46.5mA when no load is present. The datasheet says that with a 1cm*1cm copper pad, the 1117 has a thermal resistance of around 100°C/W, thus saying that 1.2W can be safely dissipated without triggering the thermal protection. At 46.5mA and 20V the 1117 dissipates only 0.7W, so it is perfectly safe to give 20V to a board without external loads. The 1117 can deliver up to 1A, thus leaving about 950mA of loads applicable... continue

So when you have 950mA of current absorption (from the 5V) 1.2W mean that you can have at most a 6.2V voltage on the input of the regulator (about 7V on the input pin, since there is a diode). I'm not saying that you can power everything, I'm saying that claiming that 12V is at the edge of the board voltages is wrong, since it only depends on how much current you are drawing (up to 30mA of current draw even 20V are fine)

Could it be possible that it is related to disconnected grounds.  I originally assumed that the 12V supply and the computer share a common ground via the same mains circuit.  Is that the case?  Also is there a reason you are supplying 12V?  What is the current draw of your connected items?

@frarugi87 - I got the 12V from the link in the comment and also https://www.arduino.cc/en/Main/ArduinoBoardUno.  Yes you can supply up to 20V, but the recommended is 12V.  I'd just assumed it was recommended for a reason. If the 1117 can dissipate the heat from an unloaded board with a 20V supply, how much load would the board need for it to generate 1.2+W with a 12V supply?  I think you are right its unlikely to be a heat issue and unless the PSU is seriously flaky then its unlikely to be an issue with unstable voltages.

12V is a little on the high end for what the arduino can handle by itself. If I were you I would use a DC step down Buck Converter module to hold the voltage at somewhere around 6v.
http://www.ebay.com/itm/like/400673913185?lpid=82&chn=ps
They're super cheap and pretty easy to use. Simply solder the + and - leads from your 12v power supply to the +in and -in on the buck converter. Then the + out and -out to the + and - for your arduino. Turn the potentiometer until you get somewhere around 6V.
Edit:
Actually I was just reading online, and some people have trouble communicating with the arduino through USB while an external power source is connected. Internet says this problem is related to sharing voltages.
https://forum.arduino.cc/index.php?topic=194598.0

I disagree. According to the arduino page 12V is the upper limit of the recommended voltages, but it can work up to 20V (in fact, the regulator has a maximum voltage of 20V, but there is also a diode). So 12V is perfectly fine. 6V, on the other hand, is undervoltage: dropout of the regulator is around 1V, the diode has a 0.6V dropout, so the minimum voltage should be around 6.6V...

The thoughts are not bad in the general sense, but unlikely to be related to the observed problem.  Setting the output to 6v however is erroneous advice - the Arduino's on-board regulator needs a higher input voltage that than, while 6v is too high to safely bypass the on-board regulator.


text:
Cycling LED's for specific time period with millis()
My goal in pseudo code is :
only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.
unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}

A way to make this work is to use only one previousTime variable, rather than three of them.
When the program as shown above starts out, millis() is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds.  At the 2 second mark, LED 7 comes on.  previousTime2 gets set to current time, so the second if is not going to be satisfied for 2 more seconds.  At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs.  Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.
With a single previousTime variable, code like the following might work.
current = (millis() - previousTime)/1000;
if (current < 6) {
  digitalWrite(6, HIGH); // turn on 6
} else {
  digitalWrite(6, LOW);  // turn off 6
}
if (current >= 6 && current < 8) {
  digitalWrite(7, HIGH); // turn on 7
} else {
  digitalWrite(7, LOW);  // turn off 7
}
if (current >= 8) {
  digitalWrite(8, HIGH); // turn on 8
} else {
  digitalWrite(8, LOW);  // turn off 8
}
if (current >= 12) {
  previousTime = millis();
}

Note, the following code has the same effect.
current = (millis() - previousTime)/1000;
digitalWrite(6, current < 6);                 // turn 6 on or off
digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
digitalWrite(8, current >= 8);                // turn 8 on or off
if (current >= 12) {
  previousTime = millis();
}


text:
Adding to the counter only ONCE while R2 =<200
I am very new to Arduino and I have this little bit of code:
if (R2 <= 200){
  counter=counter+1;
  Serial.print("counter: ");
  Serial.println(counter);
}

I want it to count every time R2 is less than or equal to 200, but I only want it to count once. Right now it adds to the counter 3-2 times while R2 is less than 200. I'd like it to only count once while in that range before R2 becomes greater than 200.
Any suggestions or links to helpful information would be very appreciated. Thank you!

Your question doesn't make sense. I want it to count every time R2 is less than or equal to 200, - OK "every time" you want to count. but I only want it to count once - so not every time?

Do you mean: I want to add one to a counter if R2 is <= 200, but only once. Then if R2 is > 200 then I want to reset this process and do it again.

You can set a flag to indicate that R2 is or has been above 200 since it last was low, much as follows.
// before loop() ...
byte Rhi = true;  // at outset, say that R2 has been high
...

// in loop() ...
  if (R2 > 200)          // Has R2 gone high?
    Rhi = true;
  if (Rhi && R2 <= 200){ // Has R2 gone low from high?
    Rhi = false;
    ++counter;
    Serial.print("counter: ");
    Serial.println(counter);
  }
  ...


text:
Help combining code
Can someone please help me fix my code?
Basically, a user inputs values that determine how many beeps will play from a breadboard-compatible speaker, and right after the beeps are played, a motor (connected to the breadboard)  is supposed to turn.
The beep-code is mine, and I got the motor code from the Arduino website. Anyway, SEPARATELY the codes work - the beeps play from the speaker, the motor turns fine. However, the codes don't work when I combine them (beeps play, but motor does not run after beeps are played), and I have no idea how to fix it. Any help is appreciated. Thanks so much.
int pin = 3;
#include <Stepper.h>

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

void loop() {
  int bpmeasure, measurespg, bpminute;
  Serial.println("Enter number of beats per measure:");
  while (Serial.available() == 0) {};
  bpmeasure = Serial.parseInt();
  Serial.println(bpmeasure);
  Serial.println("Enter number of measures on page:");
  while (Serial.available() == 0) {};
  measurespg = Serial.parseInt();
  Serial.println(measurespg);
  Serial.println("Enter tempo:");
  while (Serial.available() == 0) {};
  bpminute = Serial.parseInt();
  Serial.println(bpminute);
  float tppg = (bpmeasure * measurespg * 60000.0) / bpminute;
  // time it takes to play a page, in milliseconds
  float tpbeat = tppg / (bpmeasure * measurespg);
  // time between each individual note, in milliseconds
  float t = 0.0;
  for (float t = 0.0; t <= tppg ; t += tpbeat) {
    tone (pin, 30, 50);
    delay (tpbeat+50);
  }
  // speaker is supposed to beep every 'tpbeat' amount of milliseconds,
  // until it reaches 'tppg' milliseconds and then speaker should stop beeping
  const int stepsPerRevolution = 900;
  Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
  int stepCount = 0;
  // number of steps the motor has taken
  if (stepCount = 0) {
    // read the sensor value:
    int sensorReading = analogRead(A0);
    // map it to a range from 0 to 100:
    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
    // set the motor speed:
    if (motorSpeed > 0) {
      myStepper.setSpeed(motorSpeed);
      // step 1/100 of a revolution:
      myStepper.step(stepsPerRevolution / 100);
    }
  }
}

Not very clear what you want to do... Do you want the board to stay still until you write through serial, then play the beats, then when they finish run the motor? And until when should it rotate? Anyway try to implement it yourself, then see what is wrong and come back asking "I did this, I expected that but got this other thing. Why?"

Right now I'm not worrying about making the motor stop rotating, I just want it to do so after the beats are played

Yes, but if you do not stop the motor and return to the initial idle state you will have to reset or turn off/on the arduino to enter the wait state again.. but if you don't care, what did you try? because in my opinion just copy-pasting the two programs one after the other and joining the loops will do that..

I am aware I have to reset the arduino. I did just copy and paste the 2 programs into the same loop, and it didn't work. I don't know what I'm doing wrong ;-;

Ok, now that you joined them you are ready for the second step, which is "see what is wrong and come back asking "I did this, I expected that but got this other thing. Why?"". Which means, post the complete code, your expectations and your actual results...

Okay, post is edited

just for the future: it is usually better not to delete previous content, but rather add it at the bottom. Anyway you say that the motor does not start. But does it stop playing the tone?

You have to make the code non-blocking otherwise the motor control will not work.

what part is blocking? and how do i make it nonblocking?

and yes, it stops playing the tone

I don't see where the motor pin is used.  it is defined at the top but not referenced in the code.

The first step with combining any programs together is to forget about combining programs together. Instead you need to do something completely different.
Analyse the existing programs individually. Work out and learn exactly how they work and how they do what they do.
Then think about your program. What do you actually want it to do, and how does that relate to the things the other programs did.
Then, finally, using what you learned from analysing the other programs, you write your own new program that does what you want it to do.
Yes, there may be a certain amount of copy-and-paste from the old programs to the new, but until you have taken the time to learn how the old programs work you won't have a clue which parts of them you may want to copy-and-paste, and which you may want to use as inspiration for writing new portions of code.


text:
Serial printf implementation
Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:
int PIN = 12;

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  sprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

void setup() {
  Serial.begin(9600);
  Serial.println("serial monitor has been set up");
  char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf0, "pin %i configured to output", PIN);
  Serial.println(buf0);
  _printf("pin %i configured to output", PIN);
  char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf1, "pin %i configured to output", PIN);
  Serial.println(buf1);
  _printf("pin %i configured to output", PIN);
  pinMode(PIN, OUTPUT);
  char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf2, "pin %i configured to output", PIN);
  Serial.println(buf2);
  _printf("pin %i configured to output", PIN);
  char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf3, "pin %i configured to output", PIN);
  Serial.println(buf3);
  _printf("pin %i configured to output", PIN);
}

void loop() { }

But it gives me some weird output:
serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

What do 2263 and 2269 mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

Any reason to not use the standard printf()?

Streaming.h lets you write code that's rather more clear, using a lot less memory and producing much less assembly code.  See for example my answer to question 33319 that explains how to use it

The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.
Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.
When calculating your buffer size from a list of variables in your main loop you are incorrectly using vsnprintf - you should be using snprintf since you aren't passing it a va_list, but individual variables. In your _printf function you are correctly using vsnprintf to calculate the length of the buffer, but then incorrectly using sprintf with a va_list instead of individual variables.
So your two forms should actually be re-written as:
// Inline version
char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
sprintf(buf0, "pin %i configured to output", PIN);
Serial.println(buf0);

and:
void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  vsprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

Remember: if you have a va_list then it goes with a v*printf function. If you have individual variables they go with a *printf function.


text:
ESP8266 doesn't respond to Serial.println("AT")
If I don't declare Serial.begin(115200), I can send AT commands over serial monitor and it replies me.

But when I declare Serial.begin(115200) and send AT commands inside program or serial monitor there is nothing happens.

Did I miss something?

Just copy-paste the code/output. Don't post screenshots.

But I'm not answer to someone. You don't need the codes.

You have connected the tx of the Arduino to the tx of the ESP8266 and the rx of the Arduino to the rx of the ESP8266.
What is happening when you type AT in the Serial Monitor is that you are communicating directly with the ESP8266, and not with the Arduino.
You need to connect the rx of the Arduino to the tx of the ESP8266 and the tx of the Arduino to the rx of the ESP8266.
This has asked and answered a number of times, such as:
Arduino Uno and ESP8266 serial monitor issue
Arduino & ESP8266
Arduino Nano v3.0 with ESP8266
ESP 8266 does not respond at all
Your ESP8266 definitely uses a baud rate of 115200 (as confirmed by your first screen shot), so you don't need to change that when experimenting.

Thank you for the answer @Holmez, third link was very helpful.
I was just change the code and the RX, TX pins like below and it works perfect now.
I can send commands to the ESP both in program and over the serial monitor.

#include <SoftwareSerial.h>

SoftwareSerial wifi(10, 11);

void setup() {
  Serial.begin(115200);
  wifi.begin(115200);
  Serial.println("Test");
  wifi.println("AT+CIFSR");
}

void loop() {
  if (Serial.available()) {
    wifi.write(Serial.read());
  }
  if (wifi.available()) {
    Serial.write(wifi.read());
  }
}


text:
Expected ')' before ';' token Error
Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the Expected ')' before ';' token Error
Here is the code:
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i ; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i (&gt);= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

We could really use some help.

Well, for example for doesn't have four parts but three
for (int i = 0; i ; 256; i++) // => for (int i = 0; i < 256; ++i)

Next one doesn't look much better:
for (int i = 255; i (&gt);= 0; --i) // =>  for (int i = 255; i >= 0; --i)

There might be more, but these are really obvious. Like you copied it from some website with some characters translated into the html entities.

Thank you very much,yes indeed we copied the code from a website,thank you for helping us!

If this answer solves your issue and was useful please up vote and accept it


text:
Burning the Arduino bootloader without an extra Arduino board
Is there any way to burn the Arduino bootloader on a standalone Atmega328 (internal clock 8MHz) from the Arduino official website without using an extra Arduino board to burn the bootloader?
I mean, is it possible to burn the bootloader on the Arduino and then remove the ATmega chip from the Arduino board and use it in a breadboard?
Thanks.

If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:

Yes, use an ISP programmer. I personally use Atmel ICE, Arduinos as ISP and USBasp.
AVRISP is another popular option:

This tutorial might be useful: Sparkfun.

so it's not possible to burn the bootloader on the ATMega using the arduino board itself (conectet to the pc via USB) and then remove the MCU and use it standalone?

Not using the board itself. (It could be possible if you modified the USB>Serial Atmega to become some sort of USBtinyISP, cut and rewired a bunch of stuff, but it wouldn't be practical at all and you'd still need a programmer to reprogram it anyway). So you need a programmer at some point.


text:
NodeMCU Light Sensor
I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).
I've successfully printed from a single light sensor but now I'd like to try three.
I'm curious to know what I'm missing.  Any guidance would be appreciated.
Code is as follows:
const int photocellPin_0 = 16; // D0
const int photocellPin_1 = 5; // D1
const int photocellPin_2 = 4; // D2
int photocellReading_0;
int photocellReading_1;
int photocellReading_2;

void setup() {
  delay(4900);
  Serial.begin(115200);
  Serial.println("Startup");
  delay(100);
  pinMode(photocellPin_0, INPUT);
  pinMode(photocellPin_1, INPUT);
  pinMode(photocellPin_2, INPUT);
}

void loop() {
  delay(1000);
  photocellReading_0 = analogRead(photocellPin_0);
  photocellReading_1 = analogRead(photocellPin_1);
  photocellReading_2 = analogRead(photocellPin_2);
  Serial.println("-----NEW ON READING-----");
  Serial.print("Photo Sensor #1 = ");
  Serial.println(photocellReading_0); // the raw analog reading
  Serial.print("Photo Sensor #2 = ");
  Serial.println(photocellReading_1);
  Serial.print("Photo Sensor #3 = ");
  Serial.println(photocellReading_2);
  delay(5000);
}

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.

you can only use analogRead on pin A0 on the ESP8266. you can multiplex or even use a relay to switch out sensors, or use a cheap and precise I2C ADC, like the 16-bit ads1115 ($2.5), which gives you four hi-res analog inputs. you could also use a cheap pro mini or nano to expand IO, but they don't have the best ADCs...

The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).
digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.
You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.
The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts


text:
How to send sensor data from Arduino through NRF24L01 to Raspberry Pi

I am able to send text from the Arduino wirelessly to RPi.  I am now trying to send the sensor data I'm measuring to the Pi.  This is what I have below:

int moisture = A0;
int temp = 3;

//Skipping the setup and reading of the values

radio.write(&moisture);
radio.write(&temp);

//the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the write() method accepts (or requires) a second parameter, len, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.
Either of those cases could produce erratic results.
Instead of leaving off the second parameter, specify it.  For example:
radio.write(&moisture, 2);
radio.write(&temp, 2);

I recommend you to choose a platform for communication. You don't need to deal with the low level communication.
I suggest you to try https://www.mysensors.org/ It helps to wire your sensors, gives you example codes for the chosen sensors for data transfer in the direction to your Pi. There is a well documented API you can build your application on.
On the Pi you can use a serial gateway or/and a controller installed. These controllers are written to communicate with your sensors and other nodes. They give graphical web interface to visualize your data and their history. For a controller I recommend to start with https://www.domoticz.com/ or Openhab I think Domoticz is the better choice to start with on Pi.

most likely is that your nrf24l01 library only allow text or string communcaiton, not nuermical data.  when you send your measured data, nrf24l01 treats it as text.  so what you read is text (text's unicode numbers).  I encountered the same problem.

I will suggest you to provide valid size of data with write function for eg radio.write(&moisture,sizeof(moisture)). hope this will work for further explanation of this method www.robofever.in


text:
How to concatenate strings
I am new to the Arduino platform so please bear with me. I have a program to display rolling text on a LED matrix which is for the Tinyduino platform
#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"

void setup()
{
  LedSign::Init();
}

static char test[]="HELLO";

void loop()
{
  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
}

Then I have some code to read temperature and humidity data for the same Tinyduino platform
#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
}

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  Serial.print(celcius);
  Serial.print(" deg Celsius\t");
  Serial.print(relativeHumidity);
  Serial.println("% relative humidity");

  delay(500);
}

I am trying to integrate this together so that Arduino reads the temperature and humidity sensor data and then displays it on the LED matrix as text. I have some code that is integrated from the above two examples
#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"
#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
  LedSign::Init();
}

static char test[100]="";

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
  delay(500);
}

Here is the error message that the IDE throws out
test:28: error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

 test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";
                             ^

Using library LOL in folder: C:\Program Files (x86)\Arduino\libraries\LOL (legacy)
Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Using library Temp in folder: C:\Program Files (x86)\Arduino\libraries\Temp (legacy)
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Any suggestions on how to resolve this error is welcome.

Good first question!

You can use sprintf to format a string.
You have to change:
test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

for
sprintf(test,"%d deg celsius %d relative humidity",celcius,relativeHumidity);

I have the code working but the sensor does not refresh the data and displays it only once. Do you see any reason why that would happen

In this line there is no condition: for (int8_t x=DISPLAY_COLS, i=0;; x--). More info: https://www.tutorialspoint.com/cprogramming/c_for_loop.htm.

You cannot "add" character arrays like that. You may try to use a
String object instead, as these do support the + operator as a way
to concatenate them:
String message = (String(celcius) + " deg Celcius, "
               + relativeHumidity + " relative humidity");
const char *c_message = message.c_str();

And then you use c_message in place of your test variable.
Note that only the first element (celcius here) needs to be explicitly
converted to a String object. The other conversions happen implicitly.
Edit: Updated the code to avoid using the internal state of a
(possibly destroyed) temporary object.

-1 This results in undefined behavior.

@TomKnapen: Oops! Updated the code.


text:
Powering Arduino Mega 2560 from a Raspberry Pi Usb
I have a Raspberry Pi B+ running 7x24. I have to connect an Arduino Mega 2560 to its USB. The Arduino has only one nRF24L01-PA-LNA powered from its 3V3.
Can I power the Arduino from the Pi's USB?

I think the quickest away of getting an answer would be to RTM.  Search for the technical specs and what ampage the Pi can put out and see what the mega draws.  TBH I suspect that it isn't going to work.

If you are powering your RPi from power supply 5V/2A at least there should be no problem. USB hub on the RPi should not give more than 500mA to power Arduino. Also there is a fuse on Arduino's board to prevent any damage from USB power.
Check both Arduino and RPi schematics for more details about modules used there:

Arduino
Raspberry

The power of the Pi looks OK. But! The 3V3 ouput of the Mega has 50mA output. The nrf24L01-PA-LNA consumes 45mA in receiver mode but needs 115mA in emission mode. Emission is a peak. Using capacitor would be a solution but it is on the limit, I think it's not the solution for 7x24.

raspberry pi can power ur mega board normally,but the 3v3 in the mega board is not stable and has noise,so it is better to use 3v3 supply source for ur NRF the simplest to use is just hooking a piece of 1117 to 5v of ur mega board

Thanks, I got 5V from an other USB for the 1117 and for a capacitor. Works like a charm. :)

Yeah, as the others have mentioned you can power the Arduino form the raspberry pi's power supply, but you cannot transit data from the raspberry to the Arduino without a third party software.


text:
Arduino for push notifications to phone
I'm interested in using an Arduino for a project for taking information and sending it through a phone application. I was wondering what the cheapest option there is for an arduino with internet capabilities. From what I see, a lot of articles list they use UNOs with shields for wifi/ethernet. After looking these up, I noticed that they can get a little pricey. Is there any alternative options I may be overlooking? Thanks.

You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.

Also, the ESP8266 itself can be coded with the Arduino IDE/environment, and could replace an existing arduino. In general the ESP8266's have more RAM and flash storage than the UNO.

Is it possible to use any GPIO on ESP8266? It would be nice to hook the sensor directly onto ESP8266. For example DHT22.

The ESP8266 has several GPIO pins. https://github.com/esp8266/Arduino/blob/master/doc/reference.md#digital-io
Note that they are 3.3V, not 5V like the UNO.

Well then you can't get any cheaper than ESP8266 if your requirements are limited to a few GPIOs. Thank you for pointing that out @josecanuc.


text:
Does Arduino sent output to TX pinout?
I am beginner at Arduino,i tried to read as much as i can but i am not sure if i am doing good.I would like to send a specific code for a (non PC) device through the TX pinout when i push the button which is wired to the Pin 2.I have writtem this small code to check it:
int buttonUPpin = 2;
int UpinStatus=LOW;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
pinMode(buttonUPpin, INPUT_PULLUP);
digitalWrite(buttonUPpin,HIGH);

}

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

UpinStatus=digitalRead(buttonUPpin);

if(LOW==UpinStatus)
{
Serial.print('A');
digitalWrite(1,LOW);

}

}

When i push the button i can see at serial monitor the 'A' character but i am not sure if this character was also sent out to the TX pinout since the TX led is not blinking only the RX led.

You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).
#define buttonUPpin = 2;
#define LedPin = 3;
int UpinStatus = LOW;

void setup()
{
    Serial.begin(9600);
    pinMode(buttonUPpin, INPUT_PULLUP);
    pinMode(LedPin, OUTPUT);
    // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

}

void loop()
{
    UpinStatus=digitalRead(buttonUPpin);
    if(LOW==UpinStatus)
    {
       Serial.print('A');
       digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
    }
}

If you start the Serial it takes over the TX and RX pins and it ignores pin mode settings (and digitalWrite too).
Btw TX and RX LEDs are driven by USB to Serial interface chip so you don't have any control of it either.

in this case how can i be sure that the desired output was sent out?

If you mean TX/RX LEDs, then they are blinking if you're receiving data from computer (RX), or if you're sending data to the computer (TX). If you mean logic state on pin, you can't use pins 0 and 1 with Arduino Serial.

Rx led is blinking when i push button2 but there is no tx led blinking in the same time(to send to the tx pinout)


text:
Time displays on serial monitor but not my LCD
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

#define PIN_SCE   7
#define PIN_RESET 6
#define PIN_DC    5
#define PIN_SDIN  11
#define PIN_SCLK  13

#define LCD_COMMAND    LOW
#define LCD_DATA     HIGH

#define LCD_X     84
#define LCD_Y     48

String now_time;
char printTime;

void gotoXY(int x, int y) {
  LCDWrite(0, 0x80 | x);  // Column.
  LCDWrite(0, 0x40 | y);  // Row.  ?
}

//This takes a large array of bits and sends them to the LCD
void LCDBitmap(char my_array[]){
  for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
    LCDWrite(LCD_DATA, my_array[index]);
}

//This function takes in a character, looks it up in the font table/array
//And writes it to the screen
//Each character is 8 bits tall and 5 bits wide. We pad one blank column of
//pixels on each side of the character for readability.
void LCDCharacter(char character) {
  LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding

  for (int index = 0 ; index < 5 ; index++)
    LCDWrite(LCD_DATA, ASCII[character - 0x20][index]);
    //0x20 is the ASCII character for Space (' '). The font table starts with this character

  LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
}

//Given a string of characters, one by one is passed to the LCD
void LCDString(char *characters) {
  while (*characters)
    LCDCharacter(*characters++);
}

//Clears the LCD by writing zeros to the entire screen
void LCDClear(void) {
  for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
    LCDWrite(LCD_DATA, 0x00);

  gotoXY(0, 0); //After we clear the display, return to the home position
}

//This sends the magical commands to the PCD8544
void LCDInit(void) {

  //Configure control pins
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_SDIN, OUTPUT);
  pinMode(PIN_SCLK, OUTPUT);

  //Reset the LCD to a known state
  digitalWrite(PIN_RESET, LOW);
  digitalWrite(PIN_RESET, HIGH);

  LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
  LCDWrite(LCD_COMMAND, 0xAF); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
  LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
  LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14

  LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
  LCDWrite(LCD_COMMAND, 0x0C); //Set display control, normal mode. 0x0D for inverse
}

//There are two memory banks in the LCD, data/RAM and commands. This
//function sets the DC pin high or low depending, and then sends
//the data byte
void LCDWrite(byte data_or_command, byte data) {
  digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command

  //Send the data
  digitalWrite(PIN_SCE, LOW);
  shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
  digitalWrite(PIN_SCE, HIGH);
}

void setup(void) {
   LCDInit();
   LCDClear();
   Serial.begin(9600);
   while (!Serial) ; // Needed for Leonardo only
   setSyncProvider(RTC.get);   // the function to get the time from the RTC
   if (timeStatus() != timeSet)
     Serial.println("Unable to sync with the RTC");
   else{
     Serial.println("RTC has set the system time");
      digitalClockDisplay();
   }
}

void loop(void) {
  if(timeStatus() == timeSet)
  {
    delay(1000);
    digitalClockDisplay();
  }
}
void digitalClockDisplay(){
  // digital clock display of the time
  if(minute() < 10)
  {
    now_time = String(hour()) + ":0" + String(minute());
  }
  else if(minute() >= 10){
    now_time = String(hour()) + ":" + String(minute());
  }
  Serial.println(now_time);
   LCDClear();
   LCDString("Time: ");
   for(int i = 0; i <= now_time.length()-1; i++)
   {
      printTime = now_time.charAt(i);
      LCDString(printTime);
   }

}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  LCDString(":");
  if(digits < 10)
    LCDString('0');
  LCDString(digits);
}

When I run the code the time will display perfectly on the Serial Monitor but when I connect it to my Nokia LCD screen the words "Time: " will appear along with some random characters. Anyone know why this is?

LCDString expects a c-string not a single character.

I assume you are writing now_time one Char at a time because the LCD library does not accept the String object as input? LCDString assumes you will pass a C-style string -- that is a pointer to an array of char. When you pass in one character, it's not a pointer to a C-style string, but the LCDString function is assuming that it's a pointer to some bit of memory elsewhere.
Try not sending one Char at a time, but:
LCDString(now_time.c_str());


text:
Seven segment display multiplexing
I have written a code that displays a number into a seven segment display without manually setting the Arduino pins HIGH/LOW for each number. Now, my problem is how can I display a number larger than 9? This is my code and it works for only 1 digit number: (The seven segment display truth table is inverted because I'm using common anode 7seg)
#define SEG_A 2
#define SEG_B 3
#define SEG_C 4
#define SEG_D 5
#define SEG_E 6
#define SEG_F 7
#define SEG_G 8
#define DEC_P 12

#define SET1 9 // [!][!][x]
#define SET2 10// [!][x][!]
#define SET3 11// [x][!][!]

struct segmentmap {
  uint8_t num;
  const int segment[7];
};

const struct segmentmap segments[] = {
  // n   A  B  C  D  E  F  G
  {0, {0, 0, 0, 0, 0, 0, 1}},
  {1, {1, 0, 0, 1, 1, 1, 1}},
  {2, {0, 0, 1, 0, 0, 1, 0}},
  {3, {0, 0, 0, 0, 1, 1, 0}},
  {4, {1, 0, 0, 1, 1, 0, 0}},
  {5, {0, 1, 0, 0, 1, 0, 0}},
  {6, {0, 1, 0, 0, 0, 0, 0}},
  {7, {0, 0, 0, 1, 1, 1, 1}},
  {8, {0, 0, 0, 0, 0, 0, 0}},
  {9, {0, 0, 0, 1, 1, 0, 0}}
};

void setup() {
  Serial.begin(9600);
  for (int x = 2; x <= 8; x++) {
    pinMode(x, OUTPUT);
    Serial.print("Segment pin: ");
    Serial.print(x);
    Serial.println(" is set to OUTPUT mode.");
    digitalWrite(x, HIGH);
  }
  pinMode(DEC_P, OUTPUT);
  pinMode(SET1, OUTPUT);
  pinMode(SET2, OUTPUT);
  pinMode(SET3, OUTPUT);
  digitalWrite(SET1, 1);
}
int x = 0;
void loop() {
  if (x > 9) {
    x = 0;
  }
  updateDisplay(x);
  delay(1000);
  x++;
}

void updateDisplay(int input) {
  for (int x = 0; x <= 9; x++) {
    //Serial.println(segments[x].num);
    if (segments[x].num == input) {
      Serial.println(segments[x].segment[0]);
      ////////////Simplify this part//////////////
      digitalWrite(SEG_A, segments[x].segment[0]);
      digitalWrite(SEG_B, segments[x].segment[1]);
      digitalWrite(SEG_C, segments[x].segment[2]);
      digitalWrite(SEG_D, segments[x].segment[3]);
      digitalWrite(SEG_E, segments[x].segment[4]);
      digitalWrite(SEG_F, segments[x].segment[5]);
      digitalWrite(SEG_G, segments[x].segment[6]);
      ////////////////////////////////////////////
      //Multiplex here?//
    }
  }
}

It looks like you are using a 3 digit common anode display.
If your code currently works, fixed to display something on digit 0, then you could get it working for all 3 digits by adding/updating the following:
// globals:
byte display_buffer[3] ;  // representation of the display which you can change in loop()
byte anode_map[3] = { 9, 10, 11 } ;  // anode pins

void loop() {
  if (millis() % 5 == 0 ) updateDisplay();  // every 5mS - better to use a timer
  if ( millis() % 1000 == 0) {  // every second
    if (x > 9) {
      x = 0;
    }
    display_buffer[0] = x ;  // just for testing
    display_buffer[1] = (x + 11) % 10 ;
    display_buffer[2] = (x + 12) % 10 ;
    x++;
  }
}

void updateDisplay() {
   // called every x Ms preferably with a timer
   // selects next item from display_buffer_ptr and displays it
   //
   static byte display_buffer_ptr ;
   display_buffer_ptr ++ ;
   if ( byte display_buffer_ptr > 2 ) display_buffer_ptr = 0 ;
   int input = display_buffer[display_buffer_ptr] ;
   for ( int i = 0 ; i < 3 ; i++ ) {
       digitalWrite( anode_map[i], ( i == display_buffer_ptr ) ) ;  set current anode HIGH, rest LOW
   }
   // rest of your code to display the value of input

}

This is not the most elegant solution but involves minimal changes to your code.
It is more usual to use an array of byte for the mapping digits to segments.
You may have to optimise the switching of the anodes to stop ghosting.

my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.
your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.