text:
A question about resistance measurement with arduino
Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.
My questions are:

Is it possible?
If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

This simple example will show you how to measure the position. It uses a potentiometer with its ends connected to +5V and 0V, and you read the analog voltage at the "wiper" connection which is the centre on most potentiomenters. (To clarify - this method does not directly measure the resistance, a different arrangement would be used for that. But most potentiometer applications really just need the position.)

@Andy You can always just add a quick equation into your code to turn the voltage back into resistance, as long as you know the value of the pot you're using

@Hayman you're correct, if the overall resistance of the pot is known. But it's not entirely clear to me if the questioner wants to use a known pot in a circuit, or is trying to measure "resistance" of something in general. That's why I was being cautious :)

If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.
Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).
R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.
We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.
So we need to then provide a known resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

Current flows the same through all resistances connected in series
The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.
If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.
Here's the circuit I just described:

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.
Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:
Vout = 681 / 1024.0 * 5.0
     = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.
So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).
Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.
That's the long-hand version from a current-based perspective. However there is a short-cut.
Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.
From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.
For instance, the ratio formula:
Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)
When rearranged to get R2 gives us:
R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:
R2 = 10,000 * (1 / ((5 / 3.325) - 1))
   = 10,000 * (1 / (1.504) - 1)
   = 10,000 * (1 / 0.504)
   = 10,000 * 1.984
   = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).
You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.
Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a voltage follower with a very high (tens or hundreds of tera-ohms) impedance input.

Actually, the conversion factor is 1024, not 1023, according to the ATmega328P datasheet. Not that it makes a big difference though...

Put 5v into the ADC and you read 1023. 1023/10245 is not 5. 1023/10235 is 5.

@EdgarBonet If we're really 'nitpicking' then you could argue that the 5V isn't truly 5.0000, so you could say that using 5 is also incorrect. The way I've always known it is there are 1024 levels, as 0 is the first number that makes 1023 full scale does it not?

@Hayman You mean like I discuss on my blog?

That was an interesting read, I was trying to think how to accurately measure Vcc on board, didn't know you could do it that way. Now all my analog reads will be a bit more accurate

Put 5.01 V on the ADC and you read 1023. It's called saturation. @Hayman: I have no better alternative for the 5 V. It could be more or it could be less, but it is nominally 5 V, so I would write 5 V until I know better. But the Vcc has no influence on the resistance measurement anyway. And the conversion factor is nominally 1024: it could be 1023 like it could be 1025. The discrepancy between the real factor and 1024 is called gain error, and there is some tolerance on it. C.f. the datasheet.

Looks like the AVR's ADC uses lower-bound quantisation, so the highest value (1023) represents Vref - 1 LSB. Ergo 5V can never be measured unless you connect the VRef pin to more than 5V. For the AVR 1024 is then the correct value to use (calculations updated) though that may not be the case for other ADCs.

The question isn't explicitly clear, this answer is based on having a single known value pot and wishing to know its resistance at any one point rather than trying to find an unknown resistance entirely
You can't measure resistance directly. What you can do however is measure the voltage across a potentiometer.
There is a really good example provided by arduino which can be found here.
Now, it is possible to turn this into a resistance value with a little bit of editing to the code
int potPin = A0;    // Select the input pin for the potentiometer
int potR = 1000;    // This is your max potentiometer resistance in Ohms
int val = 0;        // Variable to store the value coming from the sensor
float voltage;      // This is the voltage from the wiper of the pot
float resistance;   // This is the resistance of the pot at the wiper

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

void loop() {
  val = analogRead(potPin);                      // Read the value from the pot wiper
  voltage = val * (5.0 / 1023.0);                // Convert the value into a voltage
  resistance = (voltage / 5.0) * potR;           // Convert the voltage into a resistance
  Serial.print("Voltage = ");
  Serial.print(voltage);                         // Print the voltage
  Serial.println("V");
  Serial.print("Resistance = ");
  Serial.print(resistance);                      // Print the resistance
  Serial.println("R");
  delay(1000);                                   // Add a little delay
}

As for your second question, it can do as high a resistance as you want. As long as you update the potR value in the code with the resistance of your pot (e.g. 1000000 for a 1MOhm pot)
I'm an electronics engineer by trade so my code could probably be cleaned up and made more efficient, this is just a starting point

Actually you can measure the resistance if and only if you have a reference resistor. Then you can measure the voltage between the reference resistor and the unknown resistor and then calculate the value of the unknown resistor.

Just nitpicking: the scale factor is 1024, not 1023.

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


text:
Powering multiple Arduino shields
To start, I am a software guy, so I am not too clued up on the electronics side of things. My question is: I have a number of Arduino shields and would like to power them with a portable power source, and therefore would like some advice on what to use without frying any electronics.
This is a list of the current equipment that will require power:

Arduino Mega 2560
SIM900 GPRS/GSM Shield
Sparkfun GPS Logger Shield
Sparkfun Wifi Shield - ESP8266

The shields will be stacked on top of each other.

Further links as I could not post them in the main question:
Arduino Mega,
SIM900

All the shields are 5v compatible. So no need to worry about 3.3v.
But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.

So I can simply attach a USB's red to the VIN and black to the GND, and then using any mobile phone power bank will provide enough current and voltage for all of the shields?
Wow, that seems super straightforward!

Yea.. please try this. They can deliver around 2A which will be sufficient. And interface on shield at a time. This will help yiu to resolve pin conflicts (same pins ued for multiple sheilds) good luck

*one shield at a time

What do you mean interface one shield at a time?

Add any of the shield first, and verify its workimg. Then connect the next shiled with this and test working. Simply stack one by one and test the working. Its not important , but will definitely help you to debug issues

@Calco Check your output rating of the mobile power pack you want to use. Some of them are limited to 500mA, you need enough current to supply all your boards in their respective worst case scenarios

DON'T CONNECT A 5V SUPPLY TO VIN - Vin goes through the 5V regulator - you will end up with about 4V instead of 5V. Instead connect the 5V supply direct to the 5V pin of the Arduino.

Ok, 5V pin NOT VIN! To confirm, if I picked up a product such as this, which says a 2.1A output current. My components list a maximum potential current draw of somewhere around 1500mA (SIM900: 500mA, GPS: 50mA, Wifi: 500mA, Arduino Mega: ?mA). So that gives me around 600mA spare, right?

Be careful relying on the color of the wire in a USB cable. Not every cable manufacturer follows this "standard" of colors.

Your stack will need quite a lot of current - most probably more than the Arduino can supply itself.
You will need to provide your own regulated 5V supply - either from a USB port (convenient if you are by a computer) - as long as it can supply more than 500mA of current (you need a Charging Downstream Port CDP for that) or from some external regulated 5V power supply, such as a mobile phone charger.
That 5V supply should be connected direct to the 5V pin of the Arduino's power header.
One thing to note: the headers themselves are only rated for up to 1A. If you need more than 1A throughout the entire stack it could be worth connecting the 5V power supply direct to the 5V pins of ALL the shields in the stack. Also do the same with the GND pins to the negative of the power supply. That way the high current doesn't need to flow through the pins themselves.

Yes.. Mjanco is right. Connect supply to 5V pin

source: Stack Exchange

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

sort: votes


text:
Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything
I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.
I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)
Here's my code so far:
Python side:
import serial
import time
import sys
import struct
ser = serial.Serial('COM3', 9600, timeout=0)
time.sleep(10)
while 1:
    print(ser.write(struct.pack('>B', 0)))
    time.sleep(2)
    print(1)
    sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  // put your setup code here, to run once:
  if (Serial) {
    Serial.end();
  }
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Godnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.listen();
  if (mySerial.available() > 0) {
    Serial.println("Hello User");
    Serial.println(mySerial.read());
  }
}

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.
Concerning my setup:
I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, ser.write() is replaced by ser.read(1), so that it reads one byte at a time. My system is Windows 7 (64 Bit).
Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.

What are you using to connect to the SoftwareSerial pins?

Some cables which came with the Genuino starter kit. RX is connected to TX and TX to RX (USB-Serial to Arduino), and ground to ground

"Some cables" isn't very descriptive. Which TX and RX pins are you connecting to?

Oh, ok. Well, I'm connecting to Pin 10 (RX) and Pin 11 (TX). Or do you mean how I connect on the other end?

OK, that makes more sense to me now.

A diagram of your setup would add a lot of clarity to your question. You checked that the USB-Serial port is COM3? What does the Python shell display when you run the script? To be clear, you connected the RX of the USB-Serial adapter to Arduino pin 11, and its TX to Arduino pin 10? Remove the 'timeout' argument in the 'ser' instantiation in the Python script and try it again.

