text:
After moving project from Arduino Mega to Due, pushbuttons now erratically toggle multiple buttons
I've had a project running successfully for months on an Arduino Mega, and today I tried to swap the Mega for a Due to increase the speed. After making the change, the entire project is working successfully except for a strange problem with the pushbuttons.
I have 5 momentary pushbuttons that toggle different controls (they simply send a wireless signal to toggle different AC outlets). After moving the project to the Due, when 1 button is pressed, it ends up toggling 2 other buttons at the same time.
Originally I was using the internal pullups to detect when the buttons were low, but also I've tried connecting them to the Due's 3.3v to detect when they're high, and both times I experienced the exact same behavior.
Is there any reason why there would be this difference in pushbutton-reading behavior between the Mega and the Due? Could it be that the Due is more sensitive to noise? How could I fix this?
The wires connecting to the pushbuttons run about 8 feet. I never had a problem with this setup while running the sketch on the Mega.
Below is the relevant code that detects button presses:
#include <Wire.h>
#include <SPI.h>
#include <Ethernet.h>
#include <RCSwitch.h>
#include <Servo.h>
#include <Event.h>
#include <Timer.h>
#include <dht.h>
#include "RTClib.h"

const byte nl1ButtonPin = 40, nl2ButtonPin = 42, nl3ButtonPin = 44,  pumpButtonPin = 5, irButtonPin = 27,

unsigned long buttonPressTime1, buttonPressTime2, buttonPressTime3, buttonPressTime4, buttonPressTime5;  // when the switch last changed state

byte oldButtonState1 = HIGH, oldButtonState2 = HIGH, oldButtonState3 = HIGH, oldButtonState4 = HIGH, oldButtonState5 = HIGH;

const unsigned long debounceTime = 100;

void setup() {
  pinMode(nl1ButtonPin, INPUT_PULLUP); pinMode(nl2ButtonPin, INPUT_PULLUP); pinMode(nl3ButtonPin, INPUT_PULLUP); pinMode(pumpButtonPin, INPUT_PULLUP); pinMode(irButtonPin, INPUT_PULLUP);
}

void loop() {
 byte buttonState1 = digitalRead(nl1ButtonPin);
  if (buttonState1 != oldButtonState1)
  {
    if (millis () - buttonPressTime1 >= debounceTime)
    {
  buttonPressTime1 = millis ();  // when we closed the switch
  oldButtonState1 = buttonState1;  // remember for next time
  if (buttonState1 == LOW) {
    Serial.println("button1 LOW!");
    toggleLight1();
   }
 }
}

   byte buttonState2 = digitalRead(nl2ButtonPin);
  if (buttonState2 != oldButtonState2)
  {
    if (millis () - buttonPressTime2 >= debounceTime)
    {
      buttonPressTime2 = millis ();  // when we closed the switch
      oldButtonState2 = buttonState2;  // remember for next time
      if (buttonState2 == LOW) {
        Serial.println("button2 LOW!");
        toggleLight2();
      }
    }
  }

byte buttonState3 = digitalRead(nl3ButtonPin);
if (buttonState3 != oldButtonState3)
{
  if (millis () - buttonPressTime3 >= debounceTime)
  {
    buttonPressTime3 = millis ();  // when we closed the switch
    oldButtonState3 = buttonState3;  // remember for next time
    if (buttonState3 == LOW) {
      Serial.println("button3 LOW!");
      toggleLight3();
    }
  }
}

byte buttonState4 = digitalRead(pumpButtonPin);
if (buttonState4 != oldButtonState4)
{
  if (millis () - buttonPressTime4 >= debounceTime)
  {
    buttonPressTime4 = millis ();  // when we closed the switch
    oldButtonState4 = buttonState4;  // remember for next time
    if (buttonState4 == LOW) {
      Serial.println("button4 LOW!");
      togglePump();
    }
  }
}

byte buttonState5 = digitalRead(irButtonPin);
if (buttonState5 != oldButtonState5)
{
  if (millis () - buttonPressTime5 >= debounceTime)
  {
    buttonPressTime5 = millis ();  // when we closed the switch
    oldButtonState5 = buttonState5;  // remember for next time
    if (buttonState5 == LOW) {
      Serial.println("button5 LOW!");
      toggleHeater();
    }
   }
  }
}

On the serial output, pressing one button shows 2 other buttons as low. So, for example, pressing button2 might show: "Button2 LOW!, Button4 LOW!, Button1 LOW!". There doesn't seem to be any clear patterns with which other 2 buttons get simultaneously pressed. Remember that this exact same code and hardware setup was working perfectly for months on the Mega, which makes me believe maybe it's something related to the Due (maybe 3.3v, maybe stronger PU resistors, etc).

You need a pull-up or a pull-down, depending on how the button are wired. Are you grounding them or connecting them to Vcc? Without that you will definitely get erratic results. See Switches tutorial.

I forgot to mention that I'm using the internal pullups. Also I've tried using a 20k resistor instead of the internal pullups, but got the same results. The switches aren't toggling randomly. The problem is that when any button is pressed, it ends up toggling the other switches as well. I love your tutorials BTW, and I got my debounce code from that specific tutorial.

Glad you like them. :) Can you post more (or all) of your code? I don't see 4 buttons being tested there, only one. You could also try a lower-value resistor (eg. 1k).

Try increasing debounceTime

Gerben: I've tried debounceTime of 1000ms, and I got the same result. NG: Is it proper to paste all 1050 lines of code? :) I just updated the post and added more code. There might be simple typos due to the transfer. Today I'll probably be experimenting with the wiring, and also (like NG said) with different resistor values. Maybe the difference could be due to the Due's stronger PU resistors? The Mega uses between 20-50k for the PUs, and the Due uses between 50-150k. I've already tried 20k though (without the internal PUs) and that didn't work.

I don't think this would cause the multiple button press issue you report, but you are not initialising your buttonPressTime variables before you first read them which may cause some issues.

The problem ended up to be a 5-way tact switch that for some reason wasn't working well with the Due. This same switch has worked perfectly for months with the same code and wiring on the Mega. Here is a link to the switch: http://tinyurl.com/plnbv8z. I had a 2nd brand new one on hand to test out, and it resulted in the same problem of causing multiple button presses on the Due. After switching to regular tact pushbuttons, everything worked fine. Does anyone know why a certain switch would work perfectly well with a Mega, but not on a Due? Any ideas on how to make the switch work?

After examining the switch more closely, I noticed small resistors on it. I tested them at 10k. Then I saw that the description of the item says that it includes pullup resistors so that the switch reads LOW when pressed. It says that the power leads can be reversed so that it reads HIGH when pressed. I've tried many different combinations after learning this, including not using the Due's internal pullups, but still have had no success. Either no switches work, or they are toggled nonstop, or 1 switch toggles all the others. Do you think it might work if I remove those on-board resistors?

I think I can explain this. You have set up a rather complex (and incorrectly wired) network of resistors. Your switch has pull-up resistors, clearly connected together, and then to the "+" pin. The other side of the switches would go to ground.

Note that I don't have anything connected to the VCC of the switch ...

Right, so your setup looks like this:

Now with no switch pressed they will all read high due to the Due's pull-up (which by the way is around 100 k compared to the Mega's 50 k.)
Now you press a switch. The naturally grounds that switch so it reads LOW. However it also pulls down neighbouring switches through the 10 k resistor network. So each switch now is in the middle of a voltage divider. There is 20 k going to ground and a couple of 100 k going to Vcc, like this:

This voltage divider would be enough for that pin to register as LOW, and indeed that would be repeated for each pin.
Adding your carefully calculated resistor between the "-" pin and ground is just changing the voltages a bit.
The correct solution is to connect the "+" pin to Vcc so that it acts as a proper pull-up. And get rid of that resistor in series with ground.

It probably worked on the Mega because of the different pull-up resistance when you activated the internal pull-up which would have changed the calculations for the voltage divider.
I've worked out what I think the voltages will be. Note that the supposedly open switches will actually have 1.1 V on them, which as far as I can tell from the datasheet is in the "undefined" territory between LOW (max 0.99 V) and HIGH (minimum 2.31 V).
Reasoning: You can effectively consider that the 4 open switches have 4 x 110 k between them and 3.3 V in parallel. In other words, 27.5 k. With a voltage divider now between that and the 10 k to ground, you have:
10 / (10 + 27.5) * 3.3 = 880 mV

So, there will be 880 mV on the common point (which is "+" on the board).
Now for each switch you have a voltage divider of:
10 / 110 * (3.3 - 0.880) = 220 mV

Add to that the 880 mV at the common point and we have:
0.88 + 0.22 = 1.10 V

