text:
Encoders for precise robot turns
So I recently purchased:
DFRobot Wheel Encoders
DFRobot 3PA and 4WD Rovers (2pk)
Romeo V2 Arduino Controller
I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!

  void stop(void)
    {
      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

    }
    void forward(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,HIGH);
      analogWrite(6,b);
      digitalWrite(7,HIGH);

    }
    void back(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,LOW);
      analogWrite(6,b);
      digitalWrite(7,LOW);

    }
    void Left(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,LOW);
      analogWrite (6,b);
      digitalWrite(7,HIGH);

    }
    void Right(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,HIGH);
      analogWrite (6,b);
      digitalWrite(7,LOW);

    }
    void setup(void)
    {

      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      for(int i =4;i<=7;i++)
        pinMode(i, OUTPUT);
      pinMode(LED_BUILTIN, OUTPUT);
     forward(100,100);

      Serial.begin(9600);

    }
void GetSensor()
{

  Sen_Val_B = SenAvg(Sensor_Back);
  Sen_Val_F = SenAvg(Sensor_Front);
  Sen_Val_R = SenAvg(Sensor_Right);
  Sen_Val_L = SenAvg(Sensor_Left);

}

int SenAvg(int SensorNumber)
{

  Arr[100]= 0;
  avg = 0;

  for(int i = 0; i<100; i++)
  {
    Arr[i] = analogRead(SensorNumber);
    avg = avg + Arr[i];
  }
    avg = avg/100;
    return avg;
}
void loop(void)
{

   GetSensor();
  if(Sen_Val_F > 200)
  {
   stop();
  }

}

What encoders do is give you clocked feedback on motor rotation, which you can count to get an idea of position and speed. So in order to turn by a specified amount, you will need to know how much your wheel has to turn for the given angle. You can then turn the wheel precisely by dividing your wheel circumference with the maximum encoder ticks per revolution.
Say we get 600 ticks per revolution and our wheel has a circumference of 10cm.
We would then turn the wheel by 100mm / 600 = 0,16mm per encoder tick!
You could even write a function taking more parameters into account (robot diameter/distance between wheels) that calculates these values.
A faster/more empirical approach than gathering all these values is to just drive your robot for x (i.e. 100) ticks and measure the angle it drove to get a direct relation between encoder ticks and robot angle.
Another, much more precise solution would be to utilize a compass or gyroscope to measure the robot's orientation and rely on that instead of the encoders.

All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn.

would this work?
  if (wall_sensed()) turn_90right(); //if wall is sensed, turn 90 degrees to the right

You may also consider change
  digitalWrite(5,LOW);
  digitalWrite(6,LOW);

to:
  digitalWrite(MOTOR_LF,STOP);   //stop left front motor
  digitalWrite(MOTOR_LR,STOP);   //stop left right motor

so that

it is a lot more readable; and
if you were to change pin assignment, it is done consistently throughout your code.

I can get the robot to turn but I'm trying to get precise 90 degree turns. I was doing the brute force approach but just using a delay. But this method seems to be inconsistent.

Hmm, when making a turn, your wheels may slip. You could check the accuracy on a compass sensor. Because if you turn a few times, you'll slowly get an offset due the inaccuracies. With a compass you get an absolute heading instead of accumulating all turns (which accumulates the error).


text:
Led and button simulation of a blink
My circuit:

My code:
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2; // pushbutton connected to pin 2.

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == HIGH) // check while the button is pressed
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
  }
}

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?

There is only one pin of the button connected to IO2. Is the other connection missing only in the diagram? Or is it missing in your actual circuit as well?

@DirkGrappendorf Yeah there is only one pin connected to pin 2. Why is that you need another one? and from where?

I meant the other pin of the button. It is not connected to anything. See my answer.

Another pin of button must be connected with ground. That thing missing in your circuit. Provide ground to another pin of button and it's working fine with your code.

The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).
There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in this tutorial).
I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to
pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a digitalRead(buttonPin) returns HIGH. When you press the button, IO2 is pulled to GND and digitalRead(buttonPin) returns LOW.
So in your case you need to check for a LOW reading, because you want the LEDs to blink when the button is pressed.
(Btw. you can replace the while loop with an if, since the loop() function is already executed in an infinite loop.)

source: Stack Exchange

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

sort: votes


text:
Does int array[100] = {0} construct work on Arduino?
I'm compiling my code in Arduino IDE. I have an array that I want to 0-initialize. I know memset works on Arduino, but I'm used to this way from my desktop C++ programming practice:
int array[100] = {0};

I couldn't find any info on whether or not this construct works on Arduino. I think it should since it uses GCC compiler. Even though it may be modified, I still expect it to remain C and C++-compliant. Still, can you confirm for me that this standard-compliant C/C++ construct works on Arduino?

Have you tried it? What were the results?

@Majenko: It seems to: the program is much larger with = {0} that without it, so the compiler is definitely doing something. On the other hand, in my test the array was all 0s both with and without = {0}. Problem is, that proves nothing. It doesn't guarantee that it will work on some other compiler with some other settings. The testing would only be conclusive if it demonstrated that this code does not work.

It's not the compiler that does it (and the = {0} does nothing by the way) but the CRT (initialization code). Maybe this will explain: https://en.wikipedia.org/wiki/.bss

@Majenko: a) if it does nothing then Arduino IDE compiler is broken: http://stackoverflow.com/a/629063/634821
b) how does it do nothing when it increases code size by a couple hundred bytes?

The = {0} may have prevented an otherwise unused variable from being optimized out of the code.

@Majenko: it was very much used, I was printing it to Serial in setup().

Maybe it changed how it was initializing it to zero - explicitly clearing that memory block rather than just relying on BSS being cleared already. So it may change the behaviour but not the end result - and ends up just needlessly increasing the size of your program.

you can actually try it and see it by printing on the serial monitor :)

@Manav: I did, see my first comment to Majenko. It proves nothing if it appears to be working right. Only a negative result would be conclusive.

You should start from the premise that the Arduino uses standard C++ (however exceptions are disabled by a command-line switch). If something is standard C++ then it will work. You don't need to worry about proving it.

I'm used to this way from my desktop C++ programming practice:
int array[100] = {0};

I couldn't find any info on whether or not this construct works on Arduino.

The = {0} has no actual effect. It is the same as:
int array[100];

Uninitialized static / global variables, and variables explicitly initialized to 0, are placed in the .bss section of memory.
This section is initialized to 0 by the CRT (C Runtime) code (the startup code for the system).
The compiler is responsible for placing these variables in the .bss, but it is the job of the startup (CRT) code to initialize it to zero.
This is standard C operation and is not likely to ever change since it would break all sorts of things.
Note: this does NOT apply to local variables allocated on the stack. These must be initialized to 0 if you want them to start as 0.

Very well, thanks for the explanation. I have no habit of relying on C default-initializing POD types (because it usually doesn't) and hence prefer doing it explicitly, but then, I also have no habit of using global or static data a lot. Didn't know the global variables are guaranteed to be default initialized (or zero-initialized? I always confuse these two terms). The main point of = {0} is that it also works for local arrays.

This construct does work in Arduino IDE. In fact, = { 0 } is one of the iconic idioms of C language. It can be used to zero-initialize an object of any type in C. In C++ things are a bit more complicated. It will work for an int [100] array, but in general case you might be better off with = {} initializer to achieve the same effect where applicable.
It is not clear why the accepted answer claims that this construct "has no actual effect" though. This is, of course, incorrect. More precisely, this initializer is redundant ("has no effect") on variables with static storage duration, since such variables are default-initialized anyway (zero-initialized for int [100]), even if you don't request it explicitly. But for a local variable declaration the effect of = { 0 } is undeniable and obvious: it will zero-initialize the array (which wouldn't've been initialized without it).
Note that even though the 0 in the = { 0 } initializes the first element of the array, this initializer ultimately triggers zero-initialization if the entire array.

The GNU cross compilers for Arduino use C/C++ front-ends and meet some version the language specs. (Although that is a moving target, you can expect a recent IDE version will be compliant with a reasonably recent language spec.)
"Arduino language" is a misnomer. The Arduino IDE will try to assist new programmers by, for example, automagically discovering library references and inserting the required #includes for you, but the resulting code is C++ and will be presented to a C++ compiler. The IDE provides a main() function that calls setup() and loop() (and serialEventRun() if you provide one) thereby reminding the programmer to initialize whatever needs to be initialized before expecting things to work right. However you can write proper C++ and get what you've come to expect. You'd have to go 'behind the IDE's back' as it were, to suppress the automatically-supplied main() function, but the toolchain doesn't care, as long as there is one and only one, main().
I tested this this trivial program:
    int array[100];

    void setup() {
      // put your setup code here, to run once:
       for(uint8_t i = 0; i < sizeof(array); ++i)
          array[i] = i;
    }

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

    }