I updated the description. And that's correct, COM3 is the port that's assigned to the USB-Serial converter. And Pin 10 (RX) is connected to TX at the USB side, while PIN 11 (TX) is connected to the RX at the USB side. Also, I've already received data from the Arduino, so I don't think it's a problem with the setup. I've also switched around the connection cables, but that doesn't solve it either

Does it work if you use the builtin hardware serial port of arduino? That way we could try to see if the problem is in the python part or the arduino part.

Ok, so I used hTerm for this, since this is probably better for debugging right now. When I send a signal from the Arduino Terminal to the Arduino via Serial(Works for both cases, virtual and builtin hardware serial port (Pin 0 (RX) and Pin 1 (TX), right?)), I get an answer in the seperate hTerm window. hTerm is connected to the USB-Serial Converter (COM7). However, if I'm sending data from hTerm or the ipython script to the Arduino, it doesn't respond. (The Arduino IDE terminal and hTerm show nothing). So, my best guess is that the USB-Serial Converter is broken...

@user25642 - Has the COM port changed number or have I misunderstood.  You program says COM3 yet you are connecting hTerm to COM7.

Well, I have two USB-Serial Converters, and I just tried them both. Sorry if that was confusing. And they both don't seem to work

What do you think should come out?
I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word.  You are using NULL, 0 to pack the structure.  When Serial.println() encounter a NULL it will assume that is the end of the string.  So you seem to be printing a zero byte string.
Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.
Does that make sense?

Hi, thanks for the reply. The struct pack has a syntax as follows:
The ">B" stands for a little endian byte that's gonna be packed, while the 0 is just an int that's packed into the byte. If I print it out, I get b'\x00' , which means that it's just an empty Byte. Is that what you meant with NULL, or is that another parameter?

And yes, I know that Serial.read(1) reads only one Byte at a time. That was just for testing purposes, as I was sending only one byte at a time. (To see if the connection works at all)
The pySerialAPI (http://pyserial.readthedocs.io/en/latest/pyserial_api.html)
states that write only takes one argument, the data. For python 3 it has to be formatted, which is why I'm using the struct package. For a 4 byte word, I would need to use something like ">BBBB", since a single B is just one byte.
I hope that clarifies what the code does a bit more :)

Generally, the struct package is used to format variables in python to certain standards. The problem is that a python int only takes up as much space as needed, so it will have a varying length, depending on the size of the number.

A variable length int, what a silly language :)  Yes thanks that clarifies a lot.  By NULL I do mean 0x00, so if that what you are getting its working.  If you print that as a string then it will seem like it is doing nothing.  Can you write (0x42) rather than packing it, you should get 0x42 on the Arduino or 'B'.

Ok, so I just used the pack-function to pack b"B" (Which is the bytes representation of a B. Python 3 is Unicode, so that should work) and send it instead of a 0. The Arduino still doesn't display anything.

Ok, so I c an send data from my python script to hTerm with virtual ports (I'm using com0com). I can also send data from hTerm to my script. But if I connect two USB-Serial Converters to each other, and connect one to hTerm and the other one to the python script, they don't communicate. So now I'll check the drivers and such for the USB-Serial Converters. (Even though they still blink up if they send something)

Don't use pack() that's what is causing the problem.  You are sending 0x00000043 which is Null, Null, Null B.  When the Arduino reads one byte it see Null, which means it prints nothing.  You need to send the single byte 0x43.  If you want or need to send a word then send 0x43000000.  This way it should work.
USB <-> Serial <-> Serial <-> USB will not work unless Serial <-> Serial has the RX and TX lines crossed over.  You don't have these lines crossed over because you can use both convertors to talk to the Arduino.

Can I ask why you are under the impression that pack() is making a 4 byte  number? If I use ">c", I'm packing the string to be its 1 byte character representation. I've checked that with the terminal. Only that one byte arrives, nothing else (I will also try to attach a screenshot of it in my question). And I'm not quite sure what you mean with "crossed over." I connected the TX of Serial-USB to the RX of the other Serial-USB, and vice versa. Is that what you were suggesting?

I noticed the NULL thing but I assumed Serial.println() would display '0', as though you ran Serial.println(0).

@user25642 - I was guessing what pack did, so thanks for correcting me.  Yes by "crossed over" I mean tx to rx and rx to tx.

When you run your python code, do you see the things you are sending on the screen there?
I think you need to be calling  ser.open().

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


text:
IDE 1.6.10 on LinuxMint 17.3 Cinnamon
When compiling I get the error
'as: unknown option »-mmcu=avr5« exit status 1'
I succeeded now using your piece of advise. Thank you so much.

Turn on verbose compilation and check the commands it is running.

I deleted the .arduino15 directory. Have I to delete also the directorie with all data of arduino?

Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15    (a.k.a. ~/.arduino15) and re-install 1.6.10.


text:
LED bar graph script not working
I have LED bar graph on pins 2-11. Eventually I want to use a voltage divider to figure out the amount of voltage left in a power supply. Currently, this script should set the number of LEDs on the bar graph based on round((v_actual/v_reference)*10), I am just using some placeholder numbers in the mean time to test this portion of the script e.g. v_actual of 5 and v_reference of 10. However, the convert variable keeps printing 0. I've checked that the other variables were passing and they are. What is the issue here?
#include <Wire.h>

int ledBarNum = 10;    // # of leds
int vref = 10;     // max voltage of power supply

void setup(){
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop() {

  ledBarSetup(5);
}

void ledBarSetup(int v) {

  // logic vref=8; vactual or v = 4; (4/8)*10 = 2
  // e.g. number of leds we need to light up to represent the total amt left

  Serial.println(v);
  Serial.println(vref);

  int convert = round((v/vref)*10);

  Serial.println(convert);

  ledBar(convert);

}

void ledBar(int n) {

  int startingPin = 2;

  for (int thisPin = 2; thisPin < ledBarNum; thisPin++) {

    if (thisPin <= n) {

      digitalWrite(thisPin, HIGH);

    } else {

      digitalWrite(thisPin, LOW);

    }

  }

}

In integer math, 5/10 is equal to 0.

Both v and vref are integers, which means that integer division will be performed. if v is ever less than vref then the result will be 0. Multiply first, then divide.

ah yes I suppose I should have looked up the diff between int and float in arduino. Was completely unaware of this. Doing the multiply then divide method! (v*10/vref)


text:
Set EEPROM from PC before program
I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.
All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?
Thanks for your help!
-sam

No, strings loaded from EEPROM take SRAM, not flash.

The simplest way would be to have two sketches.
One that will store all the strings into EEPROM.
After that you can upload the second actual sketch that uses the values stored in EEPROM.
You only need to upload the first sketch if any of the strings change.
There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.

I think here is a confusion about the three types of memory. EEPROM, FLASH and SRAM are completely separate. EEPROM is like your file storage. FLASH contains you program and static values. SRAM is the memory the program is working with.
Static values are loaded from FLASH into SRAM upon start unless you declare your static content not to load automatically by using the according Macro PROGMEM. In that case it does not eat up your SRAM until you manually read it from FLASH into SRAM. #include <avr/pgmspace.h> is used for this (pgmspace.h).
EEPROM is not loaded automatically and therefore must be read explicitly. #include <avr/eeprom.h> contains all the functionality (eeprom.h).
I'm not sure about the Arduino IDE but with avrdude you can program the EEPROM separately without having the values been predefined in your program. The third example in the AVRdude manual shows how to flash the program, eeprom and fuses at once.

thanks I'll check out the avrdude example! that may be what I am looking for

You don't need two sketches:
#include <avr/eeprom.h>

char e2str[] EEMEM = "Hello, world!\n";

void setup()
{
    Serial.begin(9600);
    uint8_t *ptr = reinterpret_cast<uint8_t *>(e2str);
    while (true)
    {
        char c = eeprom_read_byte(ptr++);
        if (c == '\0') break;
        Serial.write(c);
    }
}

void loop() {}

Compile (Sketch>Verify/Compile) the source above and you should find file named <sketch-name>.ino.eep in project's build directory.
For Arduino Nano, you can just run avrdude with -U eeprom:w:<path-to-eep-file>:i option before Sketch>Upload.
For Arduino Uno, however, you must first program it's EEPROM using programmer, since Optiboot doesn't support writing to EEPROM. Or you can burn it with Arduino Nano bootloader once (Tools>Board>Arduino Nano, Tools>Processor>ATmega328, Tools>Burn Bootloader) and then use the procedure for Arduino Nano. (Arduino Uno and Nano bootloaders use different baud rates).


text:
Problems with running multiple ESC
I've written a program which allows me to use my Arduino Uno to send a PWM to an Electronic Speed Controller. 5 seconds after startup the ESC is sent a config via PWM to signal the low to high PWM range to be used by the ESC. Then I can type into the Serial Monitor a single digit 0-9 to pick the PWM I want to send to my ESC. (n*2 = pwm)
This works great when running code for one ESC, but adding code for a second ESC causes significant issues (I only have one ESC plugged in). When I send a serial command to specify PWM rate, my ESC only receives the PWM change sometimes. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.
What's going on here?
Code
WorkingESCSoftware (main file of .eno)
#include <SoftwareServo.h>
#include "TestClass.h"

int val;    // variable to read the value from the analog pin
int stage = 0;

TestClass t, t2;

void setup()
{
  Serial.begin(115200);

  t = TestClass();
  t.setPin(3);
  t2 = TestClass();
  t2.setPin(5);
}

void loop()
{
  t.loop();
  t2.loop();
}

TestClass.h
class TestClass {
  private:
    SoftwareServo servo;
    bool _initialized = false;

    int PWM_MAX = 180;
    int PWM_HIGH = 170;
    int PWM_MEDIUM = 80;
    int PWM_LOW = 40;
    int PWM_OFF = 25; // has to be between esc config off (stop) and low (slow spin)
  public:
    TestClass();
    void setPin(int);
    void loop();
};

TestClass::TestClass() {
  Serial.println("cycle lipo power to esc");
}

void TestClass::setPin(int pin) {
  this->servo.attach(pin);
}

void TestClass::loop() {
  //  Serial.println("loop");

  // 5 seconds after power, send PWM range to ESC
  if(millis() > 5000 && this->_initialized == false) {
    this->_initialized = true;

    Serial.println("esc setup");
    this->servo.write(PWM_MAX);
    delay(5);
    this->servo.write(PWM_OFF);
    delay(5);
    Serial.println("esc ready");
  }

  char r = Serial.read();
  String inStr = String(r);
  if(r > -1) {
    Serial.print("serial in: ");
    Serial.println(inStr);
  }

  use h, m, l, o, or 0-9 to control PWM of ESC
  if(r <= -1) {
    // void
  } else if(inStr == "h") { // high
    Serial.print("HIGH: ");
    Serial.println(PWM_HIGH);
    this->servo.write(PWM_HIGH); // highest spinning (same as 160?)
  } else if(inStr == "m") { // medium
    Serial.print("MED: ");
    Serial.println(PWM_MEDIUM);
    this->servo.write(PWM_MEDIUM);
  } else if (inStr == "l") { // low
    Serial.print("LOW: ");
    Serial.println(PWM_LOW);
    this->servo.write(PWM_LOW);
  } else if (inStr == "o") {
    Serial.println("OFF");
    this->servo.write(PWM_OFF);
  } else if (inStr.toInt() >= 0 && inStr.toInt() <= 9) {
    int val = inStr.toInt() * 20;
    Serial.println(val);
    this->servo.write(val);
  }

//  SoftwareServo::refresh();
  this->servo.refresh();
}

You cannot do this simply by creating two instances of the class - you have to have a single instance of code which reads the serial port and dispatches complete commands to them.

You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.
Semiphoras are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.
In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.

Ah, so it's strictly an issue with how I'm handling Serial input? That makes sense. I'll move the serial read out to the main program loop and see how things go.

It may not be the only issue with your code.  But it is the most obvious and explains the undependable behavior.  I believe you will want to keep the serial read in the main loop.  Basically, you will want to  read the serial port, then pass the read data to the correct ESP instance. Then, I assume, you will keep repeating this pattern infinity.  So all this code would remain in the Arduino's loop() method.


text:
[Arduino UNO]Receive Serial Data from multiple sources
I have the following system:

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.
The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!
I can't use SoftwareSerial as I don't want any delay on master board!
I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.
So there are are my approaches:

Using MCP4725 I2C DAC for Compass, but what we do with GPS?
Using and intermediate Arduino UNO Chip?
On that chip I could use Software serial but how to transfer data to MASTER using only digital and analogic pins? Maybe using 10 pins to implement a parallel transfer?
Perhaps there is possible to convert Compass and GPS data to analogic then transfer to MASTER?

Anyway, what possibilities would I have to play around?

That was a lot of design restrictions. You might want to look at an I2C/SPI to UART bridge; http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/bridges/i2c-spi-slave-to-uart-irda-gpio-bridges:MC_51852

Maybe you should consider stepping away from Arduino boards and exploring the plethora of more capable boards that are out there - most of which can be programmed with the Arduino IDE using the Arduino API.

You chose the wrong part.  Lots of ARM Cortex parts have 3 UARTs, some of them have Arduino ports.

@ChrisStratton Only 3? I'm used to working with chips that have 6 UARTs... ;)

@Majenko : Can you guys provide some links please? It would be very usefully :)

This answer summarizes the possibilities:
1) HardwareSerial is always best.  You are using that for WiFi.
2) AltSoftSerial is the best software serial library, but it requires pins 8 & 9.  Very efficient and non-blocking!  Strongly recommended for the GPS connection.
3) NeoSWSerial is next best, but it supports only 9600, 19200 and 38400.  It is non-blocking on receive, so it could be used for the GPS connection.
4) SoftwareSerial is the worst.  :P  Not suitable for the GPS connection, as you have discovered.
I'll also mention my GPS library, NeoGPS.  It is smaller and faster than other libraries, and there are examples that show how to make it run during the RX character interrupt, saving even more time.  It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.