Thanks , NG! That analysis is amazing. I'm glad you could confirm it was a complex and messy situation. Everything else worked fine with the board-change from Mega to Due, and in a few hours I had everything else working: servos, relays, RTC, sensors, wireless transmitters, etc. But this simple tact switch took me 2 days of debugging!

Do you see any scenario where those on-board pullup resistors might be useful while using an Arduino?

Sure, just use them as intended. After all, 100 k is pretty weak for a pull-up. Over a long cable run as you described (8 ft) they might be unreliable. Run an additional line for power and supply the pull-up through the board.

I finally got it working. The problem was with this 5-way tact switch being initially incompatible with the Due: http://www.ebay.com/itm/5-Channel-Way-Tactile-Switch-Breakout-Module-Converter-Adapter-Board-Arduino-/141745152805 . As you can see from the picture and the description on that page, the switch includes pullup resistors on the board. I measured those resistors at 10k Ohms. For some reason the switch worked perfectly fine with the Mega's pullup resistors, but didn't work with the Due's.

After much experimentation, I found that the switch will start working if I add a 14.7k resistor between the switch and ground. The Due's internal pullups still had to be activated, otherwise it seemed the switch was firing constantly. When I used a 10k resistor, the center button on the switch wasn't working. And when I used 20k and higher resistors, many of the buttons weren't working.
I posted this as an answer because the switch is finally working the way I want it to. But I'm still curious to know if anyone has a reason why there would be a necessity to have a 14.7k resistor on the ground of this switch in order to make it work with the Due. Note that I don't have anything connected to the VCC of the switch (though I have experimented with it before).

After I moved the switch from next to the board where I was experimenting with it, back to the end of an 8' long copper cable where it was supposed to be, the 14.7k ground-resistor trick stopped working. I ended up just removing all the on-board PU resistors, and then it worked perfectly, just like as if it was a collection of regular tact pusbutton switches.


text:
WiFi module ESP8266 + Arduino Uno
I'm trying to connect a WiFi module, ESP8266-01 to an Arduino Uno. But, as I've understood, this module will only work with 3.3 V. Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.
My questions are:

Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno?
For a simple server, would I need to use several voltage regulators (since there are quite many pins)?
Since Rx is the receiver, it would not need a voltage regulator because that pin can handle up to 5 volts?
Is there any need for an external power source, such as a cell?

One example - replacing a voltage regulator, https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno? - I Googled ESP8266 arduino and got over half a million hits, so yes, I believe you could find information about it.

Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a level shifter.
You can buy them cheaply or make them up with a transistor or MOSFET.
I gather the ESP8266 has a Tx (transmit) to the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) from the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.
The ESP8266 Vcc and CH_PD can go to the Arduino 3.3V pin.
Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

References

Voltage divider - Wikipedia
Level shifter - StackExchange
SparkFun Logic Level Converter - Bi-Directional
4-channel I2C-safe Bi-directional Logic Level Converter - Adafruit
Bi-directional level shifter for I²C-bus and other systems - PDF
ESP8266 Community Forum

Thank you for your answer! I have two more questions: Wouldn't it work to use the voltage regulator as described in https://www.youtube.com/watch?v=XdGFzLANsd4? Is it possible to output 3.3V using an analog pin (marked with ~)? The voltage regulator I was thinking to use is: http://www.kjell.com/sortiment/el/elektronik/arduino/moduler/lm2596-spanningsregulator-p87896.

He appears (for some strange reason) to be using a separate regulator to supply power to the ESP8266 - ignoring the fact that the Arduino has a 3.3V pin which does just that. He also connects Tx/Rx without any level shifting which is wrong. In particular, sending to the ESP8266 should be via a level shifter, or at least a voltage divider.

Check out the ESP-Link project over on Github. It has a pretty decent implementation of communicating with an Arduino via UART. As mentioned in another comment you will need a 5v-3.3v level shifter. But if you want to make things a little less messy you could just get a 3.3v Arduino mini for probably around the same price as the level shifter. Esp-link is built with the esp-open-sdk so you will have to spend some time setting up the toolchain if you haven't already.
I'm working on a project right now using a Moteino + ESP-12E and it's working great. However I'm planning on porting the RFM69 library and removing the Arduino portion completely. I would recommend doing the same if you can. The link below shows how to use the ESP with a port-expander (using SPI) so you can have more GPIO with the ESP.
https://github.com/MetalPhreak/ESP8266_MCP23S17

If you want a simplest solution, you can just connect your 5V pin of Arduino to the 3.3V external power supply. It will work just fine on 3.3V and all of its GPIO pins will be 3.3V too.
Warning: You must be careful because if you plug your Arduino to the USB wire, you will instantly get the 5V on all the pins, so you will burn your ESP. So you will have to disconnect ESP during programming.
The easiest (and safe) way for me in this scenario is to just use a standalone ATMEGA328P-PU chip on a breadboard and connect it manually. You just have to plug in 4 capacitors, a 16M oscillator and a resistor and upload sketch using a programmer (like USBasp) and "Upload using a programmer" button. You can then safely run everything on 3.3V because the programmer has a jumper and can work on 3.3V too and you don't have to use ANY level shifters and or voltage dividers. In my case they were not even working (I don't know why). You connect such "environment" once on a breadboard and you can safely work with it later. Let me know if you need more info on this.
Warning: If you work with SPI bus (MISO, MOSI, SCK), like an SD card reader for example, then you must secure the SPI lines of the device (card reader) with resistors, because you may also burn your chip if 2 opposite signals are directed to the same line by 2 separate devices. I've burned my 328P like this once.
Warning: Don't use a programmer for supplying power to your circuit. It can work for programming, but when your ESP starts connecting to WiFi it will require much more power than the programmer can provide! In best scenario it will just not work and hang up or reset.

source: Stack Exchange

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

sort: votes


text:
Do I need to solder wires to my tilt sensor?
I am using the Arduino Starter Kit and I am on project 8. The picture of the sketch in the book is not clear because it shows the tilt sensor seemingly resting sideways, which is not the way that it connects. If you insert the pins into the board the sensor will always be standing and there will be no way to turn it. I was thinking you might have to solder wires to the pins. Does anyone know?
-Thanks
Edit: Perhaps this picture will help:

Pretend for a moment that we don't have a clue what it is your describing.  Show us some pretty pictures and point out what you mean.

My question is: How do you use a tilt sensor, because I can't seem to figure it out, and my book does not explain it.

Well I for one can't see your book or your tilt sensor. PICTURES!

The picture of the sketch in the book is not clear - the picture in your question is even less clear. Non-existent would be my way of describing it. which is not the way that it connects - you've lost me there. I usually tilt things in all sorts of directions when I connect them.

Perhaps this picture will help - see amended answer.

Generally, yes, you will need to solder to that.  In a way a wire wrap tool may be preferable (you can start with it just wrapped, and later solder the wrap if you wish) however that wire has a limited flex life, and you would have to wrap the other end to header pins before inserting them in a breadboard.  Individual female crimp connectors may also be an option, but the pins of that sensor look short and may not work well in housings, though you can individually heat shrink them.   Socket contacts from 2mm connector families sometimes grip .100" pins better at short engagement, too.

I don't have the starter kit but I have a tilt ball sensor:

My guess is that there is a ball inside it, and it connects the wires, like this:

This is confirmed by measurement.

I suggest you either solder wires to it, or push the wires into your breadboard. As you can imagine from the diagram, the contacts will be closed if the ball (or mercury or whatever it is) is downwards. In other words, if the leads are facing down. As you tilt it, the ball will move away from the two wires, breaking the connection. You may have to tilt it quite a lot for this to happen.

(Edited to add)
I see from the Arduino Starter Kit page that the tilt sensor works like this:

This shows that my guess was pretty accurate. :)
There are four pins, so I imagine that the ball would connect four of them if held upright, and various combinations if tilted forwards or sideways.

If you insert the pins into the board the sensor will always be standing and there will be no way to turn it.

Well, you could tilt the breadboard, yes?
However I agree that if you want to tilt just the sensor, then soldering wires to it would seem quite sensible.
I think the starter kit is there to show you the concepts. There is nothing stopping you tilting the entire breadboard to see how it works. In practice you would mount the sensor in such a way that it activated when moved from position A to position B, whatever that is.

I remember when the glass beads with mercury in them were still legal :)  At least with those you could see exactly how they worked.

Yes I think that tilting the sensor when it is on the breadboard might work. It would make sense to tilt the breadboard, but the pins do not fit smugly into the board so it would just fall out; but I think that is why the pins don't fit: so you can turn it.

A breadboard (even a smaller daughter one) will not permit independent connection to all four pins; also the pins are likely too short for reliable connection.