with both the Arduino IDE and Sloeber - Eclipse with the EclipseArduino plugin, which routinely provides a basic memory map after compilation - and with and without the initialization expression = {0}. I found no difference in the size of the output in either environment, with or without the initialization. In all four cases, the .bss was 209 bytes, 200 bytes larger than without the global array.

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

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


text:
BLE Shield v2.1
I have an Arduino Mega 2560 and a BLE Shield v 2.1 from RedBearLab. When I try to connect it through Bluetooth from my laptop to 'BLE Shield', it says 'Connected!'. When I try from a Windows phone, it also says 'Connected'.
But when I try to connect from an Android device, it gives me an error: 'pairing rejected by BLE shield' or 'couldn't pair with BLE Shield because of an incorrect PIN or passkey'.
What seems to be the problem?

I would guess that the problem is an incorrect PIN or passkey.
I've read from manuals for some gadgets that some devices/phones automatically try the PIN 0000 and some don't.  I have never seen my Windows phone ask for a PIN when the device hasn't got one set, so I'm guessing that Windows automatically tries 0000 and Android doesn't.  Is there a  setting on Android that will let you enter the pin (which is probably 0000) ?

Also, sometimes the pin is 1234 on default and can be changed through AT commands


text:
MIDI connectors / Diodes
Does anybody know if the following MIDI DIN connectors will fit in a breadboard?
(or in general with 'generic' electrical components?)
MIDI DIN
And the same for:
Diodes to be used for MIDI in.

What does the footprint diagram in the datasheet tell you?

There are dimensions (no real datasheet), but since the pins of the Arduino breadboard are like 2 mm apart I guess it would work.

2.54mm to be precise. It's a 0.1" grid.

Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.
Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

(search for "5 pin DIN female jack")

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.

Thank you for all this useful information. I need to check for soldering, no experience with that either (and I'm not so handy). And thanks for the other  info too... I almost wanted to buy that specific 1N914 diode and 6N138. Sorry, I don't have much electrical knowledge (yet).

All those PCB-mount DIN jacks have the same footprint.

It's almost impossible to destroy anything if you try to solder thinner wires to the pins … :)

That's true maybe... however, the problem with thinner wires is that it the MIDI connectors will be not really placed directly in the board probably (meaning like resistor wires they will moving) and to regularly replace MIDI cables) which are heavy I hoped for a MIDI connector (or more) that can be inserted without any issue.
This one looks really much like the one I posted in my question and is prototype friendly: https://www.sparkfun.com/products/9536
Also I have to check into test clips.


text:
ESP01 unsuccessful code execution
I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. I have tried with different example sketches but it seems code was not uploaded.
My Board manager configuration

Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40 MHz
CPU frequency: 80 MHz
Flash size: 1M (128K SPIFFS)
Debug port: Serial
Debug level: none
Reset method: ck (tried nodemcu too without success)
Upload speed: 115200
USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
e:
 ets Jan  8 2013,rst cause:3, boot mode:(3,7)

ets_main.c

and here's the IDE console window output:
sptool.py v1.3
Connecting..........
Auto-detected Flash size: 8m
Running Cesanta flasher stub...
Flash params set to 0x0020
Writing 229376 @ 0x0... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
Leaving...

The sketch I am using
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

The standard blink example from the Arduino IDE uses pin 13. Have you modified it to use an equivalent pin on the ESP8266 to which a led has been attached ? You may also find that for uploading a sketch, it is necessary only to have GPIO0 pulled low during the reset/restart. Afterwards, you may then pull it high to load the sketch and run it.

Yes, I am using the LED_BUILTIN macro

try using 1 instead of the macro

@dandavis nothing, I have also tried to upload a different sketch for a Captive portal but code doesn't seem to be running.

If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.
I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use digitalWrite(2, HIGH); in you code.
Have a look at this page and see if what its on about is what you are trying to do.
http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example

I guess it may be better to use a sketch which writes to the serial console to see signs of life from it if the led method is not conclusive. Incidentally, connecting a Uno directly to the ESP01 (which the OP appears to be doing)  will result possibly in 5v at the ESP01 RX pin and some sort of level shifting is recommended.

Exactly, that is what I thought and apparently serial communication within the sketch is not working (the code was just sending a string over serial, no leds involved).

GPIO1 is also known as TX, and on the ESP-01 it can be used as a digital output. Note that the blue on-board LED is also tied to GPIO1, as an inverted on-low configuration. You can't use Serial.begin if you use TX as an output.

I'm using this sketch: void setup() { Serial.begin(9600); } void loop(){ Serial.println("Hello World!"); delay(1000); }

@Anelito - 1. Are you connecting via Arduino? 2. Can you connect direct to PC/Mac? 3. Have you got a second ESP-01? 4. Are you using level shifting?

I am using an Arduino UNO as serial programmer (I have removed the Atmega) and a resistor-based level switch (2k and 1k). I have tried using esptool directly from command line and the output doesn't change. Unfortunately it's the only ESP module I got

Resistor based level switchers don't work for serial at 9600.  You can try 2400 baud, but are better off with a proper level shifter.

I know resistor switchers aren't the best choice but they worked when I was using the AT commands. I have tried with Serial and led sketches, so I believe there is a problem in uploading the code to the ESP or in running it.


text:
Post-split, where do I download the Arduino IDE?
I've been out of the loop with Arduino for several years.  I heard about the split (another link), but didn't really understand, nor keep up with it, nor the details of the fallout.
Today, I decided to jump back in and make something, and a DDG search led me to Arduino.cc to get the software.  But is that what I need?
How do I know if that's the right software IDE?  Is there another location?  Does it matter?  Does it depend on more variables?  Is this split akin to the OpenOffice and LibreOffice split, where one is more better (technical term!) supported than the other?
I'm working on an Arduino Uno I got from Microcenter.

The split is already over. They are working on merging everything that happened during the split, if they haven't already.
I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).

Both sites contain the same version of the IDE. .Org dropped their 1.7.x branch (actually 1.0.x renumbered) and both now have the 1.6.x branch version-bumped up to 1.8.x.
As Gerben noted, the split is over, The rift is healed!.


text:
How I can make alarm on off?
I want to do is BEEP! to show that the program is running.
#define SPKR 4 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

With out this any other way
I mean without repeating the code HIGH / LOW
during this beep I want do same things else

I don't understand your question. I guess English isn't your first language. Can you find another way to explain it please?

you code works well as-is with an "active buzzer" module.

The code you show will toggle the SPKR pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.
To generate a tone, use tone(pin, frequency) calls, or tone(pin, frequency, duration) calls.
For example:
void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.


text:
How can an Arduino-Quadcopter be stabilized?
I have built an arduino quad-copter and I am using an MPU6050 to read the rotational position and velocity of the aircraft. The problem is that I cannot get the thing to stabilize. Watch this video here to get an idea of what I mean.
So as you can see from the footage (and you did watch it, right?), I'm not even getting steady oscillations, it's just random. What I don't understand is how people get their quad-copters to oscillate very quickly (maybe 10 times per second) and then trim up their PID gains to smooth it out, whereas if I raise my p-gain high enough for it to adjust that quickly, the quad-copter just goes berserk and tries to kill me.
And, speaking of p-gains, here's the PID I wrote:
float KrP = 0.002000;
float KrI = 0.000001;
float KrD = 0.200000;