I think softserials are working based pinchange interrupt. This wont make you any significant delay i hop.Or you should go gps or wifi modules with SPI or IIC interface.

SoftwareSerial uses PCINT to start reception. During reception it blocks all other operations. That causes significant delays, especially at lower baud rates.


text:
Power ESP01 in forest
I want to do WiFi GeoChaching box. I'll use cheap ESP01, but problem is it will work in forest 24/7 in cycle of 1 min of work 5 in deep sleep and waiting for those who will find that.
How I can get power?

Either solar, or a very large battery. Or change the batteries every week. But I don't think Wifi is the best idea for this. I'd go with a Bluetooth Low Energy solution.

is there any cheap "board" like ESP01 with BT 4.0 and how big area i can cover?
Any idea what i can do in dark places like abonded tunels etc?

Why not just play Pokemon Go like the rest of the universe?

The BBC MicroBit might be a viable option - built in BLE.

What is your energy budget (how much energy - milliWatt Hours, or average current at what voltage - will be needed during the one minute on-time)? And how often are you willing to change its battery pack?

I think that in this case you will need multiple solutions for generating the power.

You need to know how much power you need.  This depends on you solution, I can't help there.
You need a backup battery, ideally one that doesn't mind constant trickle charge and deep discharge.  Sealed lead acid are probably the best.
Your battery must have enough power over a long enough time.
You need a power generator, wind, solar, water, chemical. And they should all have a common interface so you GeoCache is modular, so the GeoCaches can be plugged into any of the power sources, maybe even more than one source.

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue.
The battery, if SLA, is going to be a great big lump that could be dangerous if damaged.
The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.
Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.

Tell me about that chemical generator pleas @Matt

Petrol, coal, nuclear which are probably not very practical in this situation.  https://en.wikipedia.org/wiki/Electricity_generation


text:
Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload?
I've been asked to do a small project using an Ada BlueFruit board. It has a ATMega32U4. The 32U4 comes from the factory with a bootloader pre-installed. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?
Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.
It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

I don't really see what this is to do with the Arduino. You are asking about using a non-Arduino and not using the Arduino IDE.

Doesn't have anything to do with Arduino? The AdaFruit uses the Arduino software. https://learn.adafruit.com/adafruit-feather-32u4-basic-proto

I think you are talking about the "Bluefruit LE Micro" board.  Please note, Adafruit has several products called Bluefruit! So I think you are confusing people here.  And getting answers that may not be what you want.  Bottom line, (I think) you are "re-inventing the wheel".  If you go this alone (do bare-metal-programming or Atmel-boot-loader based development) you may have problems using the Adafruit Arduino libraries for their Bluetooth module soldered on this board.

The AdaFruit uses the Arduino software. - yes but the OP said s/he did not want to use the IDE. So the question was basically "how do I upload a .hex file to a ATMega32U4?".

I think the OP is giving up a lot of working-out-of-the-box code (Arduino-Adafruit Bluetooth libraries that I linked to) that he/she will have to port to the new IDE/SDK they pick.  ...  So, what the OP's question boils down to is can they use FLIP instead?  Maybe.  There's nothing special about the Arduino boot loader.  But it is likely you will have to program the Atmel with a real Atmel programmer or use a 2nd Arduino as discussed in this thread.

@st2000 I'm not giving up anything as far as I can tell. I don't see why I can't use those libraries. The libraries are written in cpp, nor ino. I do not want to burn the bootloader at all. I want to keep it intact. Why would I need to program the board when there's already a bootloader? Would EE be a better place to ask this question?