I would say @ChrisStratton is right. Those pins look close together, and it would be hard, or impossible, to get them into a breadboard with independent connections (because of the way breadboards work).

I have the starter kit with the exact same tilt sensor. In my experience it does sorta work. In that you can plug it in the breadboard and it will sit snugly and have a stable connection, but two and two of the connectors will be shorted so you can't use all four independently. And it will respond to tilting the board, at least in one specific direction. So it does work without soldering, at least for learning/demonstration purposes.

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


text:
mcufriend 2.4 tft mega 2560
Please help me w/ my 2.4 mcufriend TFT on my Mega2560.
I've followed any instructions I can find, including:
2.4" TFT LCD Shield isn't working on Arduino Mega
I still get a show white screen. I wonder if my TFT is different or is it broken? Mine looks like this:

I did run the example code from SWtft. I got this output on serial:
TFT LCD test

LCD driver chip: 6TFT LCD test
LCD driver chip: 6767
Benchmark                Time (microseconds)
Screen fill              1786024
Text                     413024
Lines                    2569212
Horiz/Vert Lines         226196
Rectangles (outline)     176972
Rectangles (filled)      4682244
Circles (filled)         2703104
Circles (outline)        1119540
Triangles (outline)      815028
Triangles (filled)       2867288
Rounded rects (outline)  469268
Rounded rects (filled)   5733992
Done!

What TFT is on the carrier board? What chip does it use?

That is the problem.. the shield came without any document.. i tried to read the chip but it is also unclear.

You won't read the chip I am on about - the "Chip On Glass" that is embedded in the TFT screen. You need to know what that is so you can get the right driver. The seller should know. If they don't then they're no good.

According to the seller the the driver is HX8347G LCD n they have managed to run it on uno while i git no luck on mega 2560.

@rudirahmadi check for differences in pin-compatibility between the UNO and MEGA. Make sure that every pin that needs PWM has PWM.

I have one of these TFT LCD shields, but mine is a ILI9335. It has taken me nearly 2 weeks to find a working Library and code for my 9335 driver and I am now setting about creating sketches based around my working Library.
  Library - TFTLCD using st7783 controller
Unfortunately most sellers of these shields (excluding good reputable companies) do not adivise of which Driver is onboard the shield and it becomes difficult to locate a working Library for the driver of the purchased shield.
ALSO, check that the Libraries you have are working for your version of Arduino IDE. Some of my libraries would not compile in v1.0.5 but will in v1.6.3 (and vice versa)
If there is no Library specific to your 6767 Driver (and I must say I have not seen one in my searches for the 9335 Driver) then you may have to download as many different Libraries to locate a sketch that works for yours.
Once you have a working Library then it is just a matter of modifying it for your purposes.
Good luck in finding a working solution for your shield.
Lance..

Thx for your share lance, i wonder if it looks like mine n did you manage to run it on mega2560?

Hello, I also have the 9335 but I have't been able to make it work. Could you share with me the libraries and examples you are using? Thanks

There are several of these boards on sale (mostly from China).
The following IDs of the different chips are taken from a file named mcufriend_kbv_2_8.txt from an archive named Mcufriend_kbv_2.8.zip which provides a whole library(supposely an UTFT fork) supporting these PCBs. Here in the Arduino.cc forum is one of the download links.
----- HX8347-A 240x320  ID=0x8347 new Untested
ILI9320  240x320  ID=0x9320
ILI9325  240x320  ID=0x9325
ILI9327  240x400  ID=0x9327
ILI9329  240x320  ID=0x9329
ILI9335  240x320  ID=0x9335
ILI9341  240x320  ID=0x9341
ILI9481  320x480  ID=0x9481
ILI9486  320x480  ID=0x9486
ILI9488  320x480  ID=0x9488
LGDP4535 240x320  ID=0x4535
RM68090  240x320  ID=0x6809
R61505V  240x320  ID=0xB505
R61505W  240x320  ID=0xC505 new Untested
R61509V  240x400  ID=0xB509
----- S6D0139  240x320  ID=0x0139 removed due to lack of tester
S6D0154  240x320  ID=0x0154
SPFD5408 240x320  ID=0x5408
----- SSD1963  800x480  ID=0x1963 new Untested
SSD1289  240x320  ID=0x1289
ST7781   240x320  ID=0x7783
ST7789V  240x320  ID=0x7789

A white screen is the result of choosing the wrong chip. Choose the right one (by ID) and it will work.

You need to modify these #define parameters of TouchScreen() from
#define YP A3
#define XM A2
#define YM 9
#define XP 8

to
#define YP A2
#define XM A1
#define YM 6
#define XP 7

Only insert the 4th line if (identifier == 0x6767) identifier = 0x7575;
into setup() as below

............
  tft.reset();

  uint16_t identifier = tft.readID();

  if(identifier==0x0101)
      identifier=0x9341;

  if (identifier == 0x6767)
      identifier = 0x7575;

  if(identifier == 0x9325) {

    Serial.println("Found ILI9325 LCD driver");

  } else if(identifier == 0x4535) {

    Serial.println("Found LGDP4535 LCD driver");

  }else if(identifier == 0x9328) {

    Serial.println("Found ILI9328 LCD driver");

  } else if(identifier == 0x7575) {

    Serial.println("Found HX8347G LCD driver");

  } else if(identifier == 0x9341) {

    Serial.println("Found ILI9341 LCD driver");

  } else if(identifier == 0x8357) {

    Serial.println("Found HX8357D LCD driver");

  } else {

    Serial.print("Unknown LCD driver chip: ");

    Serial.println(identifier, HEX);

    Serial.println("If using the Adafruit 2.4\" TFT Arduino shield, the line:");

    Serial.println("  #define USE_ADAFRUIT_SHIELD_PINOUT");

    Serial.println("should appear in the library header (Adafruit_TFT.h).");

    Serial.println("If using the breakout board, it should NOT be #defined!");

    Serial.println("Also if using the breakout, double-check that all wiring");

    Serial.println("matches the tutorial.");

    return;

  }

Try it.

Most likely not supported controller or disabled in .cpp file. Firstly find out your ID like for example ID=0x6767. Then look in the MCUFRIEND_kvb library folder "extras" to enable support for example in our case 0x6767 is 8347D. Lastly go to library root and edit MCUFRIEND_kvd.cpp and uncomment asin ou example: #define SUPPORT_8347D. Save the modified .cpp file then upload example graphic test.

Hi and welcome. uncomment asin ou example - do you mean uncomment as in your example? Please [edit] and fix any typos. Thanks.

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


text:
Why should I put a 10K resistor with an LDR?
I am wondering why should I put a 10K resistor with an LDR.
If I put a "stronger" resistor with another resistor (in this case the LDR), I'd get a lower voltage, and then I'd, too, get a lower value in the analogRead(). I'd like to know in what I'm doing wrong. Can someone help me?

Can you draw a schematic of how you've connected everything?

LDR have a changing resistance, relative the the amount of light. The arduino can't measure resistance, only voltage. So one way is to create a voltage divider. One resistor will be the LDR, the other one will be a fixed value resistor. To value of that resistor depends on the typical resistance of the LDR, the light-level range you'd like, power consumption, and other factors. I don't see why you think you are doing something wrong. With a higher value resistor, you get more precision in dark conditions. (try swapping the resistor an LDR).

LDRs themselves come in a considerable range of resistances. Search LDR specs and you will see what I mean. For example, from eBay I found one:

Bright Resistance(10Lux)(KΩ):20-230
Dark Resistance: 2 MΩ

This particular one, for example, seems to range from around 20k to 2M ohms. A reasonable series resistor would then seem to be somewhere in the middle of that range, otherwise all your readings would be skewed at one end of the scale.
For example, in this case if you used 10k and the LDR had 20 k resistance in very bright light, then the voltage would be 3.33 V
20000 / (20000 + 10000) * 5 = 3.33 V

Then if it got slightly darker and the LDR was 230 k, you would get:
230000 / (230000 + 10000) * 5 = 4.79 V

And if it was really dark you would get:
2000000 / (2000000 + 10000) * 5 = 4.98 V

You can see from those figures that you will never get a reading less than 3.33 V with this particular LDR and a 10k resistor. Thus a higher value resistor would give you a better range of readings.
However this totally depends on what resistance your particular LDR has.

Ok Nick, but I can't understand why a higher resistor gives a higher voltage than a weaker one. Like, if I put a 300 ohms resistor in the place of this 10k resistor I get a minor voltage, and wouldn't have to be the reverse? A higher resistor "returns" a minor voltage and a weaker resistor returns a higher voltage?