void adjustRoll(float currentRoll, int newRoll) {
  if (thrust <= 1200){
    inAutoRoll = false;
    NWPower = thrust;
    NEPower = thrust;        //PID not ready to turn on yet? Just set motor powers
    SWPower = thrust;        //equal to the throttle.
    SEPower = thrust;

    I_roll = 0;              // Reset the integral.
    return;                  // Don't do anything else
  }

  float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
                                                                       // adjust, based on the error.

  if (newRate > 50)newRate = 50;        // Don't adjust too fast!
  else if (newRate < -50)newRate = -50;

  float offset = newRate - rollRate;

  I_roll += KrI * offset;

  if(!inAutoRoll) {        // Is the PID just now turning on? (Throttle requirement met).
    lastRollRateOffset = offset;  //Smooth transition.
    inAutoRoll = true;
  }

  float adjust = (KrP * offset) + (KrI * I_roll) + (KrD * (offset - lastRollRateOffset));

  NWPower += adjust;
  NEPower -= adjust;
  SWPower += adjust;
  SEPower -= adjust;

  if (NWPower > maxOut) NWPower = maxOut;
   else if (NWPower < minOut) NWPower = minOut;

  if (NEPower > maxOut) NEPower = maxOut;
   else if (NEPower < minOut) NEPower = minOut;

  if (SWPower > maxOut) SWPower = maxOut;
   else if (SWPower < minOut) SWPower = minOut;

  if (SEPower > maxOut) SEPower = maxOut;
   else if (SEPower < minOut) SEPower = minOut;

  lastRollRateOffset = offset;
}

And in case you were wondering... yes, I do know about integral windup. The reason I have not dealt with that in my code is because the quadcopter is no where near stable, so I'm not worrying about perfection just yet. Also, I have my I-gain set to 0.000001, so it doesn't matter. The reason I have done this is because (as far as I know) a quadcopter can fly with only P and D, and with the way mine is behaving, I think a larger I-gain would only make things worse.
More detail about my PID: The PID corrects for the rotational velocity of the quad-copter, which, as I understand it, is the best way to control a quadcopter. The correction-rotation-rate is determined by multiplying the error (in degrees) by two. Why two? I dunno. I experimented with some other multipliers and two seems to be okay. Its also a prime number, so, yeah...
So anyways! What do I need to do to make the quad-copter stable? I have seen amazingly perfect quad-copters using the same arduino and the same MPU6050, but mine just tilts all over the place.
Some possible problems off the top of my head:

Bad algorithm for calculating the needed rotational velocity based on error.
Bad PID algorithm.
Bad PID gains.
I didn't balance my props, but seriously, would a couple of pieces of electrical tape stuck to the props really fix this? It doesn't seem like it would.

Thanks for any help you have to offer!

Have you run some subsystem testing sketches?  Eg did you specifically test whether the MPU6050 is working correctly, motor drivers ok, etc?

The MPU seems fine. When I tilt it it gives me reasonable values for yaw pitch roll, as well as for rotational velocity. The drivers work fine too. I have the quadcopter plugged into my computer so I have all the data I could possibly want on my screen while it's running.

Re 4: The cool thing about quadcopters is that all the control trimming and balancing /can/ be done in math, rather than physically.

This is far, far, far beyond the scope of this site.  If you want to build something that flies, spend some time studying existing solutions and the control algorithms they use, and read the replacement firmware threads at rcgroups; also don't use an actual arduino - pretty much every project that started there has long since moved on to better choices.

Can you post more code? Where is the PID updated?

random behavior is a big problem with Drone.
Did you solve this problem ?
My drone has got the same random behavior.
infrare4ever

To help solve this problem, I wrote a program in Processing that graphs all the data from the quadcopter, including roll rate, roll angle, thrust, etc... After doing so I realized that the problem was not in the PID, but in how I handled the data coming out of MPU6050. You can read all about it in this question I posted here before I had discovered the full solution.
The quadcopter is now capable of taking off, though sadly it is not very stable. This could be from bad PID gains, but I suspect it is from vibration in the roll-rate values from the MPU6050. The reason I think this is because I don't see steady oscillations, but rather random movement. Anyway, If I find a more complete solution I will update this answer.

For stability and tuning you need to make the adjustment cycle time compatible with the physical system.  How fast does this adjustment code get called relative to how fast the physical system oscillates?  Without that under control, tuning the gains will be difficult, particularly for krI and krD.
For instance, if you are updating every millisecond, and it takes a 1/10th of a second to physically flop over from -90 to 0 at the current roll_thrust setting, there's only enough kP to adjust the roll_thrust kP*(RollDelta/2)*DT/dt=0.002*(90/2)*0.1/0.001=9  Is that a sane adjustment for a thrust/motorPower of 1200+?  If you sample fast enough to make it capable of a full-throttle (+/-800?) adjustment with this particular kP, you might need to sample 88x faster (1ms/(800/9)=0.01125ms).  From the other direction, I'd figure out how fast you can sample, then choose a krP that could get you a full-bias adjustment in reasonable time.
Maybe think of adjust as roll_thrust state variable measured in units of ESC_microseconds, and krP is the conversion factor from whatever error you are measuring.  Is it roll angle error? roll rate error? Absolute roll rate error?  It looks like this bit:
float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
if (newRoll - currentRoll < 0) {             // adjust, based on the error.
   newRate = 0 - newRate;
}

is essentially:
float newRate = 2 * abs(newRoll - currentRoll);

which might make control discontinuous.  If currentRoll is a positional roll angle setpoint, it won't be able to tell if it is on one side or the other.
If you want a roll angle of -90deg to make full throttle one way and 90deg to full throttle the other, then krP should be on the order of 900us/90deg=10us/degree.   And krI=krD=0 to start with.
I'd code up separate PIDs for thrust, roll_thrust, pitch_thrust, yaw_thrust control variables and then sum them together to get the  {NE,NW,SE,SW}Power outputs.  Then you could monitor and control in {thrust,roll_angle,pitch_angle,yaw_rate} space and the coding will be more straightforward and interpretable.

Thanks for your feedback! I have some things to clarify though: 1) I think you may have misread my code, because there shouldn't be any accumulation in the P adjust, which has no lasting memory between individual loops in the PID. 2) My throttle increments between 1100us and 1900us, so there is an 800 range, not 2500 (ESC's accept a ppm signal of 1000 - 2000us).

Also, how can I write a positional PID to control the speed PID that I already have, and still have the slightest clue as to which of the now SIX pid gains I would have to adjust? I tried it, but I don't know how to look at my quadcopter's behavior and deduce which of the six gains I need to change. That's why I just stuck with the [2* error] to make it simple.

You are right. I missed that the thrusts were initialized in the loop--it is a plain old positional form of PID--I'm striking the velocity form bit.  The krP, krI and krD, are just scaling factors from the various forms of error to the output variable.  I think I'm still confused about what the measured inputs are.

Actually, it is a velocity form PID, let me explain: "thrust" is the 1100-1900ppm signal from the thrust stick on my transmitter. Each motor is assigned that thrust in the beginning, then the PID adjusts that thrust to each motor to try to get the quad-copter to move at the desired rotational velocity(determined by 2* error in degrees from the desired angle). So to answere your question: The measured inputs are 1) the current angle of the quad-copter, and 2) the current rotational rate of the quad-copter. Also, the if(newroll-current roll<0) thing is an error on my part. I took it out.

Are you sure that driving rotational_velocity(deg/sec) towards the 2*error_deg value is the right control scheme?   This is beyond anything Arduino, but I think you'd want to work towards stability in degree-space.  Maybe not tracking the planned velocity curve at higher gains is what is causing your instability.

I'm not sure what you mean by "stability in degree-space" or by "tracking the planned velocity curve at higher gains". Do you mean that I should focus more on position rather than velocity? Anyways, right now I'm working on writing a program that will graph the data for me as I fly the quadcopter. That way I will be able to get a much better idea about where the problem is.