@NickGammon there's a bit more to it than that. You mentioned in your (updated) answer that I would need to ensure the memory doesn't overlap with the bootloader. I'd like to know how to do that. I'm happy to edit this question to clarify, but I need some help figuring out how to do that here.

To be honest, I'm am used to bare-metal programming.  And having done a boot loader and application embedded processor project, I know it is not trivial to keep the two separated.  That is, your worries about how the linker needs to be put together is not unfounded.  That said, I'm not sure the Atmel has the right type of resources to keep the Arduino boot loader in memory and still allow you to do what ever you want w.r.t. your application programming.  Keep in mind the boot loader is situated to run FIRST after processor reset.  How are you going to work around that?

Is the Arduino bootloader actually the one that came pre flashed from the factory?

You would have to ask Adafruit that.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". Is there anything I need to take into account when writing my application code?

The things you are talking about is generation of function prototypes, that sort of thing. It's nothing you really need to worry about.

For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

No, it would be crazy for the IDE to overwrite the bootloader. Then you wouldn't be able to use it again. In fact, to change the bootloader needs special hardware. You need to connect a programmer to the ICSP pins.

I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts

I doubt you need to worry about that, as long as you ensure that whatever tool you are using knows to allow room for the bootloader.

and if I can use the Flip tool to upload

I don't see why not. Or you could use the dfu-programmer as I describe in my post How to flash the USB chip on the Arduino Uno.

I should have been more explicit. I don't want want to use the Arduino "IDE". I can compile my C code to a hex. I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts and if I can use the Flip tool to upload.

See amended reply.

Arduino uses a different (second) bootloader, next to the DFU one that build into the 32u4.

I'd much rather continue writing straight AVR code in Atmel Studio.

The Arduino IDE allows you be lazy about #includes and forward references to functions, but it won't get in your way if you choose to write correct code.
I write standard C/C++ and switch back and forth between Eclipse (no over-helpful pre-processing) and the Arduino IDE. The Arduino IDE knows better; it just CYA (covers your assumptions :) in case you don't.


text:
How to configure 2nd Quadrature Decoder IO pins in Arduino IDE
I am working to read two quadrature encoders using a single Arduino DUE, as part of my summer vacations project. According to the following link
http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP, the SAM3X8E has 2 quadrature decoders in it. Now I am not being able to understand how can I initialize this second quadrature decoder. According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 Pg16 we have to first configure the IOPINS for QDEC1. I have to do that same task in Arduino IDE instead of Atmel Studio.
This is the code that I have found and works well to read encoder using QDEC0. However, I now need to read the encoder using the second quadrature decoder, whose input pins are TIOA6 , TIOB6 which correspond to Pin 5 and 4 of Arduino DUE. After reading the Atmel SAM3X datasheet, I think I should change "TC0" with "TC2" to make the second decoder work. However, this doesn't work. I think it does not work because channel 2 is busy in time base calculations.
In Application Note 5.52 QDEC Speed Measurement Mode point 2 says to Initialize TC0, TC1, TC2. If I wanted to used other encoder which timer instance will be used.
/*
** Quadrature Encoder on Arduino Due in "Speed Mode"
** Will not work on other Arduino types because of a specific hardware requirement.
**
** @bungle99 / 2014-02-28
**
** Many thanks to @Designservicecorp (notably post #32 and post #42) that gave me the base to work from.
**
** Uses *hardware* to do the heavy lifting of interpreting the Encoder output, which gives it significant
** advantage over other Arduino's for this use case. Eg many people have reported their Unos maxing out
** or skipping counts when interpretting high RPMs, whereas people using the Due in hardware mode have
** reported better success with high RPMs.
**
** This particular example puts the hardware into "Speed" mode, whereas other examples in this thread use
** "Position" mode (see posts 32, 42). The one example in the thread that attempts Speed calcs uses Position
** Mode and uses an interrupt on the Z Index axis to manually apply a time period (needed to caculate speed)
** on each rotation.
**
** This code below has been used in tests (using Lego NXT and a gear train for driving / comparison) to
** ~3,500 RPM with a 1,024 PPR Encoder (4 x 1,024 Edges). The Arduino didn't seem to struggle and the
** numbers (eg RPM) matched fairly closely with the Lego (eg as a sanity check, the calcs in the code look
** correct).
**
** I bought one of these encoders, which seems ok;
**
**   * http://proto-pic.co.uk/rotary-encoder-1024-p-r-quadrature/
**
** Great service from proto-pic. The encoder specs are officially
**
**   * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/E6B2Encoders.pdf
**
** But look an awful lot like this one too (which is easier to read)
**
**   * http://www.ia.omron.com/product/item/e6b27032r/index.html
**
** Note that this Encoder is rated at 5V min. I've successully powered it off the 5V Arduino pin header,
** and it doesn't work off the 3.3V one. At 5V, the outputs need to be run through some resistors to bring
** them into tolerance of the Arduino inputs.
**
** The inputs are 2 and 13 (and optionally A6 for the index).
**
** The test hardware (some Lego NXT servos and gear train) was unable to turn any faster (more gears
** stalled the servos) - eg the Arduino Due was not the limiting factor. At this speed, the Due Hardware
** is dealing with approx 238,000 edges per second.
**
** This example offloads the speed calculation onto the hardware, meaning no interrupt is required.
** In addition, the index is not required either, so it allows speeds to be seen even for rotations that
** don't pass the index marker (for example, slow rotations needing a speed before a complete rotation).
** That said, index is available if you want it and the docs suggest you can still use it (and others) as
** interrupt if you wish.
**
** NB There appears to be a myriad of features on the Chip that have not been touched. Eg you can still add
** interrupts to this code to do other things; eg passing the Z index, direction changes. There are also
** filters available if your encoder suffers from noise (eg vibrations). All this is available to play with
** another day :)
**
** Code appears to work, but no guarantees. Understand it. Test it. Feedback to the group. YMMV. Don't blame
** me if it doesn't work or expolodes!
*/

const int ENCODER_EDGES_PER_ROTATION = 3200;  // this depends on your encoder
const int ENCODER_SAMPLES_PER_SECOND = 10;        // this will need to be tuned depending on your use case...
const int LOOP_DELAY_MS = 1 * 1000;               // ... as will this (see comments in main code)

void setup() {

  Serial.begin(115200);
  delay(10);

  // Setup Quadrature Encoder
  // http://www.atmel.com/Images/doc11057.pdf
  // Section 37 p869
  // Section 37.6.14 p885
  // Section 37.6.14.2 p890 Position and Rotation Measurement
  // Section 37.6.14.5 p891 Speed Measurement (what this is about)

  REG_PMC_PCER0 = PMC_PCER0_PID27
                | PMC_PCER0_PID28
                | PMC_PCER0_PID29;

  // Setup a channel in waveform mode (eg an input into the encoder to trigger the time based sampling)
  // Note some of the choices here impact calculations below and if you change them, you need to change
  // the next section to suit.
  // Section 37.7.11 p906 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR2 = TC_CMR_TCCLKS_TIMER_CLOCK4
               | TC_CMR_WAVE
               | TC_CMR_ACPC_TOGGLE
               | TC_CMR_WAVSEL_UP_RC;

  // Now define the sample period, using the clock chosen above as the basis
  // Note that REG_TC0_CMR2 above is using CLOCK4; this is an 128 divisor. You need to change the
  // divisor below if you change the clock above. You could change the input clock and the RC mode to
  // suit your app (eg how many pulses are you  expecting - depends on encoder type
  // and slowest/normal/fastest rotation speed and what you want to do with the result).
  // Section 37.6.14.5 p891 notes you need to set this up, otherwise 0 comes out all the time :-)
  REG_TC0_RC2 = F_CPU / 128 / ENCODER_SAMPLES_PER_SECOND;

  // Setup a channel in capture mode
  // Section 37.7.10 p904 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR0 = TC_CMR_ABETRG
               | TC_CMR_LDRA_EDGE
               | TC_CMR_LDRB_EDGE
               | TC_CMR_ETRGEDG_EDGE
               | TC_CMR_CPCTRG;

  // Enable features, noting Speed not Position is chosen
  // Section 37.7.2 p895 (also refer to Section 37.6.14.5 p891 for detail of what to set)

// 37.7.2 TC Block Mode Register
  REG_TC0_BMR = TC_BMR_QDEN
              | TC_BMR_SPEEDEN
              | TC_BMR_EDGPHA; //Pg 896

/*EDGPHA: EDGe on PHA count mode
0: edges are detected on both PHA and PHB.
1: edges are detected on PHA only.*/

  // Set everything going
  REG_TC0_CCR0 = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1 = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2 = TC_CCR_CLKEN | TC_CCR_SWTRG;
}