It depends on the order of the resistors, basically. If the LDR is R1, and the fixed resistor is R2, you will get an opposite effect than if they are the other way around. You are sampling in the middle, after all.

After you check the LDR specification you can use an online Ohm's Law calculator and calculate the resistance you need.  Be sure the power rating of the resistor is greater then what is shown.  Less it will smoke more is good but size is also important.
Gil


text:
Any disadvantages on using Particle Photon over an Arduino?
It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.
I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..
One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors.

It's horses for courses. The Photon fulfils a different need to the Arduino. Use the device that best fits what you want to achieve.

Arduino has never been inexpensive; once you are willing to consider alternatives there are many having more capability, and some selling for less than half of the price of the photon.  For a one-off, effort is a substantial consideration, while for a project you will use in volume, how the price decreases as you start buying in volume matters a lot - Arduino almost wins there, as you can use the inexpensive bare chips on a custom design, while with photon you may have trouble cutting out the "particle" middlemen.

Photon advantages:
The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.
A photon  about 1/4 the size of an Arduino UNO
Photon is much cheaper than arduinos
Arduino UNO advantages:
Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt
Arduino has many resources while Photons don't since Photons are fairly new
Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)
UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital
UNOs have female pins, so no breadboards are necessary for small, simple projects.
Photons have male pins, and they need to be plugged into a breadboard or soldered.
Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!

"Photons need to be connected to wifi and the cloud to run code". This isn't completely correct. Photons need internet for code to be uploaded to it, but other than that, they can run without internet (if your code doesn't require internet, but in that case you can just use an Arduino).

Thanks for pointing that out. I will edit my answer. I would also like to say that it IS possible to flash code to an Photon without wifi, but it is a highly complicated process.

Your new edit also includes some more information of USB flashing a Photon, which indeed is really complicated. Good addition.


text:
SoftwareSerial returns garbage when powered externally
I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?

Have you measured this wall wart? 15V is high for Vin, and it might be noisy conceivably. Try a different one. Preferably lower voltage.

I did measure it. 15v is whats coming out. How would i check noise?

Put the meter on AC voltage and see if you get any reading. Try a different wall-wart. Recommended input voltage is 7 to 12 V.

@NickGammon i dont have another voltage supply. Can i use a voltage divider?

Voltage dividers are not recommended as voltage regulators. Are you using a level shifter for communicating with the ESP8266? Plus, can you measure what voltage is on the 5V pin when you are powering the Nano from the wall-wart?

@NickGammon im using a voltage divider for comm to esp. Yes i will measure it. What am i looking for?

Let us continue this discussion in chat.

"Voltage dividers are not recommended as voltage regulators" - correct that to "Voltage dividers cannot be used as voltage regulators". It's not a question of recommendation, it's simple Ohm's Law that they cannot work.

Just to add my two pence quickly. Is it just that you need to have a common Ground? Try connecting the grounds of both devices together

If you check the specifications they stat 12VDC is the max.  Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag.  You can get a 9V wall Wart for under $5.  the 9V will keep the on-board regulator much cooler and add reliability.


text:
how much current does Arduino Nano draw when only using 8 digital pins?
I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply.
I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?

I would guess around 50 mA, to power the processor and the USB converter. I notice that this question suggests more like 20 mA.
To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.


text:
My mega only works on 1.0.1 IDE
My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an
 avrdude: stk500v2_getsync(): timeout communicating with programmer

When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE.
This happens on my pc, and on a laptop son no pc related problems.
I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.
I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out.
What can be the problem here? How can I get more info from the console to solve this?

How have you wired your FTDI board?

Do you mean if the programmer is correctly wired to the Mega? Yes, it is. Since it can upload sketches to it on the 1.0.1 IDE

No, I didn't ask you if you thought it was wired correctly. I asked you to tell me how it is wired. Never assume it's correct just because it's been working. Something is wrong, so let's start with that.

Good point. I don't have it in front of me right now so I'll tell you as I remember. Also note that a few hours ago I re

(Pressed enter by mistake)
Good point. I don't have it in front of me right now so I'll tell you as I remember. The FTDI chip provides 5V, GND, Rx, Tx, DTR and CTS pins. 5V and GND are connected to the power rails of the Mega (powering it with an external wall-wart PS changes nothing). Rx and Tx are conected crossed to the Rx0 and Tx0 port on the Mega. And finally the DTR is connected to Reset pin on the Mega. CTS is not connected. I believe it is connected correctly and running both versions of the IDE side by side one does upload and the other doesn't.
By the way, thank you for your help!

As I suspected - your wiring may well be wrong.  You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

I'll try that as soon as I get back home in a few hours! But then again, I can still upload correctly on the older IDE without doing any modifications to the wiring...
Anyway, that's it for now. Thank you very much!

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.

Ok so I got it working perfectly. Thank you very much! If you'd like to submit an answer then I would mark it as the correct answer. Thanks again!
Regards, Rodrigo.

You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.
The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.


text:
FTDI breakout connection
I have been successfully programming UNO boards. I wanted to transfer the project to a Pro Mini. I am using a FTDI breakout. It wouldn't show the device port. I found the device driver I was using was supplied by MatterControl. So I updated the driver from FTDI.
When I connected it I see the port available, but cannot program it. I get
not in sync: resp=0x01 avrdude: stk500_recv(): programmer is not responding

I checked in the device manager and see "USB Serial Port (COM5)" and properties shows "This device is working properly." the provider is FTDI.

This error can come from a number of sources and you'll find this is a common question on arduino.stackexchange. The most likely reasons are:

If the board wasn't reset, the bootloader didn't run;
Rx & Tx connections between the FTDI and the board may be reversed;
Avrdude may be using a different baud rate than the bootloader expects. 57600 baud used to be standard for Atmega328p bootloaders. More recent firmware is using 115200 baud. I've been bitten by this one regularly; my chips have older bootloaders and one of my PCs has a very recent Arduino IDE.

I made the board using the great tutorial by Nick Gammon  for the minimum Arduino board. I got the boot loader to load using Nick's tutorial and then spent a few evenings trying to use FTDI to upload sketches but could not get it to work. In the end, using various bits of inforamtion I found on the web, I made sure the reset signal was coming from the the FTDI (going to low) and then checked the settings of the FTDI and tried to make some changes. I found that the settings in my photos work. Mainly the bit rate 115200 and the latency (m/secs) time to 5 m/secs. The wires from FTDI starting from the top in looking at photo - brown (ground to ground), red (vcc to vcc) orange (tx to rx), Yellow (rx to tx), the other separate orange (was better I used another colour!) is from RTS to reset.
I selected Arduino uno as board and (in my case) COM 10. For me it ow works. I don't know if I would make many of these boars though because of the time and effort. However, itwas a good expeiance and I learnt a great deal. Particularly from Nick Gammon. Thanks Nick!

The problem was resolved by changing "set RTS on close" in the device manager properties as stated here
https://electronics.stackexchange.com/a/87955/80377


text:
What Driver IC to use for 40v 2amp DC motor?
I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..

One that can drive 40V 2A. This is what parametric searches are for on electronics suppliers - use them. If you can't find a suitable chip then you can always build your own H-bridge from MOSFETs.

Two minutes with a parametric search told me to use the L298N

Looking on eBay they are available for peanuts from China on a handy breakout board for even easier use.

@Majenko Can i use L298N for direction reversal as well?

It is a pair of full H-bridges. You can use it to drive two motors in both directions independently. Note that the modules on eBay seem to be limited to 35V because of the 7805 on them. Remove that and you have the full 48V range.

It's quite hard, on ebay, to find anything but L298N, once the power envelop swells enough :-)

@Majenko How do i remove 7805..infact what that means?

@AwaisSaifi There may be a switch or jumpers to do it for you. The 7805 is the 5V regulator on the board - the small black square chip thing that is on most of the breakout boards on eBay. If you do have to remove it (no switch or jumpers) then you would, logically, use a soldering iron.

@IgorStoppa not just on eBay :-p

@Majenko I intend to use just the chip not breakout board. Can i do that?

@AwaisSaifi Yes. In that case you don't have to worry about anything except making sure you have a suitable heatsink.

On the board I'm using right now, the 7805 is soldered in a not-so-easy-to-reach position and it's flat, it's using the board itself as both ground and heat sink.
In such case I'd cut the 2 pins as close as possible to the resin package, desolder the 2 stumps and wire out to a separate, discrete regulator. For bonus points, mount it upside down on the heatsink, using the same screw  and hole that the L298N is using. This is the board I'm talking about http://www.photo138.com/0/BOB/CEG007200-D-4.JPG

@Majenko Hmmm and how do i do that. I know i'm being annoying but believe me i'm a beginner and its my final year project and i need all the help i can get and this is the only place.