Yes, focus on controlling roll position instead of roll velocity.   On the second, I mean the stability problem you see at high gains might be because the desired velocity (newRate = 2 * (newRoll - currentRoll) might not be an appropriate goal for the physical system.

To be sure the receiver gets the right signal from the emitter it is mandatory to scrutinize the signal on the receiver for a while.
Once the signal on the receiver is checked good it is possible to go ahead step by step.
The first step is to drive the 4 ESC/motors with the same signal coming from the throttle.
Once the behavior of the 4 motors complies with changes on the throttle coming from the emitter it is time to go to the next step.
The next step stems from a mix with pitch/roll/yaw coming from the emitter.
The mix is added/removed to/from the throttle addressing each motor.
The behavior of the 4 motors must show exactly the mix that comes from the emitter.
An "acceptable" mix is something like (in the same unit, degres or microseconds):
Something like this:
int throttle_gaz;
int roll_length, pitch_length, yaw_length;

throttle_gaz=pulse_duration[throttle_chanel];
if ( abs(throttle_gaz-1500) <= 50 )
{
 throttle_gaz=1500;
}
roll_length=pulse_duration[roll_chanel]-1500;            //ROLL
if (abs (roll_length) <=100 )
{
roll_length=0;
}
roll_length/=3;

pitch_length=pulse_duration[pitch_chanel]-1500;           //PITCH
if (abs (pitch_length) <= 100 )
{
  pitch_length=0;
}
pitch_length/=3;

yaw_length=pulse_duration[yaw_chanel]-1500;             //YAW
if (abs (yaw_length) <=100 )
{
  yaw_length=0;
}
yaw_length/=3;

//add/soustract from THROTTLE (pulse_duration[throttle_chanel])
//change the sign (+ / -) acc
pulse_length_esc1=throttle_gaz + roll_length + pitch_length - yaw_length;
pulse_length_esc2=throttle_gaz - roll_length +  pitch_length +  yaw_length;
pulse_length_esc3=throttle_gaz + roll_length - pitch_length  + yaw_length;
pulse_length_esc4=throttle_gaz - roll_length -  pitch_length  -  yaw_length;

The question is about how to automatically stabilize the craft using data from an inertial measurement unit. Your answer does not address this question.

as a beginner in making a ,flight controller I am looking for a tutorial depicting all the steps to fullfil such a purpose.

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


text:
Cheat Sheet for interruption
Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?
The post with the nice timer cheatsheet was this one Arduino constant clock output

Wouldn't make much sense. Must peripherals can generate interrupts, and each has it's own semantics. An interrupt cheat sheet would have to cover the workings of most of the MCU peripherals: to much material for a “cheat sheet” format.

The "cheat sheet" is more commonly known as the datasheet.

Perhaps something like this (for the Arduino Uno based MPU):

The question was tagged “arduino-uno”, and this table does not apply to the Uno. You should at least tell in the answer what processor it is for.

Oops. You're correct. My apology. Let me edit that right now.


text:
Why does the serial monitor output show some unidentified symbols?
#define LED 13
#define BAUDRATE 9600
#define DEBUGOUTPUT 0
#define LED 13
#define powercontrol 10

// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[64] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;

//////////////////////////
// Microprocessor Setup //
//////////////////////////
void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(BAUDRATE); // USB
}

////////////////////////////////
// Read data from Serial UART //
////////////////////////////////
byte ReadOneByte() {
  int ByteRead;
  while(!Serial.available());
  ByteRead = Serial.read();
  #if DEBUGOUTPUT
  Serial.print((char)ByteRead);
  // echo the same byte out the USB serial (for debug purposes)
  #endif
  return ByteRead;
}

/////////////
//MAIN LOOP//
/////////////
void loop() {
  // Look for sync bytes
  if(ReadOneByte() == 170) {
    if(ReadOneByte() == 170) {
      payloadLength = ReadOneByte();
      if(payloadLength > 169)
      //Payload length can not be greater than 169
        return;
      generatedChecksum = 0;
      for(int i = 0; i < payloadLength; i++) {
        payloadData[i] = ReadOneByte();
        //Read payload into memory
        generatedChecksum += payloadData[i];
      }
      checksum = ReadOneByte();
      //Read checksum byte from stream
      generatedChecksum = 255 - generatedChecksum;
      //Take one's complement of generated checksum
      if(checksum == generatedChecksum) {
        poorQuality = 200;
        attention = 0;
        meditation = 0;
        for(int i = 0; i < payloadLength; i++) {
          // Parse the payload
          switch (payloadData[i]) {
            case 2:
              i++;
              poorQuality = payloadData[i];
              bigPacket = true;
              break;
            case 4:
              i++;
              attention = payloadData[i];
              break;
            case 5:
              i++;
              meditation = payloadData[i];
              break;
            case 0x80:
              i = i + 3;
              break;
            case 0x83:
              i = i + 25;
              break;
            default:
              break;
          } // switch
        } // for loop

        #if !DEBUGOUTPUT
        // *** Add your code here ***
        if(bigPacket) {
          if(poorQuality == 0) digitalWrite(LED, HIGH);
          else digitalWrite(LED, LOW);
          Serial.print("PoorQuality: ");
          Serial.print(poorQuality, DEC);
          Serial.print(" Attention: ");
          Serial.print(attention, DEC);
          Serial.print(" Time since last packet: ");
          Serial.print(millis() - lastReceivedPacket, DEC);
          lastReceivedPacket = millis();
          Serial.print("\n");
          switch(attention / 10) {
            digitalWrite(LED, HIGH);
            digitalWrite(LED, LOW);
          }
        }
        #endif
        bigPacket = false;
      } else {
        // Checksum Error
      } // end if else for checksum
    } // end if read 0xAA byte
  } // end if read 0xAA byte
}

A snapshot of the output would be quite helpful...

It time to start stroking our crystal balls, what symbols?
Actually it doesn't really matter, ReadOneByte() is the cause, you are printing ByteRead without checking that it is printable.  Character greater than 127 will look strange when you print them out, only 32-126 are printable (127 is backspace) see http://www.asciitable.com/ for more details.  In this case I would print the value as a hex number, Serial.println(ByteRead, HEX);
If you are still getting symbols after changing that there may be other prints that have the same problem

select the same serial Baudrate in the select which is in the bellow of the serial monitor window as you have put in the code.


text:
5V usb surge protection for circuit board?
I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

Arduinos can handle a wide variety of voltages.  The main reason to keep it below about 7 is simply to reduce heat stress on the on-board regulator.  Putting the voltage in via the Vin pin bypasses the regulator, though.  Using the mini USB will definitely limit the current the unit can draw for driving output pins.

you can use an LM7805 or an AMS117 LDO@5v to snub any excess voltage. It might "warble" at ~5v, but it will stop higher voltages dead in their tracks.

@SDsolar below 7V? Well, according to the datasheet on Vin pin you should give voltages ABOVE 7V (otherwise the regulator cannot work properly) or give it exactly 5V on the +5V pin (bypassing the regulator). No other ways...

@dandavis LM7805 has a dropout voltage of around 2V, so if you power it with 5V you will get 3V on its output. The AMS1117 (not AMS117) has a lower dropout, but it's still greater than 1V, thus giving you at most 4V

Below 7v for the normal barrel-style plug which goes through the regulator.     Vin goes directly into the circuit and can handle 12 Volts.

@frarugi87: i measured 4.4v from 5v on an AMS, and 3.76 from a LM, but good point. A cheap 5.1v zener would be simpler, ex: http://electronics.stackexchange.com/questions/81429/why-do-we-connect-a-resistor-before-a-zener-diode

@dandavis yes, the dropout varies with the current. Maybe the datasheet data are trimmed for a 1A, I forgot to check. Anyway the zener solution has the problem of the resistor: if you want it to protect up to 6V (and no more than 6V) and a 1W zener, you can use a resistor to let at most 150mA in the zener. If the circuit draws 200mA, this means that the resistor is about 2.5 Ohm. When you give it 5V, the zener will turn off, and the 200mA will cause a 0.5V drop on the resistor, thus giving you 4.5V...

A polyfuse will limit current not voltage.
There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.
You should NOT need any of this if you use a reasonable power supply.

What is the recommended way of adding reverse polarity protection to surge protection in such a circuit ?

Raspberry Pi is different from Arduino.  The specs say to never put in more than about 5.5 Volts.  Since power supplies are widely available for Rpi boards, it should be easy to find one that is regulated enough.  The Pi itself doesn't draw all that much power, but the more USB devices you plug into it will increase the current requirements.  Total current for all 4 USB ports should not exceed 1.5 Amps.  If you are running an external hard drive it is best if it has its own power supply.