void loop() {

  int iIndexCount = REG_TC0_CV1;  // Don't need this, but manual notes its available
  int iSpeedPPP = REG_TC0_RA0;    // This is what we're really after (speed in Pulses Per sample Period)

  // which we can convert to rps or rpm easily
  double dSpeedRPS = ((iSpeedPPP / (ENCODER_EDGES_PER_ROTATION * 1.0)) * ENCODER_SAMPLES_PER_SECOND);
  double dSpeedRPM =  dSpeedRPS * 60;

  Serial.print("Speed ppp: ");
  Serial.print(iSpeedPPP);
  Serial.print(", ");
  Serial.print("Speed rps: ");
  Serial.print(dSpeedRPS);
  Serial.print(", ");
  Serial.print("Speed rpm: ");
  Serial.print(dSpeedRPM);
  Serial.print(", ");
  Serial.print("Indexes: ");
  Serial.print(iIndexCount);
  Serial.print(". ");
  Serial.println();

  // Slow down the main loop noting the Encoder can update independently in the background (we're
  // effectively polling it to find out the latest and greatest info on each loop around).
  delay(LOOP_DELAY_MS);
}

Additionally I wanted to ask what is the difference between REG_TC0_CMR2 REG_TC0_CMR0 and REG_TC0_CMR1 ? Two of them are used in the above code.
Motor with Encoder I am using is:

TC blocks are pretty much identical (except TC1 doesn't have wired some signals to pins)
So you have to copy registers containing *_TC0_* = and replace TC0 to TC2.
Plus PC25 and PC24 should be set to its alternate function PIO_PERIPH_B. Something like this:
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

Also TC6, TC7 and TC8 clocks must be enabled by:
REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

And TC_CMR0..2 are Channel Mode Registers for one of three timers/counters in one TC block. Again, these are the same, but WAVE mode dependent.

Full configuration:
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

I have tried this , but it doesn't work. We are not getting any measurement....

@MasoodSalik also clocks must be enabled for channels 6-8. I though it's enabled for whole block by REG_PMC_PCER0 = PMC_PCER_PID29 but it was just third counter in TC0.

I have enabled all the clocks using
{ REG_PMC_PCER0 = PMC_PCER0_PID27                     | PMC_PCER0_PID28                     | PMC_PCER0_PID29                      | PMC_PCER0_PID30                       | PMC_PCER0_PID31;  REG_PMC_PCER1 = PMC_PCER1_PID32                     | PMC_PCER1_PID33                     | PMC_PCER1_PID34                      | PMC_PCER1_PID35; }
Now I am able to read QDEN1 from pin 4 and 5 . QDEN0 from pin 2 and 13. I am now reading clicks_per_revoluion using REG_TC2_CV0 and  REG_TC0_CV0. Now i am trying to measure the speed

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


text:
NodeMCU : Input pullup in A0
I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.
I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.
I am setting up the gpio in the setup method like this:
void setup(void){
    pinMode(sensorPin, INPUT_PULLUP);
    ...

And my sensorPin variable is declared in the beginning of the sketch
int sensorPin = A0;

Any ideas why when I read the value in the NodeMCU I don't get the same behaviour as in an Arduino board?

Probably because the nodemcu isn't an arduino. Internal pullups on analog pins is an AVR quirk that you cannot rely on being the same on other mcus.

Sorry if I am asking really basic questions, as I am starting in this field. The final objective is to put all the code inside an esp8266, as they have an analog gpio, and I was using the nodeMCU because it was easier for me to push the code there. Is there any way to get the right analog values I get in an arduino in a nodeMCU?

The obvious way is to use an external pullup. You can guarantee it will be there then.

Reading the documentation here (https://www.arduino.cc/en/Tutorial/DigitalPins) it says that they use a 20K resistor when we activate by software the pullup resistor. I will try to use an external pullup as you have suggested. Thank you!

You're confusing Arduino with NodeMCU. NodeMCU is a completely different beast running with a different chip from a different manufacturer with a different core architecture. You cannot use Arduino documentation for low-level things like chip internals when looking at a completely different chip. That's like using a Ford manual to try and fix your VW.

What I meant is that I was activating the pullup resistor in the arduino analog gpio, and to get a similar effect I need to put an external pullup resistor in the NodeMCU to get the same values as I am getting in the Arduino. Would this work or internally the analog gpios work so differently that I won't be able to get same behaviour?

Ah, gotcha. Yes, try and keep the same value as the internal one. However the internal one could be anywhere between around 10k to 50k or more.

I just wrote this blog post you might find interesting: https://hackingmajenkoblog.wordpress.com/2016/08/12/measuring-arduino-internal-pull-up-resistors/

As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:
 .
Special thanks to Majenko for his time and patience. Cheers!

Did you have to connect the R1 across VCC (5v)? Would it still work with a 3.33v pin or should I need a lower resister in that case?

@ΕГИІИО I used the 3.3 V pin in my final project with the nodeMCU so you should be good with the same resistance. Cheers!

@PayToPwn Alternatively, you can short the A0 pin with any digital pin and pull-up that digital pin. In fact, INPUT_PULLUP on analog input pin is very useful. In that way, you can connect photo-resistor directly to the analog pin and measure light intensity without external resistors.


text:
Sensirion library for SHT7x humidity sensor
I have following code (and it works great!) for SHT75 Sensirion sensor.

/*
 * Example code for SHT1x or SHT7x sensors demonstrating blocking calls
 * for temperature and humidity measurement in the setup routine and
 * non-blocking calls in the main loop.  The pin 13 LED is flashed as a
 * background task while temperature and humidity measurements are made.
 * In addition, the sensor may be placed in low resolution mode by
 * uncommenting the status register write call in setup().
 */

#include <Sensirion.h>

const uint8_t dataPin =  2;            // SHT serial data
const uint8_t sclkPin =  3;            // SHT serial clock
const uint8_t ledPin  = 13;            // Arduino built-in LED
const uint32_t TRHSTEP   = 3000UL;     // Sensor query period
const uint32_t BLINKSTEP =  250UL;     // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte shtState = 0;
byte ledState = 0;

unsigned long curMillis;               // Time interval tracking
unsigned long trhMillis = 0;
unsigned long blinkMillis = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait at least 11 ms before first cmd
//  sht.writeSR(LOW_RES);                // Set sensor to low resolution
  sht.measTemp(&rawData);              // Maps to: sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // Maps to: sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop()
{
  curMillis = millis();

  if (curMillis - blinkMillis >= BLINKSTEP) {    // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  switch (shtState) {
  case 0:
    if (curMillis - trhMillis >= TRHSTEP) {      // Start new temp/humi measurement?
      sht.meas(TEMP, &rawData, NONBLOCK);
      shtState++;
      trhMillis = curMillis;
    }
    break;
  case 1:
    if (sht.measRdy()) {                         // Process temperature measurement?
      temperature = sht.calcTemp(rawData);
      sht.meas(HUMI, &rawData, NONBLOCK);
      shtState++;
    }
    break;
  case 2:
    if (sht.measRdy()) {                         // Process humidity measurement?
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      shtState = 0;
      logData();
    }
    break;
  default:
    Serial.println("How did I get here?");
    break;
  }
}

void logData() {
  Serial.print("Temperature = ");   Serial.print(temperature);
  Serial.print(" C, Humidity = ");  Serial.print(humidity);
  Serial.print(" %, Dewpoint = ");  Serial.print(dewpoint);
  Serial.println(" C");
}

How can I extend it for two sensors (by using of another pins, of course)?

You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.

i.e. Sensirion sht2 = Sensirion(dataPin2, sclkPin2);

@Majenko Thank You! Your recommendation works very well! Many thanks to Gerben to.


text:
What is the variable pot exactly for in arduino sensors boards?
I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.
Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.

It's for sensitivity adjustment.

thanks, but I still don't get what is meant by sensitivity... if there is more light for example, while it higher the threshold to which the photoresistor will saturate or will it amplify the output ?


text:
External power supply?
I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).
Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.
My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?
It it necessary to use extra bypass capacitors in this case?

My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

It it necessary to use extra bypass capacitors in this case?

No.

Great. Are there specified limits as to what voltage range is acceptable to apply to the 5V pin, assuming the regulated supply is non ideal?

The datasheet for the ATmega32U4 seems to suggest VCC = 2.7V to 5.5V although I'm not sure on this.

That is correct. However at lower voltages you run into instability with the clock being too fast. Best stick to 4.5V - 5.5V.

Great, thank you for the practical answer.

authors: Павел Князькин


text:
Supplying power to arduino by 5V and 2A adapter
Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?
More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

Amps are not "forced" through a circuit like volts are. A closed circuit draws as much power (in amps) as it needs, so the only problem you could ever have is having too little current and not too much. Seeing as your module draws 200ma 2 amps to power it is plenty.

I'm not quite sure what the second half of your question is saying, but:

can i power my Arduino by 5 volt 2 amp adapter by connecting it through the usb port

Yes, you can.


text:
EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected
I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.
When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.
I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.
While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.
I am currently testing my code with a simple serial relay sketch, ESP on Serial3.
I have nothing else connected to ESP besides vcc, ch_pd, gnd, tx and Rx.
I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx
I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.
I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.
I appreciate any and all replies, and will provide any necessary clarification.
Thanks,
Vl4d

Just a couple of silly questions, but I'm not very much into ESP. 1) when is the LED supposed to turn off? 2) you put the voltage divider only on the ESP RX terminal (i.e. on the arduino TX), right?

A wiring diagram would help.
Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.

I would also check the ground on the components. All of the ground pins need to be connected together. IC's get flakey with grounding issues.


text:
How to connect Arduino to headphone jack?
I would like to connect a headphone jack to my Arduino and make it as an output. I mean I would simply send some simple beeps.
I know that there is a breadboard friendly headphone jack, but I don't know how to wire it. I really don't know if I can simply connect the Arduino to the headphone jack, or I will need some resistors, etc. Will I need some voltage measurements?
Also, can I do this simply by connecting the parts of the jack ( right, left, GND) to the Arduino?
So could you please help me with this?

This project connects the headphones directly to a digital pin.  Here is the schematic:

I would, however, be more cautious and add a limiting resistor.  The output of an Arduino pin should be limited to 20mA as stated here. So, using

V=I*R
5 = 0.02 * R
R = 5 / 0.02
R = 250ohms

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.
The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.

I had the same problem and here how I figured out a solution,
Assume your stereo jack is connected to the folowing pins;
Pin 9 = Left stereo
Pin 10 = Right stereo
GND = Ground
The solution relies on using arduinos inner circuitry.
Pin 9 and Pin 10 are our pins to control left and right stereo sounds.
We need a third pin which will be the main output source for stereo both(left and right) condition.
Say this pin be Pin8.
Connect Pin8 to Pin9 and Pin10 by two resistors of 1kOhm or similar depending on your sound level choice.
When you seet pin8 mode to OUTPUT, pin 9 and pin 10 modes to INPUT, and when you play a tone  at pin8 as tone(pin8,duration,frequency) will play stereo on the headphone.
On the other hand if pin9 is set to OUTPUT and pin10 set to INPUT, playing tone at pin8 will flow the current through right pin of the stereo jack, right sound.
Similarly if pin10 is set to OUTPUT and pin9 is set to INPUT,and tone played at the pin8 send the current through left stereo jack connected to pin9, left sound is played.
Hope this helps.


text:
Inexpensive way of connecting a lot of modules on a distance
I need to connect a lot (~100) of modules with a computer (Raspberry pi). The modules are based on Arduino micro and are very simple. They will be spread around, but for the two adjacent the distance would not be larger than 2 meters.
From time to time they receive information from the computer and also can send some data back. So bandwidth requirement is small.
My first idea was connecting them in one i2c network. It would be fine, except I have figured out that i2c is not good for a distances. Signal degrades and communication is unreliable if works in the first place.
Second idea is the nrf24 network (mash). But I am not sure how reliable communication is with them? Wired seams more reliable.
What would you recommend? It needs to be as cheap as possible, because of number of modules. Reliability of communication is important. The bandwidth requirement is very small (1Kbps is enough). Also modules are not battery powered so no need to be low power option.
What is the best way of doing this?
EDIT:
Network topology (it can be changed):

simulate this circuit – Schematic created using CircuitLab

I don't think I2C will necessarily be bad. You'd have to be a bit more considerate in applying it; like spreading the pull-up resistors and picking the correct values, and maybe do some termination to prevent ringing. Lowering the clock speed will also help. But I'm no expert here. You could read this paper. The first alternative to sprung to mind was RS485, which is pretty robust. PS what is the total length? Also how are they connected? All in a single line, or more like a tree?

There are lots of ways of doing that.  Wired can work if you do a daisy chain rather than a bus, but you do have to deal with wires.  Radio works too if you design your protocol well - you can get modules on-air compatible with the NRF24L01 for a dollar each.  You haven't specified the maximum distance from the pi to a node; if it is beyond expected radio range you do a mesh or forwarding scheme, at the cost of software complexity.  At a higher radio cost (~$10 in small quantities) there are also things like LoRa.

Yes, probably I2C could work, but still I am afraid it would be pretty unreliable. Or maybe I am too afraid. Maximum length is ~50m, so mesh would be needed. They would be connected like multiple rows connected in column (something like stretched star). Hope you understand. RS485 is only between two modules, no network? Need to daisy chain? I will read about it. LoRa looks too expensive (if could be avoided).

Added picture of network topology. Number of modules is larger, but this is basic idea.

Looks like RS485 is a good solution for wired communication over some distance. Which would you prefer nRf24 vs RS485?

nRF24-s are probably cheaper and easier to use than RS485 system.

What about reliability? Can nRf24 be sufficiently reliable. Do you have any experience with it?


text:
User-Agent question
I've seen a few different User-Agents used in demo sketches and am curious as to what the various User-Agent options are and how to determine which one to use.
For example...
User-Agent: Mozilla/4.0
User-Agent: Arduino/1.0
User-Agent: ESP8266
User-Agent: ArduinoWiFi/1.1
I've used Arduino/1.0 successfully with an Uno/WiFi101 but want to use an ESP8266 now.  Do I continue using Arduino/1.0 or switch to ESP8266 (Arduino IDE 1.6.5)?
When would someone use Mozilla?
Any guidance is appreciated.

You can use anything you like. It's used by the remote server to (try and) determine what browser you're using in order to give you the best visual experience. On an Arduino you really don't care about the visual experience. You don't even need to provide a User-Agent field, but it is courteous to do so.


text:
Ignore event until x minutes
I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.
Here is the code I come up with:
if (digitalRead(sensor_event)==HIGH)
  {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute > time_pushed+5)
                           time_set=0; // Unlock
                 }
               else
                 {
                        if (tm.Minute >= 55)
                          time_pushed=0;
                        else
                          time_pushed=tm.Minute; // Set global volatile min value

                        print("Sensor event");
                        time_set=1;
                 }
      }
  }

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.
The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).
Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.
Thanks