@AwaisSaifi Crudely: You buy a big heatsink of the right style and attach it with a bolt through the hole.  In detail: You read the datasheet, calculate the thermal coefficients etc and find the right heatsink to dissipate the desired amount of heat in the environment you are running it in. Look at the ones on eBay - you will see the heatsink. The big lump of metal attached to the chip.

@IgorStoppa that would be difficult for me as i want it to be simpler.

@Majenko ok got that.

I'd think it's simpler to rewire 2 pads than design from scratch the board I linked to. Btw, it's 2-sided and has tracks already routed and designed to cope with the currents involved.

@IgorStoppa gotta consider both options. you said you would use a seperate regulator, which one to be exact?

If you check the datasheet for the L298N, it says that the max voltage is 7V, so a 7807 is the simpler choice..
You do not even have to solder anything: as long as you cut the pins of the onboard 7805, you can feed the 7V through the 3rd line of the power connector, which would be usually meant for drawing 5V from the onboard regulator.

@Majenko what if i use a driver with higher parameters like 50v 3amp? Will it work with my motor?

@AwaisSaifi Yes, that will be fine. Those are upper limits of what it can handle - more than that and you risk burning out the driver.

@Majenko Will the motor draw what it needs and not more??

@AwaisSaifi That is correct. You provide the correct voltage (power supply), the motor draws an amount of current (depending on loading). The driver has to be able to cope with those two values. A bit like a pint of beer. You want a pint of beer, and the bar tender is capable of pouring you a pint of beer. As long as what he pours it into is big enough it won't overflow - whether it's a pint glass, or a flagon, it doesn't matter.

@IgorStoppa If i am to rewire the regulator, which regulator should i use?

@AwaisSaifi: did I not answer already?

@IgorStoppa I'm terribly sorry man. I think i'm overstressed about this project. anyways apologies. :)

what if i just join the two pins from where i remove the 7805? @IgorStoppa

If i understood the datasheet correctly, you want the regulated side to be 7V, but joining the 2 voltage domains means that also the input voltage must be 7V

I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor.  By far the easiest way is to simply use a N-Channel logic level MOSFET.  Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground.  The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino.  The low side of the 40V power supply must be connected to the source of the MOSFET.
Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).
Carefully check your wiring; if it is ok you are ready to test it.  The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected.  The anode side connects to the drain of the MOSFET.  When the motor is turned on the LED will light, if it does not reverse polarity of the LED.  As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected.  Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

This helps dampen oscillations
Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
For the MOSFET you need at least 60V with a 10A rating.  This should work with a small heat sink.  If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger)
The other side of the resistor goes to the gate of the MOSFET.
Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together.  The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V.  The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.
Good Luck,
Gil


text:
How can I do this sentence show me in arduino
How can I do this sentence show me in arduino."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'

Umm..... you what?

Your question does not make any sense at all.

Your question is unclear.
Note that Mouse and Keyboard libraries are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro.   They are not relevant when using an Uno.

For Uno, it's LUFA: http://www.fourwalledcubicle.com/LUFA.php


text:
Bluetooth distorts analog read?
I'm working to make a simple pedometer with Arduino, and after managing to find an algorithm that correctly finds the steps, I added a bluetooth extension (the overly popular and cheap JY-MCU) to check the steps via bluetooth.
I am facing a strange issue, though: when the bluetooth device is powered and waiting for a connection (red led blinking) the analog read function that reads data from the accelerometer goes crazy (thus the pedometer finds a step each second or so). When the bluetooth is powered down or connected to a device such as a mobile phone this doesn't happen.
Did anyone have this problem before? What could be the issue? My setup is easy, you can see it on the image.

I had other sensors as well but since the problem stays even when there are only those two connected I posted the bare minimum setup.
At first I thought I could use some kind of pull-ups to stabilise the signal, but I really have no idea on where to tie them and if they can really be helpful at all...
Any help is appreciated.

Try placing them further apart. Also use two separate wires to power the two modules (which you are probably already doing). If all that fails, try powering the ADXL from 3.3v. If this fixes thing, it means there is some coupling issue.

Yes, the common red line of the drawing is in reality the long "+" line of the breadboard, and two different wires go to BT and ADXL. Powering either of the two with the 3.3v out doesn't help either (originally my idea was of powering the BT with one of the out pins because that way I could control when powering on and off the BT, but for the sake of resolving this issue I momentarily switched to the common rail of power).  The only "fix" is when I power the BT with an external battery (which, as you say, it means there are coupling issues)...

Try adding a small value cap between AREF and ground. Who knows.

Please add an analysis of the power budget. How much current can the 3.3V pin on the Uno supply? How much does the BT require (on peak)? Etc. You need to always do the numbers; hardware and software.

You can try decoupling the power for the bluetooth:

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that.  The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big.  (Make sure you wire it the right way round - check which pin is marked as -)  You might also want to add a small capacitor (say 100nF) in parallel with the large one.

It seems it is not working. At first I thought it was, but I had some code wrong. I'll try again and keep you posted.

Decoupling should be the right solution because when I connect the bluetooth to an external battery it gives me no problem. I just have to figure out why I can't decouple it correctly!

What size components are you using? I only guessed the values in the drawing, it may take some adjustment. Try smaller resistor, or replace the resistor with an inductor.

I tried capacitors up to 1000micro, and the resistor as suggested 10 ohm. I'll see if at home I have some smaller resistors or an inductor

Just one question: I managed to find a 2200µF capacitor and tried that as well. But I noticed that it's a 6.3V capacitor. Could the voltage difference be an issue and the reason why decoupling does not work? Do I have to find a 5V one maybe?

@Luca No. You need a capacitor whose voltage is above the voltage you are using - 6.3V is perfect.  The voltage rating of a capacitor is the voltage above which it is liable to explode.

@Luca Oh, one other thing - the resistor and capacitor will cause a delay in the powering on of the bluetooth module. The bigger the capacitor the longer that delay will be - you may want to reduce the value of the resistor to compensate (but not too much or you will risk exceeding the USB inrush current rating) and/or add a delay to the start of your program to allow the capacitor to charge up.

Yes, I noticed the delay and I though that it would more or less be the usual 0.69RC, isn't it? I really don't care about the delay as long as I get it working... Which still doesn't, and I'm beginning to get a little frustrated because I'm sure that the capacitor charges since it powers the BT for some fraction of a second if I try to disconnect the circuit from the main power source...


text:
ATMega328 + Bluefruit LE stops working soon after power on (not consistently)
Now I am Running Arduino code for Bluefruit LE on bare ATMega328 with 8MHz internal clock, with Bluefruit connected, pin 0 and 1 RX/TX unused, and AT42QT1011-based capsense circuits (logical input to pins 1, 2, 3).
There appeared one problem: when I try to switch the device ON (with 4.5 V batteries, but the same with 5 V USB power), it happens only after three or more attempts. Each time "loop" stops after a second of what appears to be correct operation. For example, if I touch one of the capsensors on the first second of operation, and LED is on, it stays ON, which means, the "loop" is not run.
I have tried to put back the Serial (it was in use in the original echoDemo example), tried to put pollACI after digitalWrite to LED pins. See pin assignments defined in the sketch, those were re-checked with actual circuit.
Measured power supply current and voltage - there were no significant changes in it, even if both LEDs were on. BLE module at startup or while transmitting, was not causing any brownouts. In addition, checked input current and voltage with oscilloscope, and there were no anomalies as well.
NB, this is atmega328, without "p", so for the record I am using 0x07 efuse, 0xE2 lfuse and 0xD9 hfuse.
Also, if the device starts up, it will work fine for at least an hour.
What could be other reasons for such random early failure? (in average, about four attempts to switch on, sometimes starts even on first, second time)
The sketch in question:
/*********************************************************************
This is an example for our nRF8001 Bluetooth Low Energy Breakout

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/1697

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Kevin Townsend/KTOWN  for Adafruit Industries.
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in any redistribution
*********************************************************************/

//#define F_CPU 8000000

#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2     // This should be an interrupt pin, on Uno thats #2 or #3
#define ADAFRUITBLE_RST 7

#define REDLED 8
#define BLUELED 9
#define LEFTPAD A2
#define RIGHTPAD A3
#define BADPAD A1

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

unsigned int leftcnt, rightcnt;