The easiest way to ensure polarity protection is with a full-wave rectifier.  4 diodes.  The only negative is that each diode would have some voltage drop.  So in my case I use approved power supplies that can only be plugged in one way.  But if you want to build a full-wave rectifier, here is what they look like:  https://www.google.com/search?q=full+wave+rectifier&newwindow=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi4jdmimLLSAhWHCBoKHfCCChMQ_AUICCgB&biw=1211&bih=548#imgrc=yidbnb0eK_wGWM:

@SDsolar. Thanks. I don't want to incur a voltage drop because the USB supply should already be 5volts, regulated, with the correct polarity and the circuit design will assume that, but also protect itself in the case that it isn't the case, or there is a voltage spike (lightning strike in the electricity distribution network etc.). I guess I use the series polyfuse, the tvs diode across the supply after the polyfuse and say a 1N4007 normal diode reversed also across the supply after the poly fuse.

You hit the nail on the head.  That's why I just use regulated power supplies with the micro-USB plug that enforces polarity physically.

@6v6gt - this is really another question entirely (this question is about surge protection). Please post it as a new question. No-one will find your question (and any answers under it) as comments about surge protection.

@NickGammon . You're right. I've put the question here: http://electronics.stackexchange.com/questions/289649/circuit-protection-incorporating-a-transient-voltage-supressor-and-polyfuse

I second Milliways answer:

You should NOT need any of this if you use a reasonable power supply.

Anyway, if you really have a crappy power supply you can use one of the modules you find on ebay (for instance this is the first result I came across). Be sure to look for "buck boost" modules (step up/down), because they can both raise and lower the voltage.
This will do the job your power supply is not able to do, so to give you a stable voltage. You can then also vary the voltage without worrying (they usually are able to handle 4V (e.g. lithium batteries), 7.2V (e.g. 2 lithium batteries), 12V, ...
If you want also reverse protection, I suggest you to simply put a diode in series with THE INPUT (anode on the positive of your power supply, cathode on the IN+ terminal of this regulator). This way the voltage drop will be absorbed by the regulator. You can use a cheap 1N4007 or even a Schottky diode (which have less drop -> better power consumption).
I discourage you from using a full wave rectifier, since the diodes on the ground will change the ground reference (and so if you connect something else you may experience problems).
You can find a lot of "buck/boost" modules out there, just check that the input and output voltages and currents are suitable for your project.
But again, unless your power supply is really crappy you won't need this. If you just need an inversion protection, you can also use a circuit I found on a PC : put a fuse (they used a real fuse, you can use a polyfuse) between the power positive input and the circuit positive, then add a diode with the anode to ground and the cathode to the circuit positive. If you attach it correctly the diode will be reverse polarized and the circuit will work correctly, if you attach it in reverse the diode will conduct and so will create a large current which will trip the fuse.


text:
Stop Led's from blinking
My code:
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   }
 if (buttonState == HIGH){
   digitalWrite(led, LOW);}
  }

The last line of code:
if (buttonState == HIGH){
   digitalWrite(led, LOW);}

Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?
EDITED for clarification:
The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.

What do you want to happen? Press once to start blinking and again to stop blinking? Blink while the button is pressed? Something else?

Yes the first thing you said.  Press once to start blinking and again to stop blinking

can i know how to have a button to trigger blinking of led and another button is to stop the blinking ?

It makes sense to make switch-testing fairly independent of blink-control.  That's done in the following code, which turns blinking on or off each time a button is pressed.  With this code, between button presses the LED either is off or it blinks at about a 2 Hz rate.
enum { LED=13, ButtonPin=2, BounceMS=50, BlinkMS=256 };
unsigned long buttonAt;
bool blinky, bouncy, buttonState;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(ButtonPin, INPUT_PULLUP);
  blinky = bouncy = buttonState = false;
  buttonAt = millis();
}

void loop() {
  // Detect button changes
  if (bouncy) {
    if (millis() - buttonAt > BounceMS)
      bouncy = false;       // End of debounce period
  } else {
    if (digitalRead(ButtonPin) != buttonState) {
      buttonState = digitalRead(ButtonPin);
      buttonAt = millis();
      bouncy = true;        // Start debounce period
      if (buttonState) {    // Was button just pressed?
        blinky = !blinky;   // Toggle blink-state
      }
    }
  }
  // Control light-blinking
  if (blinky) {
    // Turn LED on for BlinkMS ms, then off for same
    digitalWrite(LED, (millis() - buttonAt)%(2*BlinkMS) < BlinkMS);
  } else {
    digitalWrite(LED, LOW);
  }
}

EDITED
The Arduino loop() function makes the use of a while loop redundant in this case. Even worse: the way you've implemented that while loop prevents buttonState from being updated, thus getting stuck in the loop.
What you actually need is to use timers to blink the LED, and a 2-state machine driven by HIGH to LOW button transitions.
Try this instead:
#include "Timer.h"

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
const int led = 13;
const int buttonPin = 2;

// declare state variables as global
bool buttonState = LOW;
bool buttonState_prev = LOW;
bool toggleBlinking;
bool blinkState;

// declare a Timer object so blinking can be done without loosing button presses
Timer timer_b;
int blink_id;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // initial state: toggle led each 1000 ms
  blink_id = timer_b.oscillate(led, 1000, HIGH);
  blinkState = true;
  toggleBlinking = false;
}

// the loop routine runs over and over again forever:
void loop() {
  // Update the timer (required)
  timer_b.update();

  // check if button has been pressed (HIGH to LOW),
  // then debounce it and raise toggle flag
  buttonState = digitalRead(buttonPin);
  if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
    // simple button debounce (confirm press after some ms)
    delay (50);
    buttonState = digitalRead(buttonPin);
    if (buttonState != buttonState_prev) toggleBlinking = true;
  }

  // keep current LED state unless the button has been pushed
  switch (blinkState) {
    case true:
      // if button has been pushed, stop blinking and change LED state
      if (toggleBlinking == true) {
        timer_b.stop (blink_id);
        blinkState = false;
      }
      break;
    case false:
      digitalWrite(led, LOW);
      // if button has been pushed, start blinking and change LED state
      if (toggleBlinking == true) {
        blink_id = timer_b.oscillate(led, 1000, HIGH);
        blinkState = true;
      }
      break;
  }

  buttonState_prev = buttonState;
  toggleBlinking = false;
}

NOTE: You'll need to install the Timer.h library. I'VE TESTED MY CODE AND IT WORKS.

That's not a deadlock, but otherwise good :-)

You're right, thanks. I'll edit the answer.

Your code just makes the Led's blink once... I understand what you are trying to do here but I wanted so that the led's blink continuously once the button is pressed. But, when the button is pressed again, they stop blinking. Like I said, This makes the led's only blink once then stop blinking without having the button pressed...

OK, I'll see your using a pull-up. I'll check it.

Yes sorry, I should've given more details :/

@EnricBlanco any updates? sorry I've just been on this for quiet a while and need some explanation about the problems..

I've edited the answer, take a look.

As the OP explained in a comment, what he is trying to achieve is to have a button alternate between blink and off, not having the button to be pressed to shut down the led.
This can be done in this way:
bool prevButtonState;
bool ledBlinking;

void loop()
{
    bool buttonState = digitalRead(buttonPin);

    if (prevButtonState && !buttonState)
    { // Pressing edge: there is a transition between high and low
        ledBlinking = !ledBlinking;
    }
    prevButtonState = buttonState;

    if (ledBlinking)
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second
    }
    else
    {
        digitalWrite(led, LOW);
    }
}

This, however, leads to a very long time between successive checks of the button (since there is a 2s delay between cycles). You can solve this using the millis function:
bool prevButtonState;
bool ledBlinking;
unsigned long prevMillis;

void loop()
{
    bool buttonState = digitalRead(buttonPin);

    if (prevButtonState && !buttonState)
    { // Pressing edge: there is a transition between high and low
        ledBlinking = !ledBlinking;

        prevMillis = millis() - 1000; // Force a check
    }
    prevButtonState = buttonState;

    if (ledBlinking)
    {
        if ((millis() - prevMillis) >= 1000)
        {
            prevMillis += 1000;
            digitalWrite(led, !digitalRead(led));
        }
    }
    else
    {
        digitalWrite(led, LOW);
    }
}

Next there is the debounce problem, but this becomes OT. Suggestion: use the Bounce2 library to manage the button if you experience bounces

No, I do want to use the button to swith the led off.. Like a switch and a light bulb.. the only difference is that the lighbulb blinks.