Use the millis() function instead if you can accomodate a rollover after 50 days.

Take a reading of millis() at the start time.
time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.

Assuming all three are unsigned values, if(current_time - start_time >= timeout), then rollover becomes irrelevant.

This is exactly what I looking for so the rollover never cause a problem, yes the device will run over 50 days. But in your example let's say the timeout is 1 minute 10000 mS. If current_time eg 9991512 and the start time 9990512 and lets say it overflows back from 9991512 -> 0000000 how is this helps me?

@catkillr: Arithmetic on unsigned long is performed modulo 2^32, so the difference current_time - start_time is always correct modulo 2^32 even if there is an overflow.

See http://www.gammon.com.au/millis for a detailed explanation of why this works.

Calculate target time, rollover if necessary and check if time is already passed that point. As long as you are checking the time multiple times per minute you shouldn't run into any issues.
if (digitalRead(sensor_event)==HIGH)
{

  if (RTC.read(tm)) {

          if(time_set)
            {
                   if (tm.Minute >= targettime)
                       time_set=0; // Unlock
             }
           else
             {
                    targettime=tm.Minute+5; // Set global volatile min value
                    targettime=targettime % 60;

                    print("Sensor event");
                    time_set=1;
             }
  }
}

The proper way to do that depends on whether the event is guaranteed to
happen at least once every 49.7 days. If this is the case then, as
Tom Carpenter suggested in a comment, you can just test for
now - last_event >= hold_time:
void loop()
{
    uint32_t now = millis();
    static uint32_t last_event = -hold_time;

    // Detect the event if it did not happen in the last five minutes.
    if (now - last_event >= hold_time
            && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        last_event = now;
    }
}

If you can have 49.7 days without a single event, then this approach
fails because last_event is ambiguous. The simplest solution is
probably to implement a state machine with only two states, as the event
detection is either “on hold” or it is not:
void loop()
{
    uint32_t now = millis();
    static bool on_hold;
    static uint32_t last_event;

    // Remove the hold after five minutes.
    if (on_hold && now - last_event >= hold_time) {
        on_hold = false;
    }

    // Detect the event.
    if (!on_hold && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        on_hold = true;
        last_event = now;
    }
}