void setup(void)
{
  pinMode(REDLED, OUTPUT);
  pinMode(BLUELED, OUTPUT);
  pinMode(LEFTPAD, INPUT_PULLUP);
  pinMode(RIGHTPAD, INPUT_PULLUP);
  pinMode(BADPAD, INPUT_PULLUP);
  digitalWrite(BLUELED, LOW);
  digitalWrite(REDLED, LOW);
  delay(300);
  BTLEserial.setDeviceName("MYUART"); /* 7 characters max! */
  BTLEserial.begin();
  digitalWrite(REDLED, HIGH);
  delay(300);
  digitalWrite(BLUELED, HIGH);
  leftcnt = 0;
  rightcnt = 0;
}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop()
{
  BTLEserial.pollACI();

  if (digitalRead(LEFTPAD)) {
    leftcnt++;
    digitalWrite(BLUELED, LOW);
  } else {
    leftcnt = 0;
    digitalWrite(BLUELED, HIGH);
  }
  if (digitalRead(RIGHTPAD)) {
    rightcnt++;
    digitalWrite(REDLED, LOW);
  } else {
    rightcnt = 0;
    digitalWrite(REDLED, HIGH);
  }

  aci_evt_opcode_t status = BTLEserial.getState();

  if (status == ACI_EVT_CONNECTED) {
    boolean inp = false;
    while (BTLEserial.available()) {
      char c = BTLEserial.read();
      inp = true;
    }
    if (inp) {
      if (leftcnt > 5) {
        BTLEserial.print("LEFT");
      }
      if (rightcnt > 5) {
        BTLEserial.print("RIGHT");
      }
      if (digitalRead(BADPAD)) {
        BTLEserial.print("CENTRAL");
      }
    }
  }
}

UPDATE: MCU's reset pin is pulled-up by a resistor. Bluefruit's RST connected to PD7 on atmega328 (also known as arduino digital pin 7). Also, 3.3 uF capacitor on the power lines near MCU's IC. (there are more near capsense circuits).
When I disconnect Bluefruit's power, the rest of the circuit (LEDs showing cap sensors state) works without failures after startup. So it looks like under some circumstances, control never leaves BLE code to return to the loop?
UPDATE 2: Found long list of reset causes (not sure yet whether relevant here): Arduino/AVR ATmega microcontroller, random resets, jumps or variable/data corruption ...
UPDATE 3: Added two 100nF bypass capacitors near GND / VCC pins on both sides. The problem is still there.
UPDATE 4: Performed all kinds of experiments, placing BLE module's power lines in different places, with different capacitors. Only in the case of separate power (common ground) the problems were different (but may be due to different times of turning module and MCU on).
UPDATE 5: May be relevant or not, but when I run MCU on 1MHz (8 MHz internal clock, divided by 8 - lfuse 0x62), success rate is better than 70%. The speed seem to be enough for my application, but of course near 100% turn-on success should be achieved.
MAY BE IMPORTANT: I have added watchdog to sketch (thanks to the "Make: Sensors" book by Karvinen & Karvinen, Valtokari):
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  WDTCSR = 1<<WDP0 | 1<<WDP3;
  WDTCSR |= _BV(WDIE);
  MCUSR &= ~( 1 << WDRF);

And in the respective ISR red led is turned on or off once in about 8 seconds or so. And ISR code works (thus, MCU works all the time too, right?), even though the "loop" runs no longer.
Can this still be attributed to trouble with power or is it more likely control flow is stuck somewhere in the BLE library?
UPDATE: Well... As advised here, while trying out Serial (via microbot USB adapter), I understood, that it does not work reliably (if at all, sometimes eats characters, prints garbage, ...). Not sure whether SPI is sensitive to clock accuracy, but if it is, it may be the problem. Also, the circuit turns on always when powered from USB3 port 5V.

What is the wiring of your reset pin?  Do you have bypass caps on the power pins?   Write a sketch which outputs a running count on the serial port, temporarily connect a logic level serial port (USB converter cable or whatever) to the transmit pin, and monitor that to see if it keeps running or also experiences unexplained failure.

Updated. Do you mean a sketch, where I do not do any Bluetooth? As for connecting serial port, I will try.

Yes, one with no bluetooth only to test the hardware of the MCU portion of your board.  The capacitor you have described is more of a filter than a bypass.  Don't remove it, but you should also have a smaller (and hence lower inductance) capacitor connected as directly across the power pins as you can manage.

Updated: the rest of circuit works without failures, when power disconnected from Bluefruit (or if all control wires disconnected - I have two separate cables).

You should still try it connected, but with a program that doesn't use it, and only outputs on the serial.  One thing to keep in mind is that BLE chips, especially first generation ones, can draw a lot of pulse current when transmitting.

Tried. The device works fine when I remove BTLEserial.pollACI(). Otherwise the same behaviour: more often than not cease to operate after approx. a second. I have not seen any pulses of current on the scope, but will do more checking tomorrow. Also, when I disconnect/reconnect Bluefruit's power, MCU sometimes resets - this might indeed indicate power problem (unless the Adafruit's library is doing this reset).

Does the bare ATMega328 have some decoupling capacitors near it?

The main problem cause was inaccurate internal clock. As soon, as external 8MHz crystal has been attached to XTAL pins (with a pair of 22pF capacitors to GND), problems with turning the board on disappeared.
Also, I found
while(1);

loop in the Adafruit's nRF8001 library, which runs whenever problems with the Bluefruit LE board are encountered. That is possibly why interrupts worked fine, but the whole MCU never returned to the main loop.


text:
Arduino Due upload firmware issue
I have Arduino Due on SAM3x8e. I'm on Ubuntu 14.04. Before today I uploaded firmware via terminal using those commands:
$ stty -F /dev/ttyACM0 speed 1200 cs8 -cstopb -parenb
$ /home/q/apps/devel/arduino/arduino-1.5.7/hardware/tools/bossac --port=ttyACM0 -U false -e -w -v -b /home/q/work/gk/j-v2/embedded/smib/Release/smib.bin -R

It was good, but now it stopped working. Bossac just hangs up '-d' displays nothing. That is all.
I downloaded arduino IDE 1.6.5, but this doesn't matter. In ide's console I get
Sketch uses 11,000 bytes (2%) of program storage space. Maximum is 524,288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
/home/q/.arduino15/packages/arduino/tools/bossac/1.3a-arduino/bossac -i -d --port=ttyACM0 -U false -e -w -v -b /tmp/build238086227206829290.tmp/AnalogReadSerial.cpp.bin -R

It sticks, no leds blinking on Arduino board. It seems it actually hangs up, due to it loads 99% of CPU... May be Ubuntu update caused this issue...?
dmesg
[ 5168.658692] usb 3-3: new full-speed USB device number 7 using xhci_hcd
[ 5168.676969] usb 3-3: New USB device found, idVendor=2341, idProduct=003d
[ 5168.676979] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 5168.676985] usb 3-3: Product: Arduino Due Prog. Port
[ 5168.676989] usb 3-3: Manufacturer: Arduino (www.arduino.cc)
[ 5168.676994] usb 3-3: SerialNumber: 75438313633351A07051
[ 5168.677225] usb 3-3: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[ 5168.677652] cdc_acm 3-3:1.0: ttyACM0: USB ACM device

syslog
Oct  4 21:49:01 4xybook kernel: [ 5356.553290] usb 3-3: new full-speed USB device number 8 using xhci_hcd
Oct  4 21:49:01 4xybook kernel: [ 5356.571623] usb 3-3: New USB device found, idVendor=2341, idProduct=003d
Oct  4 21:49:01 4xybook kernel: [ 5356.571635] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Oct  4 21:49:01 4xybook kernel: [ 5356.571643] usb 3-3: Product: Arduino Due Prog. Port
Oct  4 21:49:01 4xybook kernel: [ 5356.571649] usb 3-3: Manufacturer: Arduino (www.arduino.cc)
Oct  4 21:49:01 4xybook kernel: [ 5356.571655] usb 3-3: SerialNumber: 75438313633351A07051
Oct  4 21:49:01 4xybook kernel: [ 5356.571923] usb 3-3: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
Oct  4 21:49:01 4xybook kernel: [ 5356.572506] cdc_acm 3-3:1.0: ttyACM0: USB ACM device
Oct  4 21:49:01 4xybook mtp-probe: checking bus 3, device 8: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-3"
Oct  4 21:49:01 4xybook mtp-probe: bus: 3, device: 8 was not an MTP device