In this comment you say that you want one push -> led blink, another push -> led off. This is what my code does. Your code is keep pressed -> led blink, leave unpressed -> led off

while (buttonState == LOW)

gets you trapped in an endless loop, once buttonState == LOW.
You have to poll buttonState inside this loop if you ever want to get out of it.
However this is not enough for your purpose. What you really need is a (boolean) variable - let's name it blinking, for instance - which changes its value each time you see a falling edge on buttonState.
Then check this variable's value in an if/else clause like this:
if (blinking == true)
{
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
}
else
{
   digitalWrite(led, LOW);}
}

But with this you will soon face the next problem: The polling speed for your button is very low, because of the very long delays, which keep you about 2 seconds inside the if clause.
Try setting up the blink cycle using a PWM, as described here
Then use the if clause above to set the PWM duty to 50%, and the else clause to set it to 0%.

So you want me to put If (buttonState == HIGH) inside the while loop?

@Utsav That won't help. The buttonState doesn't reflects current state of pin. The digitalRead does.

@KIIV so I put another bool buttonState = digitalRead(buttonPin); inside the while loop and then I also cut and pasted the If statement inside the while loop. They still do not produce the outcome :/ i'm sorry I couldn't really implement what you wanted...

@Utsav no, you want to update buttonState, not to create new one and shadow the other one from the outside of scope.

When I create this new bool variable called 'blinking', do I set the variable with a number? like: bool blinking = 0; or do something else? I am quite confused..

This answer is somewhat misleading. Polling buttonState inside a while(buttonState==LOW) loop doesn't achieve anything.

try this:
if (key_pressed()) digitalWrite(LED_PIN, (digitalRead(LED_PIN)==ON)?OFF:ON);
else digitalWrite(LED_PIN, OFF);

define ON/OFF based on your led connection.
Edit.
If you want the button too change the mode of led blinking, try this.
    if (btn_pressed())                  //if btn falling edge detected
        btn_status ^= 1;                //flip the last bit. btn_status += 1; works as well
    if (btn_status & 0x01) led1_flp();  //flip led1
    else led1_off();                    //otherwise, turn off led1

    //flip led2
    IO_FLP(LED_PORT, LED2);

the logic is fairly simple: if the button is pressed (active low), toggle btn_status. if btn_status is 1, blink the led1.
basically, press the button, led starts to blink; press the button the 2nd time, led stops to blink;
led2 is always blinking, to show concurrency of the code.
here it goes in action.

the code is written for a pic but basically runs on any mcu.


text:
Increase IR transmitter directivity and range
I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:

So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. I want to increase this to at least 5 meters. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong):
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.

Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

Any help is appreciated, thank you.

Why would all the devices turn on ? Different devices and functions have different 'codes'

I'd start by using a smaller value resistor. You can drive those leds pretty hard, since the are only on for short periods (38000 pulses per second). IR bouncing of walls is normal. Had to prevent this. My TV remote works better if I aim at the ceiling.

I am using same NEC code for all devices, this is only a part of the project the devices actually communicate through WiFi, IR is used to select device. It requires the same code to be used.

@Gerben I am using 330 ohm resistor, I have a couple of 100 ohm ones I'll try that. Can't I just remove the resistor and short the LED and collector of transistor since it is not directly connected to Arduino I/O pin?. I had tested in different rooms and found out that bouncing off walls happens more in rooms with less furniture. Thank you.

Not using a resistor is a bad idea. If you want an even lower value, you could use two 100ohm resistors in parallel. By the way, you really should put a resistor between the Arduino pin and the base of the transistor!!!

Okay I'll add in a resistor between base and I/O pin.

Even if you try to mask the sensor you're still going to get problems with the IR reflecting off objects and maybe even people, I suggest you need to rethink your control/selection mechanism.

you will need discrete IR emitters, aka "blasters". you can find some with small suction cups that seal around the devices IR sensor, ensuring only the correct device receives the code.

Use a red laser instead of IR emitting diode.

Yes thinking of using it

Can i have the source code please Kind regards

more detailed question specification is in this website？ thx ！
https://electronics.stackexchange.com/questions/371867/what-is-the-relationship-between-emitter-intensity-ie-with-the-forward-current-i

The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).
So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.
But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.
The back side (flat one) should not be sensitive.

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).
But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".
You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).
In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.
First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).
But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

TLDR: I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.
Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.

Thank you so much. This cleared many doubts I had. If IR is built like that then is there an alternative that could provide directivity and range like a low powered laser transmitter and receiver which I could use with arduino?

Yes, for example laser transmiter and photoresistor like here: http://www.instructables.com/id/Arduino-Laser-Tripwire/ (or basically any photo-something - photo-diode, photo-transistor, photo-resistor, even normal LED can be used as receiver ...). But you would need to develope some "protocol" if you want more than just switch it on while you are shining there. And you have to cope with daylight too, so put the receiver in some kind of hole/bore to be not so much affected by normal light. And you would still need to go to modulated PWM, as to filter out other light sources (like in IR).

Just google Ardduino laser :) Or arduino light receiver or arduino transmitter - tons of examples everywhere :)


text:
PCF8563 does not remember time when restarting Arduino Uno?
I'm trying to use the following RTC module (PCF8563) with Arduino Uno.
I am using this library to set/get time and date from PCF8563. However, whenever I shut down the Arduino, the time/date is lost! Even though, as you can see in the picture, the module is equipped with a 3V battery to keep running when Arduino is unplugged.
Any help would be highly appreciated!

Did you try to put the jumper in the “BAT” position?

[SOLVED]
The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to Edgar Bonet