Now I would want to insist on a specific point: in either approach
the millis() rollover is not an issue. The choice
between the first and the second approach depends solely on the maximum
time between the events, not on how long the program is meant to run.

Just to save a lot of headaches for everybody who wonders here and still have  a problem with this code:
uint32_t hold_time = 1*60*1000; // 1 minute will never work

uint32_t hold_time = 60000; // 1 minute will work

You must define the value as an EXACT number, not putting in multiplication and rely on the compiler to calculate it for you.
Probably because it's unsigned long and screws up something with the multiplication but with the first example you will be put on hold for days, maybe forever.

See Integer arithmetic and overflow. You can make it work by forcing the first item to be long: uint32_t hold_time = 1L*60*1000;

Don't bother with the RTC, just use millis().  Or just convert the time in hours/minutes/seconds to a single number in seconds (i.e. UNIX timestamp) and use that.  Then use these time comparison macros:
#define time_after(unknown, known) ((long)(known) - (long)(unknown) < 0)
#define time_before(unknown, known) ((long)(unknown) - (long)(known) < 0)
#define time_after_eq(unknown, known) ((long)(unknown) - (long)(known) >= 0)
#define time_before_eq(unknown, known) ((long)(known) - (long)(unknown) >= 0)

Then do something like this in your main loop, with a variable unsigned long sample_timer that's initialized to 0 at the start of your program:
if (time_after_eq(millis(), sample_timer))
{
    if (event)
    {
        sample_timer = millis() + 5*60*1000;
        // handle event...
    }
}

These time comparison macros will properly handle overflow if you use unsigned long for your timestamps.

−1 because this can lead to signed integer overflow, which is undefined behavior (i.e. a bug). But you can fix the macros by doing the subtraction before the cast.

Really? Then give the Linux kernel your down vote because that's where these macros came from: http://www.makelinux.net/books/lkd2/ch10lev1sec3

You found a bug in the Linux kernel. Congrats. But I would advise that, before reporting it, you make sure it hasn't already been fixed.

Update: I checked the current Linux kernel and, as I suspected, the bug has already been addressed. The fix, jiffies: Avoid undefined behavior from signed overflow, was committed by Paul E. McKenney three years ago. I urge you to read the commit message, as it explains in more detail what I wrote in my first comment. And notice that McKenney’s fix goes exactly along my suggestion: subtract before cast. Also, when you know you have posted a buggy answer, it is good practice to either fix it or delete it.

It's also good practice to comment before down voting.

I don't understand why you write that. Here is the only thing I found about commenting to explain a downvote, and it does in no way imply that the comment should be written before rather than right after the vote. I have tried to be constructive in all my comments, but this remark of yours sounds to me like pure angry rant.


text:
Delaying pushbutton input to microcontroller while it's busy processing I/O
I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.
Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.
Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.
I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?
Below is the simplified code
#include <SPI.h>
#include <Wire.h>
byte Input=1;
volatile byte Check=1;
volatile byte Output=1;

int j;
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 13;
////Pin connected to DS of 74HC595
int dataPin = 11;

int interruptPin=2;

int espPin=7;

char arduinoStatus[100]="\0";

 void pin_read(){

    for(j=0; j<50; j++)
    delayMicroseconds(1000);

    Check=1;
    for(j=0; j<8; j++){
      digitalWrite(latchPin, LOW);
      delayMicroseconds(500);

     SPI.transfer(Check);
     SPI.transfer(Output);

     digitalWrite(latchPin, HIGH);

     delayMicroseconds(500);
    if(digitalRead(interruptPin)==HIGH){
      //Serial.println(Check);

      if(bitRead(Output, j)==1)
      bitWrite(Output, j, 0);
      else
      bitWrite(Output, j, 1);
    }//dig check

    Check = Check<<1;

    }

    digitalWrite(latchPin, LOW);
    delayMicroseconds(500);
    SPI.transfer(255); //to push buttons
    SPI.transfer(Output); //to LEDs

    digitalWrite(latchPin, HIGH);
    delayMicroseconds(500);

}//pin_read

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(espPin, OUTPUT);
  pinMode(interruptPin, INPUT);//Input from buttons

  delay(1000);
  // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();
  SPI.transfer(255);
  SPI.transfer(255);
   //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);

    Serial.begin(115200);
    attachInterrupt(0, pin_read, RISING);

    Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
  Wire.onReceive(receiveEvent);

  Serial.println("Initialized...");
}

void loop() {
  Serial.println("Interrupting...");
 digitalWrite(espPin, HIGH);

 while(digitalRead(interruptPin)==HIGH){}
  delayMicroseconds(500);
 digitalWrite(espPin, LOW);
 delayMicroseconds(500);
 Serial.println("Done...");
Serial.print("Output:");
Serial.println(Output);
delay(3000);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  int i=0;
  Serial.println("received::");
  while (Wire.available()) { // loop through all
    char c = Wire.read(); // receive byte as a character
    arduinoStatus[i++]=c;

    Serial.print(c);         // print the character

  }
  arduinoStatus[i]='\0';
  Serial.println("###");
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Serial.println("Sending...");
  Wire.write("hello"); // respond with message of 6 bytes
  Wire.write(Output);
  Serial.println("Sent");
  // as expected by master
}

Sounds like you need to re-organize your software, in particular you probably need to use non-blocking I2C routines, at least if you have any peripherals that do clock-stretching.  Most likely you could get away with only servicing the user inputs between i2c words, but if clock-stretching is possible, they could take longer.

Are you using delay() functions in your code?

A question like this really needs to include your code.

@ChrisStratton,@Transistor: have tried to search for non blocking I2C library for Arduino, but it looks like many people are looking for the same and not finding., I have posted the simplified code I am using.

"When push button is clicked Arduino ISR is invoked via pin 2" - where is the ISR in your code?

attachInterrupt(0, pin_read, RISING);, pin_read function is right up the code.

@Bruce: The interrupt code is buried inside the compiler generated stuff on the Arduino sketch system. It's a pseudo C thing, kind of. You call a function to add something to the list of things they will call in some order in the actual code that is hidden away. This makes getting introduced to Arduino coding easy. But the problem then is that sketch programmers don't understand enough when it comes to the OP's question.

Without looking any further than the first delaymicroseconds() command I would say that that's where the trouble lies. The delay() functions are very handy for getting the beginner's first LED to blink and are a big problem after that. The problem is that the CPU is completely tied up during the delay and can't do anything else other than interrupts and you only have a limited supply of those. Your button press is missed.
You need to develop your own timers in the code and keep the main loop running constantly checking on each pass to see if the delay is complete.

What about polling the buttons periodically instead of using an interrupt?  If you check them every 10 ms or so, you should still be able to detect a button press reliably.  Connecting buttons to interrupt inputs is not necessarily the best idea due to contact bounce - this can cause a number of back-to-back interrupts.  My guess is that interrupts are being disabled during some part of your code and when the interrupt pin level changes during that period, it gets ignored.

Close. I would use the interrupt to set a flag. Then,  in the main loop, you process the button press whenever the loop comes back around.

That won't solve the problem if the interrupt is getting missed while interrupts are disabled.

True. I didn't notice anything disabling the interrupts though.


text:
Connecting Bluetooth module to Arduino Uno without RX/TX pins
Can I connect a Bluetooth module to usual digital pins, other than D0/D1 (RX/TX) pins as the shield is already using the D0 and D1 pins?
My Bluetooth module is an HC-05 MODULE.

Please be more specific. What Bluetooth module? What do you mean as in "0,1 pins" in comparison to "normal digital pins"? You mean IO pins from the Arduino instead of ICSP?

Google SoftwareSerial