lsusb
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 8087:07da Intel Corp.
Bus 001 Device 003: ID 064e:c336 Suyin Corp.
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 002: ID 152d:0567 JMicron Technology Corp. / JMicron USA Technology Corp.
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 008: ID 2341:003d Arduino SA
Bus 003 Device 002: ID 1a2c:0e24 China Resource Semico Co., Ltd
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Any help would be really appreciated.
Update
strace gives this.
execve("/home/q/apps/devel/arduino/arduino-1.5.7/hardware/tools/bossac", ["/home/q/apps/devel/arduino/ardui"..., "--port=ttyACM0", "-U", "false", "-e", "-w", "-v", "-b", "-d", "/home/q/work/gamekeeper/jackpot-"..., "-R"], [/* 78 vars */]) = 0
brk(0)                                  = 0x22a5000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e385000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=169535, ...}) = 0
mmap(NULL, 169535, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f468e35b000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/usr/lib/x86_64-linux-gnu/libstdc++.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0 \266\5\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=979056, ...}) = 0
mmap(NULL, 3159040, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468de61000
mprotect(0x7f468df47000, 2093056, PROT_NONE) = 0
mmap(0x7f468e146000, 40960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe5000) = 0x7f468e146000
mmap(0x7f468e150000, 82944, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f468e150000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libgcc_s.so.1", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260*\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=90080, ...}) = 0
mmap(NULL, 2185952, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468dc4b000
mprotect(0x7f468dc61000, 2093056, PROT_NONE) = 0
mmap(0x7f468de60000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x15000) = 0x7f468de60000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320\37\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1840928, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e35a000
mmap(NULL, 3949248, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468d886000
mprotect(0x7f468da41000, 2093056, PROT_NONE) = 0
mmap(0x7f468dc40000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ba000) = 0x7f468dc40000
mmap(0x7f468dc46000, 17088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f468dc46000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libm.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\20V\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=1071552, ...}) = 0
mmap(NULL, 3166568, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468d580000
mprotect(0x7f468d685000, 2093056, PROT_NONE) = 0
mmap(0x7f468d884000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x104000) = 0x7f468d884000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e359000
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e357000
arch_prctl(ARCH_SET_FS, 0x7f468e357780) = 0
mprotect(0x7f468dc40000, 16384, PROT_READ) = 0
mprotect(0x7f468d884000, 4096, PROT_READ) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e356000
mprotect(0x7f468e146000, 32768, PROT_READ) = 0
mprotect(0x7f468e387000, 4096, PROT_READ) = 0
munmap(0x7f468e35b000, 169535)          = 0
brk(0)                                  = 0x22a5000
brk(0x22c6000)                          = 0x22c6000
openat(AT_FDCWD, "/dev", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3
open("/dev/ttyACM0", O_RDWR|O_NOCTTY|O_NONBLOCK) = 4
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B9600 opost isig icanon echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B9600 opost isig icanon echo ...}) = 0
ioctl(4, SNDCTL_TMR_START or SNDRV_TIMER_IOCTL_TREAD or TCSETS, {B115200 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B115200 -opost -isig -icanon -echo ...}) = 0
nanosleep({0, 500000000}, NULL)         = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99992})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99994})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99996})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0

It indefinitely polls the descriptor. select = 1 means there is a data, but read returns 0. It seems like something on lower level is broken... may be because of system update (

You could run bossac under strace and possibly see what it is doing when it hangs, but be prepared for a flood of data.  Are you able to either try that board on another computer, or try another similar board on this computer?

Which port are you using - the programming port or the native port?

@Chris Stratton I tried another board with the same result (

@Majenko Same result on both ports.

Have you tried erasing the board?

How exactly? if bossac -e, yes

From the man page for select() readfds will be watched to see if characters  become  available  for
reading  (more  precisely, to see if a read will not block; in particu‐
lar, a file descriptor is also ready on end-of-file) - probably the case since after the first call it starts returning effectively immediately with the timeout unused.  You might see if anything is odd in the serial port settings, or use lsof to see if anything else has the port open.  Trying on another machine (or live USB boot?) would be good too.

@Majenko I havn't seen 'erase' button before), I tried, unfortunately, it doesn't help

Hi Chris, I updated strace log, now it's from begining. lsof shows only bossac as port user. Under Ubuntu Live USB bossac returns "No device found". On another windows machine it works

Kernel update resolves the issue.
http://askubuntu.com/questions/681555/ubuntu-14-04-arduino-due-upload-firmware-issue


text:
Why PJ0 and PJ1 are not reporting as PCINT pins
When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT.  (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.)  For example, for an ATmega-2560 board, the program's output includes lines like
  Pin# Port Mask  PWM  PCINT
  11   PB5  0x20  PWM  PCINT5  PCINT0_vect
  46   PL3  0x08  PWM
  52   PB1  0x02       PCINT1  PCINT0_vect

Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:
  14   PJ1  0x02
  15   PJ0  0x01

As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1_vect, but the program doesn't report them as such.  What is this problem due to?
⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561.  Also see Why is my interrupt code not working?.
Sketch pinsList.ino:
/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

Majenko was very close but seems to have missed the explanatory comment from the source code:
// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
// Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.
As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file in commit f179794  in response to issue 490:

The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins.  We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code originally written as part of the software serial library to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes).  It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...
It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless.  But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.
Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.

And also the counterargument that software serial is not the only use for interrupts.

@IgnacioVazquez-Abrams - when the code in question was originally written, it was only for software serial and buried in that (at the time 3rd party) library.  So that would be an argument for patching it now that it is more general, but not an argument against the original decision.

It's because of this entry in the board's pins_arduino.h file:
#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Basically your program isn't reporting what the pins can do - it's reporting what the Arduino system has been programmed to support for those pins.  Basically it hasn't been programmed to support PCINT on those pins.

Majenko, although I already understood that I upvoted your answer; but why aren't pins 14 and 15 listed in that macro?

Who knows? Why is anything the way it is with Arduino? Most of the time the answer is "Because the person that wrote it is clueless"...


text:
Upload Assembly to AVR on a breadboard using Arduino as ISP
I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command
avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

and also
avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?
EDIT This command worked for me
avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i

You're using your Arduino as the programmer, but you're using "avrisp"?

i do so because the arduino ide doesnt compile and upload my asm code correctly - just inline asm. what should i use? -c arduino? i also tried that without any success.

Hello folks is my question bad written or does nobody have an answer?

It would be good to definitively separate the problem into pieces.  If you can get a bootloader on the breadboard chip, such that you can upload sketches to it over (USB-) serial rather than ISP, then you should also be able to upload valid assembly code built with a bootloader-compatible memory footprint.  But if you are using an Arduino as an ISP programmer, and are having problems differentiating between its bootloader and the programmed ISP sketch, then you need to solve that first.  Making sure the ISP sketch uses a different baud rate than the bootloader could help a lot.

thank you very much. im really new to that stuff, sry. where can i see what baudrate the bootloader uses? in the arduino ide its just a menu button i have klicked "burn bootloader". i dont have a usual programmer, just the arduino.

very sad, no answer even on stackexchange. maybe its impossible what i want to do. thank you all anyways if i'll find a solution, i will tell you too.

Hello folks is my question bad written or does nobody have an answer? - so, no answer after one hour, huh? Maybe a lot of people are in bed. Patience, old chap!

Try uploading the blink sketch to the standalone atmega328 first. Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).

@Gerben Thank you :D shame on me that i havent thought about that. works perfectly. Wont you add it as an answer? i cant give points to comments.

Great to hear you got it working. Maybe you could add the right command for in case someone else has the same problem in the future.

Try uploading the blink sketch to the standalone atmega328 first.
Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).


text:
Why can only some digital ports output PWM and the others not?
If it matters, I'm talking about the arduino uno v3.

Six out of twenty ain't bad. Plus you can do PWM in software, to an extent, like the Tone library does.

Check out the ATMega328p datasheet: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.
It's a limitation, but so is everything else.
If you do not like it, you can always choose a different microcontroller, either AVR or something else.
Certain models might  be designed to have more units of a specific type than you would find on generic microcontrollers.

on top of that, typically Timer1 (16 bits) is used by the OS/scheduler - what OS/scheduler are you referring to?

ChibiOS, for example, uses Timer1. Some time ago I went through various options available in terms of OS/RTOS/scheduler for ARduino/AVR and, as far as I can remember, Timer1 was the favourite choice.

That is one of the hardware features/functions of the microprocessor.  It is like a bag of candy when you eat the last piece there is no more left.  You can do software PWM but that can use a lot of compute power.  You can also get PWM peripheral devices you can connect to it.

After all, it's a cost issue.
Not only of the Arduino/Atmel, but any microcontroller.
The outputs of the PWM unit (which has a limited number of PWM channels) have to be routed to the output pins.
This routing is basically fix, because the silicon mask is fix.
However, to add some flexibility, most controllers allow a limited configuration of this routing by adding some internal switches which can be accessed by writing to the specific registers.
But any additional routing capabilities means more of those internal switches, which results in more size -> more silicon -> more expensive.
Therefore the micro designers say - for example - "OK, it's enough to be able to output x of the y available PWM channels at every edge of the micro", and the poor PCB designer has to cope with what he gets.
Using an FPGA instead of a microcontroller you are really free to setup your function to pin routing - but look at the price of an FPGA ;-)