text:
FFT library for Arduino 101?
I am currently trying to get a real-time FFT working for a project on an Arduino 101 which uses the Intel Curie chip. All the FFT libraries (if any) seem to be for the Arduino Uno and architecture dependent (most of them have assembly stuff for optimization).
I was wondering if there is any robust, up do date and most importantly working (with the latest Arduino 101) library. I have tried the PlainFFT library which I read might be compatible with the Arduino 101 (https://forum.arduino.cc/index.php?topic=409791.0).
However this library seems to be out of date, using old extensions of sketch files and old library names in its code (I could not get it to work). Alternatively I wanted to try and tailor a pure C code such as https://github.com/jtfell/c-fft, which seems to have its own Makefile for compilation (this one uses a C99 compiler). I could compile and use this code on a Linux terminal but I am not sure how to go on about making it run inside an Arduino sketch.

I used lightweighted KissFFT (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.

So when I get this library from let's say https://sourceforge.net/projects/kissfft/?source=typ_redirect how do I then use it in an Arduino sketch? Just putting it in the libraries folder and #include it in the sketch (.ino) will not work. What adjustments will I need to make?


text:
Advice needed, commercializing an Arduino Due project
We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!

What kind of project?

Depends on the kind of project you are doing. If the Due is just minor part (say you are producind 3D printer) and you plan to do like tens of the devices, I would consider using it, but probably would solder it in for good contact reliability. Maybe put it inside a box too, so nothing can short anything on the board. (And then the Due is not in plain sight).
If it is mainly Due with some sensors around and you want to sell thousands of them, then I would make extra PCB for it, containing everything what is possible on one board. (Like @Majenko suggested.)
Anyway I made a lot of PCB in my kitchen (yes, literally) for my "Arduino" projects, even when I made only 1 or 2 devices just for me. Every of them worked just fine. It is not so dificult to do if you are not pushing some limits too hard. Even Due small chip can be soldered by hands and with some basic tools on your eating table.
But if you lack the skills, hiring contractor (or found company, which does that) may be cheaper in terms of your time and number of devices destroyed before getting the skill and customers complaining about devices broken after short time use.

There's two routes you can take.
First route:

Get the Due schematics.
Remove the parts you don't need.
Add to it the new components for your product.
Lay out the PCB design.
Get the PCB manufactured.
Solder all the components on.
Test it and go back to step 2/3 as required.

Second route:

Hire a contractor that knows the SAM3X and can do it all for you.


text:
Weird probled with TFT LCD screen and DHT22 sensor
I'm doing a research project that uses three sensors (DHT22, HTU21D and TMP102) and two screens (a normal 16x2 LCD, and a TFT).
I connected all the sensors and the LCD in my Arduino Uno and everything works fine. However, when I connect the TFT, the TFT simply freezes and does nothing. I ran the example Arduino sketches for TFT and it works fine. I also did a bit of debugging and found that if I don't invoke the DHT22 sensor reading functions (i.e., dht.readTemperature()), the TFT screen works fine.
I also triple-checked the wiring and it doesn't seems that something is wrong.
Any ideas why this behaviour occurs? Thanks.

sounds like you need to configure the DHT to use a different GPIO

Similar problem have someone else here too: http://arduino.stackexchange.com/questions/34987/ultrasonic-sensors-with-12v-motors-will-not-work-adruino - there was some shared pins, so each device worked separately, but not both togeher. Changing the pins (GPIO) solved that.

Thank you, both. The problem was shared pins between the components. Now, I must figure out how to extend the outputs pins on Arduino!

To get more pins on an Arduino, look at the MCP23008 port expander.


text:
CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision?
To my knowledge the SeeedStudio CAN-Bus shield utilizes D13, and so does the SD-card module I use. And also Arduino Uno's LED_BUILTIN is 13. Am I in danger of some sort of collision here?
I have read this question, but that one describes situation where both modules are on a single shield.
Why I am alerted: I can perform following sequence: turn the LED on, open file, write, close file, turn the LED off, no apparent problem here. But when I connect my CAN-Bus shield to merely read messages (i.e. no sending data to the shield, not on purpose) my car behaves funny as if I still somehow managed to send some rogue bytes to the shield. (Right side windows and mirror are dead, infotainment display shows dead splash screen, dashboard complains about "engine malfunction" and airbags...)
I wonder if by writing to the SD-card and possibly turning the LED on I didn't send some bytes to the shield. Do I need to somehow Select Slave?

The actual cause of the car going crazy was that I did not have GND connected

Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

You could stop using the LED on D13?
Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.


text:
I2C Wire.write function doesn't seem to work
Using the simplest code possible to test the library:
#include <Wire.h>

void setup()
{

  Wire.begin(); // join i2c bus

  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                              // device address is specified in datasheet

  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte

  Wire.endTransmission();     // stop transmitting
}

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

Are you sure you've got ACK? The beginTransmission expects unshifted device address (it might need address 22 instead of 44). (It's the address without R/W bit)

I'm trying it without a device attached to check the data first. Does the ACK need to be present in order to send the remaining data? That is a NACK on the 9th bit.

Without an ACK from a device at that address the transfer will abort. It's not like SPI - it's a SEND-ACK-SEND-ACK-SEND-ACK protocol.

OK, I figured out what was going on...
An example program that I downloaded to test the hardware was sending a "self address" command to the chip, which was causing the address to get set to 0x03 and I didn't notice this. This new address stays in memory. So, when I went back to test the library code, I was sending 0x00 (default from factory) instead of the new address (0x03). The NACK after the address byte should have been a clue, but hey, live and learn.
Thanks for all the responses. Hopefully my pain will help someone else.

According to the captured communication NACK was received (confirmed in comments) and according to the Wire library twi_stop will be called (and sent) in this fault scenario.
case TW_MT_SLA_NACK:  // address sent, nack received
  twi_error = TW_MT_SLA_NACK;
  twi_stop();
  break;

You can also test the return code from Wire.endTransmission(). https://www.arduino.cc/en/Reference/WireEndTransmission

This is good information. I'll try putting the device on the bus and see if that makes a difference. Thank you!

It looks like you have code for an I2C master. Sending to a slave involves sending the slave address, and waiting for an ACK from the slave (that is, the addressed slave pulls the data bus low).
You can see that in a graphic from my page about I2C:

At the 100 µs mark you can see that the slave pulls SDA low, which is an ACK. Thus the master knows that the addressed slave exists. Without that, the slave is not there, and there is no point in sending any further data.


text:
Open video file if sensor reaches certain threshold value
I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!

What I'm thinking is that you could make a conditional statement. Below is a little a bit of pseudo code on how to possibly open said video from an SD card because there's no way Arduino would be able to store a video on it's own, let alone play good quality videos:
int dangerLevel = 500 (or however the shield reads the smoke level)

int smokeDetectorPin = A0

setup:

smokeDetected = analogRead(smokeDetectorPin)

loop:

if smokeDetected >= dangerLevel:

open video from SD card directory or computer.

So in order to get a "video" from the SD card, you should check this website. Like I mentioned before, this is really primitive and it's probably not what you're looking for.
I found something very interest about the Arduino that I never knew you could do before and using composite display from a TV. Interesting and you can find that info here.
And lastly, to get a video from your computer or laptop, there's really no easy way. However, I did find two solutions that might be able to do this. First of all, and this may sound ironic since we're on an Arduino Stackexchange, you could use a Raspberry Pi (and this is the easily solution I can think of) though I believe your instructor prefers if you use the Arduino instead. Second, and this took me forever to find on the internet, you could use a third party software called "Gobetwino" and you can check out what that does here. I saw on YouTube video of a quick little demonstration of what it does. When the button is pressed, the video is played. That's conditional and you can do the same thing but for the smoke detector.

You're welcome :) it took me a really long time to look all of this up and I actually learned a lot of stuff myself.


text:
Change conditioning in real time
I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:
int solenoidPin = 4; //connected to Digital 4
int moisturePin = A0; //connected to Analog A0

void setup() {
  Serial.begin(9600);
  pinMode(solenoidPin, OUTPUT);
}
void loop() {
  int val;
  moisture = analogRead(moisturePin); //connect sensor to Analog A0
  Serial.println(val); //print the value to serial port
  delay(1000); //wait 1 second for next reading

  if (moisture <= 350) //if moisture is less than reading 350 {
  digitalWrite(solenoidPin, HIGH); //switch solenoid ON
  delay(600000) //water for ten minutes
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
}

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the if (moisture <= 350) while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

  if (moisture <= 350) //if moisture is less than reading 350 {

That is wrong, because you have the brace { after the comment. You need it before the comment, eg.
 if (moisture <= 350) { //if moisture is less than reading 350

Or preferably in my opinion:
if (moisture <= 350) //if moisture is less than reading 350
  {

I'm just asking if it's possible to change the if (moisture <= 350)

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace 350 in the code. You could use a simple LCD or LED display to show what the current reading is.

delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read How to do multiple things at once which shows how you can keep doing other things, while waiting for time to elapse.

Thanks for catching that small { fluke. Now, back to the the change in the condition. You mentioned a potentiometer. Where exactly in the circuit would that go?

Actually, come to think of it, the potentiometer would probably be series with the moisture sensor. Please correct me if I'm wrong.

That could be fiddly to get right. Normally you have a potentiometer with the 2 end pins connected to Gnd and +5V and the middle (wiper) to an analog input. It acts as a voltage divider and then you can read a number in the range 0 to 1023 which indicates how far you have turned the knob.

There's another "fluke" here: delay(600000) //water for ten minutes - there should be a semicolon after the right parenthesis.


text:
My Digispark board won't show up in Ports tab in Arduino IDE (OSX)
I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:
"Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.
Atmel 1624 tiny85

I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".
Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.
See:
http://digistump.com/wiki/digispark/tutorials/connecting
You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.


text:
Using SlickEdit to compile Arduino files
I would like to compile my Arduino sketches in SlickEdit.  I have turned on the verbose compile output in the standard IDE and I can see the compile and switches, but it doesn't appear that there is a Makefile in use.  I don't see the "Entering" and "Leaving" messages that I associate with Make anyway.  Is using a third party tool to control the build an Arduino no-no?  Has anyone used Make to build Arduino?

Can you elaborate please? What is SlickEdit? (link). I don't see the "Entering" and "Leaving" messages that I associate with Make anyway. - make doesn't have such messages per se. Is using a third party tool to control the build an Arduino no-no? - no, a lot of people do that.

Arduino doesn't use Make. In the settings there is an option to use an external editor. If you enable this you can write code in SlickEdit, but you'd have to use the Arduino IDE for compiling and uploading.

Try to see if you can live with using slickedit as the externally editor. I havent used slickedit as a project mgmt but have done so with si and pn. Both are fairly straight forward but thee setup process is fairly manual. On the automation from sublime text can be used as a full blown Arduino environment so you may check that out as a possible alternative.

Many people use Make to compile Arduino software - but the Arduino IDE doesn't. There are many projects online to implement the build procedure using Make. Try googling for them.

The first two lines of the arduino verbose output show you how to call the arduino builder api. It will then do the rest.

@VisualMicro, you should add this as the answer.  After creating two tools(one for each line) in SE, a dump-prefs and a Build, I get a binary.  Adding a third tool called Download, lets me perform all basic operations in SE that I do in the IDE.


text:
Why is the piezo buzzer not making any sound?
My ciruit:

My code:
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the tone(12,260); that I added?

General advice: get one thing working at a time. I don't think your button/flash code does what you want, even before you add the buzzer.

@MarkSmith Is this reference towards my previous question?

No, to this one.

Well my whole point of this project is to implement an alarm system. currently it works with the button acting as the alarm switch, led's as the lights and piezo for the sound. From the answer below, I have done this, however I couldn't understand any of the answers from my previous question (http://arduino.stackexchange.com/questions/35177/stop-leds-from-blinking) that allowed me to disable the alarm. That is really the only problem I am facing currently.

@Utsav Some issues will disappear if you stop using buttonState and start using digitalRead everywhere instead. You need current state of pin, not the state loaded looooong time ago. The buttonState won't magically change a state without any assigment into it!

Really the important thing is to understand what you're doing. You had five answers to your previous question -- you can ask for more explanations if things don't make sense. Using code you don't understand will get you into trouble sooner or later.

@MarkSmith the reason why I dont understand the answers you guys provide is because you think I understand everything and answer questions in a very complex way. You guys change the whole code and I don't understand some of the new "words" that I witness. Trust me, I appreciate all the work and I do want to learn but this is not a homework site so I can't ask small questions and expect a reply. The way I wrote the code above makes complete sense, but when you fiddle with it too much, I cannot understand. Other than that, I thank you and other members of this site who have helped me.

Both the code and the circuit have problems.
In the code:
• If the while (buttonState == LOW) loop is ever entered, it will never be left, because buttonState, the controlling variable, does not change within the loop.
The simplest fix is to remove the line bool buttonState = digitalRead(buttonPin); and replace while (buttonState == LOW) with while (!digitalRead(buttonPin)), which says to loop while digitalRead(buttonPin) is not true; ie, while it is false, or low.
• The empty braces, { } at the end of the while loop are superfluous and should be deleted.
In the circuit diagram:
• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, tone(12,260); tells the Arduino to use pin 12 for tone output.
To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.
• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


text:
I2C between 2 or more Arduino boards
HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is :
MASTER with LCD I2C , RTC1037
SLAVE some sensor not I2C
I allready put 2 pullup resistor 10Kohm on SDA and SCL
I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

Define "shut down". Also, define "stop working"...

switch off :) sorry for my english

"switch off" as in remove the power completely? Then you may need to isolate the I2C bus from it as well.

Yep, remove power completely,how to isolate the i2c bus? 2 relay 1 for sda 1 for scl when i need to switch off ?

Relay is kind of overkill and power hungry. MOSFETS (as Adafruit use in the I2C level shifters) are a better choice. See Adafruit's app note here: https://cdn-shop.adafruit.com/datasheets/an97055.pdf - ignore the level shifting as you would have both sides the same voltage, but section 2.3 is of interest. Your slave would be the 3.3V side of the shifter (but at 5V not 3.3V). Paragraph 2.3.4 tells you what you need to know for this application.

tnks a lot for your reply

You need to isolate the slave device from the I2C bus since it is causing interference with the signals.
Adafruit have published a good application note about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

2.3.4 Isolation of the powered-down “Lower voltage” section.
An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
  VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
  below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
  noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
  stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
  may have the same value, e.g. both 3.3V or both 5V.


text:
conflicts with LiquidCrystal.h and SoftwareSerial.h library?
Simply put, if I include and initialize both libraries, the LCD displays junk. If I don't include and use the software serial lib, the LCD displays correctly.
BTW, there are no devices physically connected to the software serial defined pins.....
Yes, I've verified that there are no pin definition conflicts.
The code is large (> 1200 lines, with multiple #ifdef statements for conditional target configurations) so I won't include it unless someone wants to see it.
So, does anyone know of a conflict with these 2 (current) libraries?

No, I can't think that there would be a conflict. It must be how you're using them.

I suggest making a MCVE to see if the problem exists without the rest of your code.

I simply commented out ALL the lines that setup or use the software serial, leaving all the other code intact, and the LCD then works fine.

The only thing the software serial does is read an hc-12 radio that's not even installed at this point.....

So make an MCVE that contains JUST lines for the LCD and the serial and see if it breaks.

The basic code wasn't the problem, but these statements were: radioSerial.print(F("AT+C001\r\n")); // set to channel 1

I 'borrowed' that code from some examples, not familiar with the code itself, will try something else.......

I removed the F( stuff from the code(not sure what it does) and the LCD works as expected......just what is that construct that I borrowed from the examples??

I found out what that construct does, and for the life of me I see no reason that it caused issues with the LCD.....my code doesn't use and special constructs or anything that would leave me to believe that there's a memory size issue......Now I can actually debug the code for serial communications for the radio module.


text:
Arduino + motor driver (L293D) power consumption
Please help me on this question.
Original question :
My chip consists of 1 arduino nano and  3 L293D motor driver. This chip is for controlling motors and other equipments. My question is about how to calculate power consumption of my chip. I searched for about voltage settings of arduiono nano and L293D motor driver, but there are many phusical thinks that i cannot understand. How many hours 2000 mah battery enough for.
Note :
Motors and other equipments will have own power supply. That i say it is just for Arduino Nano, Bluetoot adapter for arduino (HC-05) and 3 motor driver (L293D).

If you are powering all modules from the bench power supply, note down the voltage and the current. Product of the two will give you power consumption.

It also depends on the voltage provides by power bank.

I cannot got power settings of L293D. I read technical specification but cannot understand

Sorry, I misread your question as you already have it connected and working, correct me if i am wrong. you are only looking for the battery life time estimation.

are you driving three motor with one L293D or you are using 3 L293D motor driver ICs?

Yes i connect via power adapter. And it works fine. But it should be with battery not adapter. And I want to calculate which kind of battery i should use. How many Mah  battery is enoght for 3(for examle .. maybe 5 hours )  hours.
Note : I use 3 L293D and can control 6 motors with it

how much current do you need to use to drive the motor? the current to the motor is supplied by the L293D device and hence, it matters. in short, share the motor specs.

About motor specs i cannot say exactly. Bu i can say this is formula 1 car something like this with 4 AA battery

Please don't cross-post the same question to multiple stacks.  StackExchange policy is against cross-posting.

Did you even read the question? This is 1% about arduino  and 99% about general electonics... this question does not belong to arduino stack, why do you moderators keep moving everything with "Arduino" written on it?

To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.
On Texas Instruments datasheet, we have:

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.
Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.
Example:
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).
The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.
To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.
As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.
If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.
Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.
Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.


text:
Help with struct variable
I made a struct like this:
typedef struct {
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
} buttons;

and a variable like this:
button test[1] =
{
  {{0,0,0},{0,0,100,100},"getSomething",setSomething}
}

In loop() I call test[i].color, test[i].position normally.
Problems start when I want to execute a function.
I made two attemps, one with string and one with a function statement. With the string I have no problems using a strcmp() but it's not what I want.
I need to know how I can store 2 different functions in the struct and how I can execute.
Thanks in advance!

Could you post what you've tried, please, and in what way it didn't work?

Jot answers is what I needed!

What mark was saying is if you post more code people may be able to understand what you are trying to say better and help you faster.
I thought you wanted to store two function pointer in the one struct by what your text says.

The typedef is no longer needed, using the 'struct' with a name declares the type.
// Arduino Uno

struct buttons
{
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
};

// Declare the functions here, or use prototyping
void func1();
void func2();

buttons test[] =
{
  { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
  { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
};

void setup()
{
  Serial.begin(9600);
  Serial.println("Calling the functions:");

  test[0].fn();
  test[1].fn();
}

void loop()
{
}

void func1()
{
  Serial.println("func1");
}

void func2()
{
  Serial.println("func2");
}

Not needed because what? Because it is C++?