Classic Arduinos use pins 0 and 1 for serial communication to the host computer, so it is problematic to connect a bluetooth module there anyway - it can be done, but basically means that programming the board and communicating with it by serial will not work (at least not reliably) until the interfering bluetooth module is removed or disabled.  For these boards you need to use a software serial instance to talk to the module, and you can put it on most any digital pins.
ATmega32u4 boards like the Leonardo do not have debug/programming on pins 0 and 1 but do have a hardware UART there, so those would be the best choice for a bluetooth module, but you can still use software serial.
The Arduino Mega has additional hardware serial pins that would be good choices, but you can use software serial.
Various ARM based boards with Arduino ports typically have additional hardware serial pins which you should use.  Software serial may or may not be an option on these (it's not that an implementation cannot exist, but that software serial is generally disadvantageous, so when a chip has more hardware UARTs that particular function may not be ported).

you can define pin and can use after defining int RX=any pin TX=any pin

Define any two PWM to RX/TX it will work do not use 0,1 it will give serial communication error...


text:
can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in
can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in

Unplug it from what? Your question is a bit vague. Do you mean unplug the USB cable from your PC? It won't "still work" unless you plug in a different power source.

like what type of of power source can use. i apologize for not being clear enough but i am new at this and don't even know where to start. i don't even have my equipment yet.  but thank you for being able to answer my question.

As st2000 said, the program resides in program memory (firmware if you like) and stays there until replaced, even with the power off. Whether it works "the same way" depends a bit on other factors (eg. do you use the USB for sending messages?) but in principle it should still work.

Once you compile and upload your arduino sketch and any libraries it uses, your code is stored in nonvolatile memory inside the processor. You can unplug your arduino and power it up later and it will run your code again with out any help from your computer.


text:
Problem with wrapping Adafruit Motor Controller function calls in a class
I'm working on an Arduino robot and I ran into a problem when reorganizing my code. I have an Adafruit Motor Shield v2.3 connected to an Arduino Uno. My robot can be controlled using a bluetooth connection (BlueSMIRF module) or it can be told to avoid obstacles using an ultra sonic range finder.
Everything worked fine and the robot moved nicely until I decided I wanted to organize the code better, so that my code for moving the robot would be in a separate class, my code for servo movement also in a class as well as my code for the logic for movement (received bluetooth command - do this, or avoid obstacles like so, etc.). Suddenly, none of the motors respond or just one.
I'm not sure if I have a problem with my C++ and passing pointers to my functions or what is going on...
Here is my main .ino file, its relevant parts, I left out stuff that concerns the bluetooth connection etc. And yes, I know the hardcoded include paths look ugly, I'll figure out what to do with includes at some point... :
// bluetoothRobot.ino

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <Servo.h>
#include <SonarSRF08.h>
#include <SoftwareSerial.h>
#include <MemoryFree.h>
#include "utility/Adafruit_PWMServoDriver.h"

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\AvoidObstacleController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MemoryFree-master\MemoryFree.h"

MotorController* motorController;

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

void setup()
{
    motorController->start(&AFMS, leftRearMotor, leftFrontMotor, rightFrontMotor, rightRearMotor);
    AFMS.begin();
}

void loop()
{
    if(bluetooth.available())  {
        char command = (char) bluetooth.read();

        if (controlMode == 2) {
            motorController->executeBluetoothCommand(command);
        }
    }
}

Here is my MotorController.h:
// MotorController.h

#ifndef MotorController_h
#define MotorController_h

#include "Arduino.h"
#include <Wire.h>
#include <Adafruit_MotorShield.h>

class MotorController {
    public:
      int executeBluetoothCommand(char command);
      void start(Adafruit_MotorShield *AFMS, Adafruit_DCMotor *rightRearMotor, Adafruit_DCMotor *leftRearMotor, Adafruit_DCMotor *rightFrontMotor, Adafruit_DCMotor *leftFrontMotor);
      void turnRight();
      void turnLeft();
      void moveForward();
      void moveBackward();
      void stopRobot();
      void setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed);
    private:
      Adafruit_MotorShield* AFMS;
      Adafruit_DCMotor* leftRearMotor;
      Adafruit_DCMotor* rightRearMotor;
      Adafruit_DCMotor* rightFrontMotor;
      Adafruit_DCMotor* leftFrontMotor;
  };

#endif

And here is MotorController.cpp:
// MotorController.cpp

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"

void MotorController::start(Adafruit_MotorShield *shield, Adafruit_DCMotor *rrm, Adafruit_DCMotor *lrm, Adafruit_DCMotor *rfm, Adafruit_DCMotor *lfm) {
      AFMS = shield;
      rightRearMotor = rrm;
      leftRearMotor = lrm;
      rightFrontMotor = rfm;
      leftFrontMotor = lfm;
      setRobotSpeed(80,80);
  }
int MotorController::executeBluetoothCommand(char command) {
        switch(command) {
            case 'F':
              moveForward();
              break;

            case 'B':
              moveBackward();
              break;

            case 'L':
              turnLeft();
              break;

            case 'R':
              turnRight();
              break;

            case 'S':
              stopRobot();
              break;

            /*case 'W':
              stopRobot();
              controlMode = 1;
              tiltServoAngle = 120;
              panServoAngle = 90;
              motorController.setPanAndTilt(panServoAngle, tiltServoAngle);
            */
            default:
              return -1;
              }
    return 0;

}
void MotorController::setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed) {
        leftFrontMotor->setSpeed(leftWheelsSpeed);
        leftRearMotor->setSpeed(leftWheelsSpeed);
        rightRearMotor->setSpeed(rightWheelsSpeed);
        rightFrontMotor->setSpeed(rightWheelsSpeed);
  }
void MotorController::moveForward() {

        setRobotSpeed(80,80);
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(FORWARD);
        leftFrontMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);

  }

void MotorController::moveBackward() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80,80);
  }

void MotorController::turnLeft() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80, 80);
  }

void MotorController::turnRight() {
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(FORWARD);
        setRobotSpeed(80, 80);

  }

void MotorController::stopRobot() {
        leftRearMotor->run(RELEASE);
        rightRearMotor->run(RELEASE);
        rightFrontMotor->run(RELEASE);
        leftFrontMotor->run(RELEASE);
  }

I used to have a constructor for MotorController with the Motor Shield library AFMS.begin() call in it and all. But this caused the Arduino to constantly reset for some reason. I coudn't understand why but I moved the motor configurations and call to begin() to my .ino file where the problem doesn't occur.
Problem: What happens with the code as it is, is which ever pointer to motor is passed last seems to work and that particular motor turns but the others won't. If I comment out the call to setRobotSpeed in MotorController::start, nothing happens with any motor even though speed is also set in the relevant functions.
As said, the robot worked fine when the code was in my .ino file. Although, for some reason I had to call the Motor Shield library's begin() function always before any other commands to motors. So it was called every time the user told the robot to move forward, move backward etc. Otherwise nothing happened with the motors. Now, if I add a call AFMS->run() to my MotorController.cpp, the Arduino starts to constantly reset...
Also, none of the other stuff (blueSMIRF, the range finder code etc.) should interfere since they were also there when it worked and I even commented out that stuff.
I'm baffled. Maybe its some silly mistake with my C++? Or is there really something weird going on here?
Any help would be much appreciated, I've spent hours trying to figure this thing out! Thanks in advance!

I would epecte your current code to not even compile because of the backslashes \ in the include paths. \ is a special character in C and C++ and is used to escape the next character and change its meaning. In include paths you should always use / even when working on Windows.

@jfpoilpret As I said in the question, it does work just fine except for the motors not turning and does compile. But I'll fix the paths, thanks!

The obvious issue in your current code is that motorController is a pointer to your class but I don't see any place it was instantiated properly.
Hence, it points anywhere the first time you use it, which can explain resets of the MCU.
Now, either you keep it as a pointer:
MotorController* motorController;

And then you instantiate it in place:
MotorController* motorController = new MotorController();

Or you can also instantiate it in setup() as first line (ie before it is used anywhere else):
void setup() {
    motorController = new MotorController();
    ...
}

However, for reasons discussed elsewhere on this site, I would not use dynamic allocation but I'd rather define motorController as an instance of MotorController instead of a pointer:
MotorController motorController;

Now everywhere you were using motorController->xxx you'll have to replace it it with motorController.xxx.
That should remove the most important bug of your current code (I can-'t tell if there are other issues but this one must be fixed in priority).

Omg... Thanks! I had a feeling this might be something really simple. I feel a bit silly now. I just spent like a day wondering. I guess what I am learning is to pay more attention to my C++ and what exactly I'm doing. I've done a lot of coding in Java and other languages, using Eclipse and these kinds of things still take me by surprise, when I don't get a warning and the code works except it doesn't!

One thing about instantiating classes before setup() is called is that init() (which you don't see) may undo all of your careful setup.
Your code starts:
Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

but these are constructed before setup(). And then you call MotorController::start() with those values. You haven't provided the code for AFMS::getMotor() - so it may be doing things internally that is undone by init().
Instead of creating the whole pointer, why not do this:
const byte rightRearMotor = 1;
const byte leftRearMotor = 2;
const byte rightFrontMotor = 3;
const byte leftFrontMotor = 4;

and then callig AFMS.getMotor() inside MotorController::start():
void MotorController::start(Adafruit_MotorShield *shield,
                            byte rrm, byte lrm, byte rfm, byte lfm) {
    AFMS = shield;
    rightRearMotor = AFMS.getMotor(rrm);
    leftRearMotor = AFMS.getMotor(lrm);
    rightFrontMotor = AFMS.getMotor(rfm);
    leftFrontMotor = AFMS.getMotor(lfm);
    setRobotSpeed(80,80);
}