text:
Need help in the project "Arduino for audio processing"
I am following this link from Instructables site:
http://www.instructables.com/id/Arduino-Audio-Input/
My question is:
Instead of using the Microphone Radioshack 33-3038, which is listed in the tutorial, can I use https://www.sparkfun.com/products/9964?
Kindly suggest if there any modifications required in other parts for the circuitry, if I go for Electret Microphone.

Oooh, another wonderful Instructable circuit design... shudder

The replacement microphone you link to contains all the circuitry in that instructable*.  You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.

Destructable! Awesome!

@Gerben 90% of what is on Instructables is complete and utter garbage. The other 10% is my comments telling them so ;)

one more query guys,
As sparkfun  Electret microphone has already inbuilt op-amp, So do I need to discard op-amp circuitry in instructable site or  just proceed with op-amp circuitry ?
confirm me.

Discard it. As I said in my answer, connect it direct to an analog input.

Thanks Majenko As you suggested I made a connection to A0 and I can see I was able to get the frequency values as my output, But I can see code is not stable at all, So could you suggest me is there any good reference code or any blog  which can help me out to get the frequency hz values as my output when I connect electret microphone to arduino.

What are you trying to get the frequency of?

Actually, I have one device on which I have to test the frequency of the sound  it generates at different operations like--success,failure..

@ferraro That really doesn't help.  What is the sound?  Most sound is made up of many different frequencies - even a sound that appears to be on one note.

I have builded the circuit as mentioned in instructables, Can see -1hz always as an output in serial, Could somebody help me what could be the reason

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


text:
How to use TimerOne while calculating time?
I'm trying to get warning with buzzer while I get same values on 3 seconds. But first warning doesn't wait 3 seconds. Second warning is correct. Code is attached. BlinkLED1() method is same BlinkLED2. Probably, I'm missing crowning touch. Can you help me?
Thanks in advance.
void initialsettings(double roll,double pitch){
  if(level==0){
    if(roll>=34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
        Timer1.attachInterrupt(blinkLED);
    } else{
         Timer1.stop();
         timerstatus=false;
         level=0;
    }

   }else if(level==1){
      if(roll<=-34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
         Timer1.attachInterrupt(blinkLED2);
      } else{
           Timer1.stop();
         timerstatus=false;

      }

  }else if(level==2){

  }
}

void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");
    //Serial.print("\n");

}

    Timer1.attachInterrupt(blinkLED);

...
void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");

Don't do serial prints inside an interrupt service routine (ISR).
Don't use delay() inside an ISR.
Don't turn interrupts on or off inside an ISR.
Variables shared between an ISR and the main code should be volatile (I can't see from your snippet whether they are or not).

Reference: Interrupts


text:
Wrong calculation UNO
I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes_SJoys, max value of 1023 on any axis) and example would be:
y = 500;
servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?
#include <Servo.h>

Servo servo;
int d2 = 2;
int a0 = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(d2);
}

void loop() {
  int y = analogRead(a0);
  Serial.print("y: "); Serial.println(y);

  servo.write(y * 180 / 1023);
  Serial.println(y * 180 / 1023);

  delay(100);
}

PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.

What you are experiencing is a common pitfall.
You are probably expecting floating point calculations, but what you are writing are only integer ones.
Try with:  y * 180. / 1023.   (notice the dots).
This will work only with constants.
To make it work with anything, use a cast:  y * 180 / (float) 1023
Happy hacking.

Awesome, this worked, thanks! (Just had to cast evertyhing)

Please select the answer as correct, if it helped.

One cast should be sufficient.

Oh, yea... But for some reason casting didn't work on 1023, but it did on 180. Weird.

The reason you're getting completely the wrong value (not just losing the decimal portion) is because of a problem called integer overflow.
Because the Arduino is an 8-bit device the default integer size is double that.  That means that an integer value can store 16 bits, and when signed that's -32768 to 32767.
Any calculations, unless you specify otherwise, have to fit into that range.  If you take your calculation step by step you will see how it works:
500 * 180 = 90,000

Represented in Hexadecimal (for ease of demonstration) 90,000 is 0x15F90.  That is 17 bits (4 bits per digit, the left hand is just one bit since it's only the value 1), and 17 is more than the maximum 16 allowed.  So we have to "overflow" that value and discard the lefthand-most digit to keep it at 16 bits.  So we end up with 0x5F90.
0x5F90 in decimal is 24464.  Now we divide that by 1023 and we get:
24464 / 1023 = 23.914

Because it's integers we have no decimal portion of it, so that just ends up as the 23 that you are seeing.
Solutions?  Change the data type.
As @IgorStoppa has pointed out you can use floating point values which gives you big values and the decimal portion.  As long as one value in your sum is floating point all the values will be. This is known as promotion.  There's numerous ways you can force floating values:

Represent your literals as a floating point value - that means adding a decimal place. You could have (as Igor shows) things like 1023., but I find that a little obscure.  It's better to explicitly show a decimal value since it's obvious what it is then, such as y * 180.0 / 1023.0.
Use a floating point literal suffix.  You can add certain letters after a number to describe what that number is.  f is for floating point: y * 180f / 1023f.

Floating point is quite heavy weight though and can cause your program to get bigger than you'd like.  If you're not interested in the decimal portion you can instead use long variables.  The best way to do that is with the long literal suffix L:  y * 180L / 1023L
Promotion means that all the variables are promoted to the size of the biggest variable (not greatest value, the variable with the largest storage space).  Long and Float are both 32 bits in size, so using either of those will force the other values to both be promoted to equivalent types.


text:
Beginner here. Which arduino revision should i buy?
I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there:

My questions

which arduino revision is this?
Does it matter which revision i    buy?

That looks like an early-version Uno, rather than an Uno R3 as shown below. (Image is from dxcdn.com and is one of the first few images in a google images for Uno R3 search.)

For a beginner, replacing a DIP ATMEGA328P may be a chip too far.  I suggest that rather than looking for an Uno with a replacable chip, get any Uno you like.
Also note that for beginning projects, it makes sense to use the same kind of Arduino – an Uno, a Mega, a Pro Mini, a Nano, etc. – as the guide you are following uses, so that you won't have to adapt any pin numbers and wiring pictures.  As you gain experience, it should become easy to adapt designs to different boards.

It looks very much like the R2 that I have here.

That looks like an UNO R2, the type with DIP micro controller (you can extract it and replace it with another one, in case of problems).
The R3 version is probably the best choice to get started.
You might want one that has a connector where this one has only the 3x2 empty pads on the top left (close to the vertical writing AREF).
Have a look on ebay/aliexpress/amazon. You can find it for as little as $5-$6. Just search for UNOR3, if you elect to buy this type.

Looks more like an R2 to me.

Whoops, true, it's R2, I'll fix it. But I still think the removable AVR is better than the SMD one.


text:
How to control 6 stepper motors with Arduino?
I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example DRV8834.
Is it possible?
Any suggestion for another type of motor driver?
We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?

Two questions: 1) Are you wanting unipolar or bipolar steppers? 2) What is the end result you actually want to achieve?

You can set the current using the potentiometer on the DRV8834 board. PWM doesn't make sense for stepper-motors. PWM only makes sense for regular DC motors. It seems more like you need to look into what motor you need for your application before deciding on the motor driver.

We already decided to use stepper motors. I have 6 bipolar steppers. I need just to move forward and backward 6 wires that are connected with the stepper motors by means of a simple mechanism. Do I have enough pin in Arduino for 6 motor drivers?

Your requirements are so close to typical 3d printer electronics that you could learn a lot from those designs, even if you end up having to create something of your own.

We can also be use easy driver for 6 stepper motor ... or if we want to many stepper motor control we can use there bit shift Resister 74HC595. for driver ULN20003 IC driver or l293d IC.

Yes it is possible, of course everything is possible!
These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).
For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).
M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.
Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.
Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is not moving. This is usually done from software (the driver does not known when it is time for a long period at stop).
The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. analogWrite())
drive this to 0, then start movements
once movements are finished, use analogWrite() and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.

You could create your own custom shield with an Arduino mega and 6 Stepper sticks
http://www.amazon.com/Hobbypower-StepStick-4-layer-DRV8825-Stepper/dp/B00NCSK6T2/ref=sr_1_1?ie=UTF8&qid=1455740571&sr=8-1&keywords=DRV8825
Here is a link to the stepper sticks I was talking about. To make this work you would need to be able to solder the breadboard together and set up the arduino to accept pins from the breadboard. You would also need a 12v power supply to give the motors power

Why the DRV8825 over the DRV8834?