message:
How is a 41KB char array filling up 256KB of program memory?

I have an array of 41,400 elements of type char, which I am trying to put in program memory on a Mega2560. It should have 256KB of flash memory, but when I try to compile my sketch, it says the size of the array is too large. Each char is one byte, so this array should be 41,400 bytes. I'm at a loss as to how this can be too big.

I have also tried using an array of byte variables (should be the same thing) with no success. This is the only variable going into program memory.

Here is the relevant line:

    const char Array[] PROGMEM = {0,19,21,25,27,27,27,29,24, ... };

I have included avr/pgmspace.h

Thanks in advance for any help.

body:
The limitation here is the data type of the index of the array. That is `int`, and on an 8-bit system an `int` can hold a value in the range -32768 to 32767.

That means the biggest index number an array can have is 32767.

That limit cannot be changed. You're stuck with it.

However, there are some tricks you can use to expand it.  One is to use a larger data type than `char` and pack your data into it.  For instance, using `unsigned int` as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.

Using unsigned long (32 bits) would double that again.

It is then up to you to work out how to get to the individual bytes. Using the `pgm_read_byte_*()` function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...


sender: user

sender: assistant

body:
You cannot have more than 32767 elements in one array. The reason is explained nicely by Majenko.

Solution for your problem is very simple, because you need only 41400 elements:

    class MyArray
    {
      static char array1[30000] = {...};
      static char array2[11400] = {...}; // rest

      public:
        char get(long index)
        {
          return index > 30000 ? array2[index - 30000] : array1[index];
        }

        char operator[] (long index)
        {
          return get(index);
        }
    };

So you can use two arrays and depending of the index choose which one to use. I think it is faster than using array of ints, because you need to have division (by two, so it can be only shift right by one) and than again shifting to get the char. Also it is easier to use because for ints you need first to pack values (two values in one int).

This is just example code, fit it to your needs.


message:
Problems With Fading Through Neopixel Colors

I have a 20x20 matrix of neopixel LED's. I have a certain set of LED's on in different places at different times. Each one is set to `mainColor`. Right now `mainColor` is just set to `strip.Color(r, g, b)` but I would like to have those color fade through the spectrum. I decided the easiest way would just be to do something like [this][1], and simply `return strip.Color(r, g, b)` to `mainColor`, then calling it to turn change the colors like so:

    strip.setPixelColor(pixelNumber, mainColor(5));

Here is the code for `mainColor`:
    int r;
    int g;
    int b = 255;
    int _r;
    int _g;
    int _b = 255;

    void Color (int FADESPEED)
    {
        // fade from blue to violet
        for (_r = 0; _r < 256; _r++) {
            r = _r;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
        // fade from violet to red
        for (_b = 255; _b > 0; _b--) {
            b = _b;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
        // fade from red to yellow
        for (_g = 0; _g < 256; _g++) {
            g = _g;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
        // fade from yellow to green
        for (_r = 255; _r > 0; _r--) {
            r = _r;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
        // fade from green to teal
        for (_b = 0; _b < 256; _b++) {
            b = _b;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
        // fade from teal to blue
        for (_g = 255; _g > 0; _g--) {
            g = _g;

            mainColor = strip.Color(r, g, b);
            Clock ();

            delay(FADESPEED);
        }
    }

This was good but it would only return `r, g, b` as it was on the last iteration of the last for loop, which obviously isn't what I want. But when I un-comment the `Serial.print's` the values were perfect. So then I put `return strip.Color(r, g, b)` into each for loop, however this only returns the first iteration of the first loop, which is also not what I want. Does anyone know how in the world I can `return strip.Color(r, g, b)` for every iteration of every for loop? Or if not, any alternatives that would work in this situation.

Thanks, Matthew
  [1]: https://learn.adafruit.com/rgb-led-strips/example-code

body:
There appears to be a number of problems with this code.

The variables only have scope with in this function and are not static.  So they will not survive from call to call.  Every time you call this function it will be like starting over.

Putting returns in the middle of code is not good coding practice.  It is very difficult to follow and hard to debug.  It would be best to arrange your code so that there is only 1 return at the end of the function.

This code (from Adafruit) only controls 1 RGB LED.  If you are to control 40 RGB LEDs all at different stages of color changing you would need 40 copies of this function.  This is not very efficient. Instead use this function to populate one lookup table with R G B data.  Then track 40 variables, one for each RGB LED.  Use the 40 variables to lookup a specific color combination in the lookup table for each of the 40 RGB LEDs.


message:
My Arduino Code isn't workig... and i just couldn't see any problems... thoughts?

>**There's Latest Update!**

So i'm working on a counter just for fun. How it works is when you press BUTTON1 the LED Lights up red, the buzzer beeps and the variable "counter" adds one to itself; After counting, you can press BUTTON2 then it will first show a transition animation then blink&beep while taking away the value of "counter". After the value of "counter" is less than 1, everything will start from the beginning.

But what actually happens is after the transition animation played, the LED and the buzzer just won't do any thing. I'm sure my physical connection is all correct, and the buttons are also pulled to ground with a resistor& a 100nf cap to prevent accidental pressing and vibration.

***
Note that I'm using a common anode RGB LED, so the anode pin is always HIGH but to light up individual colors i'll have to pull the cathode pins LOW (remember how electrons flow?)

>**Update**
@Tom Carpenter's latest answer still didn't solve the problem. I found the "else" function inside the "if" didn't work at all. So if i put the counter code inside the "else" function, the result would be none. But if i put the counter code in the "if" inside the primary "if", it would, again, count at clock speed, which results blinking forever!
**So is there anyway for the code to only count once per press&release cycle without losing?**

*The latest code:*
***
    #define RLED 10
    #define GLED 11
    #define BLED 12

    #define B1 4
    #define B2 5

    #define BZZ 3

    boolean OB1V;

    int counter;

    void setup() {

      pinMode(RLED, OUTPUT);
      pinMode(GLED, OUTPUT);
      pinMode(BLED, OUTPUT);

      pinMode(B1, INPUT);
      pinMode(B2, INPUT);

      pinMode(BZZ, OUTPUT);

      OB1V = digitalRead(B1);

    }

    void loop() {

      digitalWrite(RLED, HIGH);
      digitalWrite(GLED, HIGH);
      digitalWrite(BLED, HIGH);

      boolean NB1V = digitalRead(B1);

      if (NB1V != OB1V)
        {
          digitalWrite(RLED, LOW);
          digitalWrite(BZZ, HIGH);
          counter = 0;
        }
      else
        {
          digitalWrite(RLED, HIGH);
          digitalWrite(BZZ, LOW);
          counter = counter +1;
        }

      if ( digitalRead(B2) == HIGH )
        {
          digitalWrite(GLED, LOW);
          delay(300);
          digitalWrite(GLED, HIGH);
          digitalWrite(RLED, LOW);
          delay(300);
          digitalWrite(RLED, HIGH);
          digitalWrite(GLED, LOW);
          delay(300);
          digitalWrite(GLED, HIGH);
          digitalWrite(BLED, LOW);
          delay(100);
          digitalWrite(BLED, HIGH);
          delay(300);

          for ( counter; counter >= 1; counter -- )
            {
              digitalWrite(GLED, LOW);
              digitalWrite(BZZ, HIGH);
              delay(200);
              digitalWrite(GLED, HIGH);
              digitalWrite(BZZ, LOW);
              delay(200);
            }
        }
    }

***

body:
There are a number of problems with your code.  Your code does not deal with releasing the button.  Once you press B1 (assuming pressing B1 causes the input to go high) the counter (if correctly implemented (that is, it should be counter++)) would count up to 32K then start over at zero and count up again. Only stopping when you release B1.  The value of counter could be any number between 0 and 32K.

Working with buttons is difficult.   And the 100nF capacitor will do little to help.  It would be better if you learned how to debounce buttons and treat both the press and the release with equal importance.

There is an Arduino library called [Bounce][1] that will do some of this for you.  It will not help with your logical errors.  You still need to treat pressing and releasing the button with equal importance.  But it will help debounce button presses so your results will more closely match your expectation.

added later...

Your altered code will still not work.  You need to keep track of the state of the button in order to increment the counter by one for each button press.  You can call it edge detection code or state machine code.   But the code needs history to decide what to do next.  [Here][2] is an example of code which does this.

  [1]: http://playground.arduino.cc/Code/Bounce
  [2]: https://www.arduino.cc/en/Tutorial/StateChangeDetection


body:
Your problems come down to the fact that in the first code you are trying to do things on level sensitivity rather than edge sensitivity.

To try and understand the difference, some examples. Level sensitivity is effectively:

> Do 'x' **while** 'y'

In other words, if 'y' is true (for example an input is high), then keep doing 'x' (e.g. adding to a counter). This is what your code is doing at the moment, but not what you want it to be doing.

Edge sensitivity on the other hand is:

> Do 'x' **when** 'y changed'

In other words, when the state of 'y' changes (for example from true to false), then doing 'x' once.

The key difference between the two is the difference between 'while' and 'when'.

---

So how do you do edge sensitivity in code?

The way you have done it requires that the button be high and then low at exactly the right moment for the code to catch it. What happens if the button goes low at the end of the loop? Your code will miss the edge because at the start of the next loop it is not high, so doesn't get in to the first if statement.

Lets think about what 'changes' means. It means when the current value is different from the previous value. That implies that we need to keep track of what the previous value is in order to compare it to the current value. In fact that is exactly what we do:

    boolean oldButtonValue; //It would be better to use a static variable in loop, but for simplicity of the example lets use a global.

    void setup() {
        oldButtonValue = digitalRead(buttonPin); //This line is executed once to initialise the variable.
    }

    void loop() {

        //Each loop we read our current value
        boolean newButtonValue = digitalRead(buttonPin);

        //Has it changed?
        if (newButtonValue != oldButtonValue) {

            //Do something on edge.

        }

        //Update the old button value to match the new one (so we can check it again next loop
        oldButtonValue = newButtonValue;
    }

What this does is each loop it compares the current state of the button with the state of it from the previous loop. If the value changes, it does something.

---

Now the trouble with that code is it executes on *any* edge. That means that each time you press the button, it will run twice, once on press and again on release. So lets modify it slightly:

        ...

        //Has it changed?
        if (newButtonValue != oldButtonValue) {

            //Was it a rising edge?
            if (newButtonValue) {
                //If the button value is now high, it must have been a rising edge
            } else {
                //Otherwise it was a falling edge

            }
        }

        ...

The extra comparison allows us to determine whether it was a rising edge or a falling edge. So you can now do something either when the button is pressed, or when it is released (or both if you want).

---

You can have a second boolean variable to keep track of the old state for the second button. Then you use the same approach to do edge sensitivity detection approach for the second button.


message:
Slice byte-stream into bit pieces

I receive byte data from a RS-232 device with `Serial.read();`. Now I need to slice this down in bit-pieces:

- value1: 15bits
- value2: 7bits
- value3: 9bits
- value4: 12bits
- and so on

Data from the stream (switch them around for better understanding):

- Byte 1: 00101100 => 00110100 (least significant byte first)
- Byte 2: 10011011 => 11011001
- Byte 3: 00110011 => 11001100
- Byte 4: 11101000 => 00010111
- Byte 5: 01001100 => 00110010
- Byte 6: 01100111 => 11100110

Now the least significant is first.

- value1: `00110100.1101100[1]` => 6956
Need to cut of the last bit of the second byte
- value2: `1.110011[00]` => 103
Add the last bit of the second byte and cut off the last two bits of the third byte
- value3: `00.0001011[1]` => 416
Add the last two bits of the third byte and cut off the last bit of the fourth byte
- value4: `1.00110010.111[00110]` => 3737
Add the last bit of the fourth byte and cut off the last 5 bits of the fifth byte

Now the question: How do I realize this from programming side. I'm lost.

body:
**Note: This is an answer that OP originally edited into his question.**

---

I gather the data into an array of bytes `data[125]`.

Then I gather the relevant bytes per value and stack them together:

    long var = (data[4]<<8) + (data[3]);

I shift them so the relevant bytes start first

    var=var>>3;

Afterwards I mask them with the RIGHT mask

    var=var & 0xFF;

For the example in my question:

    long var = (data[1]<<8) + (data[0]); // I need two bytes
    var=var>>1; // shift them to the right one bit
    var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"


message:
How to use Arduino as RC Receiver

I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

[![enter image description here][1]][1]
Following is the image of my CC3D. The cable colors does not correspond to each other.

[![enter image description here][2]][2]

Which input cable should I connect to Arduino?
How should I connect black(ground) and red(5V) cables to Arduino:

  [1]: https://i.stack.imgur.com/TF0a8.png
  [2]: https://i.stack.imgur.com/Rre43.jpg

body:
EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..)
It seems it is not the question of op.

What you want is easy but there are some pitfalls.
I can make a long story short by these links

http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html

if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_25.html

I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib

And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.


message:
teensy as a keybooard throws error as keyboard input

I have a program (bash script) I wrote that is for stop motion animation. The script works perfectly, when I use any given keyboard on my laptop, and it works on other computers, as well.  So i wanted to add a controller, using a teensy, and the keyboard library. [source here:][1]

The teensy, set up as a keyboard, using one of the example codes, which I modified. The output appears correct: when I press any of the buttons, I get the expected output (asdw). But, the script throws an error, and exits anyhow, which means something else is being sent besides the key presses I desire.

So, WHY?
Here is the keyboard source for the teensy:

     /* Buttons to USB Keyboard Example

       You must select Keyboard from the "Tools > USB Type" menu

       This example code is in the public domain.
    */

    #include <Bounce.h>

    // Create Bounce objects for each button.  The Bounce object
    // automatically deals with contact chatter or "bounce", and
    // it makes detecting changes very simple.
    Bounce button0 = Bounce(0, 10);
    Bounce button1 = Bounce(1, 10);  // 10 = 10 ms debounce time
    Bounce button2 = Bounce(2, 10);  // which is appropriate for
    Bounce button3 = Bounce(3, 10);  // most mechanical pushbuttons
    Bounce button4 = Bounce(4, 10);
    Bounce button5 = Bounce(5, 10);  // if a button is too "sensitive"
    Bounce button6 = Bounce(6, 10);  // to rapid touch, you can
    Bounce button7 = Bounce(7, 10);  // increase this time.
    Bounce button8 = Bounce(8, 10);
    Bounce button9 = Bounce(9, 10);

    void setup() {
      pinMode(0, INPUT_PULLUP);
      pinMode(1, INPUT_PULLUP);
      pinMode(2, INPUT_PULLUP);
      pinMode(3, INPUT_PULLUP);
      pinMode(4, INPUT_PULLUP);
      pinMode(5, INPUT_PULLUP);
      pinMode(6, INPUT_PULLUP);  // Teensy++ LED, may need 1k resistor pullup
      pinMode(7, INPUT_PULLUP);
      pinMode(8, INPUT_PULLUP);
      pinMode(9, INPUT_PULLUP);
    }

    void loop() {
      // Update all the buttons.  There should not be any long
      // delays in loop(), so this runs repetitively at a rate
      // faster than the buttons could be pressed and released.
      button0.update();
      button1.update();
      button2.update();
      button3.update();
      button4.update();
      button5.update();
      button6.update();
      button7.update();
      button8.update();
      button9.update();

      // Check each button for "falling" edge.
      // Type a message on the Keyboard when each button presses
      // Update the Joystick buttons only upon changes.
      // falling = high (not pressed - voltage from pullup resistor)
      //           to low (pressed - button connects pin to ground)
      if (button0.fallingEdge()) {
        Keyboard.println("s");
      }
      if (button1.fallingEdge()) {
        Keyboard.println("d");
      }
      if (button2.fallingEdge()) {
        Keyboard.println("w");
      }
      if (button3.fallingEdge()) {
        Keyboard.println("a");
      }
    }

What should I do to just get the key presses (asdw) from the teensy as if it were a plain old keyboard.

  [1]: https://ghostbin.com/paste/pwzwm

body: Ok I figured it out. The code includes "keyboard.println". I should use "keyboard.print instead", to properly simulate keyboard presses. the newline is what was screwing it up.


body: You are calling Keyboard.println() which sends the character string followed by a new line.  If you want to emulate a keyboard you should only use Keyboard.print() which only sends the character string with no new line.


message:
Adafruit GPS module with SoftwareSerial affecting servo signals

I'm having a bit of an odd problem here. I'm programming a self-built quadcopter using an Arduino Uno for control. One of the sensor's that I'm using is [Adafruit's GPS breakout](https://www.adafruit.com/products/746). The motors are controlled with electronic speed controllers (ESCs) that controlled identically to normal servo motors. Everything is connected together with [a custom Arduino shield](https://123d.circuits.io/circuits/1150668-quadcopter-electronics-shield-v2). The GPS is using SoftwareSerial on pins 3 and 4, and the ESCs are connected on pins 5-8. Most of the GPS code is directly copied from [Adafruit's documentation](https://github.com/adafruit/Adafruit_GPS/blob/master/examples/echo/echo.pde).

What I've found is that even when the throttle is held steady (at any power level), the motors experience quick bursts of power far beyond normal whenever there is communication between the GPS module and the Arduino. For example, the GPS updates on 1Hz intervals and so the motors get a burst of speed about every second. Has anyone else experienced something like this or could someone at least point me in the right direction?

Here's an abbreviated version of the code that I'm currently using:

    #include <Servo.h>
    #include <Wire.h>
    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    Servo ESC1;
    Servo ESC2;
    Servo ESC3;
    Servo ESC4;
    const int maxThrottle = 2000;
    const int minThrottle = 1000;

    SoftwareSerial softwareSerial(4, 3);
    Adafruit_GPS GPS(&softwareSerial);
    // Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
    // Set to 'true' if you want to debug and listen to the raw GPS sentences.
    #define GPSECHO false
    bool usingInterrupt = false;
    uint32_t timer = millis();

    void setup() {
        ESC1.attach(5);
        ESC2.attach(8);
        ESC3.attach(6);
        ESC4.attach(7);
        setThrottleAll(minThrottle);

        GPS.begin(9600);
        GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
        GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
        GPS.sendCommand(PGCMD_ANTENNA);
        useInterrupt(true);
    }
    int throttleCommand = 20;
    void loop() {
        // Map throttle command percentage to raw throttle values that are sent to the ESCs
        int throttle = map(throttleCommand, 0, 100, minThrottle, maxThrottle);
        setThrottle(1, throttle);
        setThrottle(2, throttle);
        setThrottle(3, throttle);
        setThrottle(4, throttle);
    }

    // GPS interrupt
    SIGNAL(TIMER0_COMPA_vect) {
        char c = GPS.read();
        // if you want to debug, this is a good time to do it!
        #ifdef UDR0
         if (GPSECHO)
                if (c) UDR0 = c;
                    // writing direct to UDR0 is much much faster than Serial.print
                    // but only one character can be written at a time.
        #endif
    }
    void useInterrupt(boolean v) {
        if (v) {
            // Timer0 is already used for millis() - we'll just interrupt somewhere
            // in the middle and call the "Compare A" function above
            OCR0A = 0xAF;
            TIMSK0 |= _BV(OCIE0A);
            usingInterrupt = true;
        }
        else {
            // do not call the interrupt function COMPA anymore
            TIMSK0 &= ~_BV(OCIE0A);
            usingInterrupt = false;
        }
    }

    void setThrottleAll(int throttle) {
     setThrottle(1, throttle);
     setThrottle(2, throttle);
     setThrottle(3, throttle);
     setThrottle(4, throttle);
    }
    void setThrottle(int index, int throttle) {
     if (index == 1)
      ESC1.writeMicroseconds(throttle);
     if (index == 2)
      ESC2.writeMicroseconds(throttle);
     if (index == 3)
      ESC3.writeMicroseconds(throttle);
     if (index == 4)
      ESC4.writeMicroseconds(throttle);
    }

body:
The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit_GPS), and your program structure is based on the awful Adafruit_GPS example.

The good news is that there are much better alternatives: [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) and [NeoGPS](https://github.com/SlashDevin/NeoGPS).  Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos.  It can be an "interesting challenge" or a "beginner's nightmare."

Suggestions:

**1)** Consider using the HardwareSerial object, `Serial`, for the GPS interface.  Your excerpt does not show what `Serial` is currently used for, but if it's debug print statements... don't.  Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC).  This would have a tremendous impact.

**2)** If you *really really* can't use `Serial` for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded `SoftwareSerial`.  Next best is NeoSWSerial on any pins, including 4&3 that you are using now.  There is absolutely no reason to shoot yourself in the foot with `SoftwareSerial`.

**3)** As other's have commented, use HW PWM... let the machine do the work for you.

**4)** Consider using the faster and smaller NeoGPS library.  And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient.  The Adafruit_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a `SoftwareSerial` interrupt... that was on for the entire character time of ~1ms.  What a phenomenal waste!

**5)** Use interrupt-driven GPS parsing.  All three Neo__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters *during* the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow).  And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete.  This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with `strcmp` and `strchr`.  Ugh.  No, I meant to say UGH!

**6)** NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.

It's definitely a tight squeeze.  Either reallocate your pins and use better libraries, or get a bigger hammer.      :-)


message:
Looking for a wireless soil moisture sensor

I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?

body: The project is very much possible but it will be easier if you attach the moisture sensor directly to the arduino and add a wifi shield or a bluetooth shield to the arduino itself and make it communicate with computer or phone. You could also program the arduino to directly water the plants if it finds that they dont have much moisture. You will rarely find a sensor that transmits data wirelessly and still be economically feasible. The Sparkfun SEN-13322 moisture sensor is good for the purpose but again connect it to arduino direclty.


message:
Why is timer0 the fastest timer in the arduino?

In the [documentation][1], it shows that the higher  frequency that can be reached with an Arduino UNO for and 8bits PWM is using timer0  with the pre-scaler  set at 1. That  gives a Fs of 62500 Hz, but why is that so?

  [1]: http://playground.arduino.cc/Main/TimerPWMCheatsheet

I understand the Prescaler is dividing the frequency, but why it does start at 62500 Hz and  timer1 and timer2 have as maximum 31372 Hz.

body:
Timers 1 and 2 are configured by the Arduino core library to run the so
called “_phase correct PWM_” mode. In this mode, the timers count
forward from 0 to 255, and then they count backwards to zero. Timer 0 is
configured by the same library in “_fast PWM_” mode, where it counts
from 0 to 255 and then overflows back to zero in a single timer cycle.

You can, if you want, configure timers 1 and 2 in fast PWM mode. For
doing this, you will have to access their I/O registers directly. C.f.
the datasheet of the relevant microcontroller for details.

A couple of links:

* the [datasheet of the
  ATmega328P](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)
  microcontroller describes all the possible configurations of the
  timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
* the source code of the [Arduino init()
  function](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L284)
  to see how Arduino core configures them.


message:
How to connect a phone's camera to an Arduino?

I would like to ask how to connect my phone's camera to an Arduino, just like it is done in this [this video][1]. Is anyone familiar with [this application][2] they are using?

  [1]: https://www.youtube.com/watch?v=vkvkfcqEUkk
  [2]: https://www.youtube.com/watch?v=xan3j-TiNsw

body: Normally I would say that the phone is some kind of converting image to serial data and sending it to arduino via serial port. But there is no cables on the phone in the video. It is communicating wirelessly. But I don't think that vehicle is atonoumus?  The phone should be transfering image data via ethernet (wifi) and the user controls it. The reason I don't think that's an atonoumus is because you can't simply process that image stream with an arduino it would be a enormous process for arduino's little chip. They must be processing it on a computer. Either two ways the phone is talking to another processor. Not the arduino. Maybe if you tell what you want to do spesificly I might help you instead of trying to figure out this video :))  EDIT: ***it could also be a Bluetooth connection :))***


body:
That [video][1] shows a Bluetooth connection between the smartphone and the Arduino.

(A USB connection between the smartphone and the Arduino might be better in some ways).

details
-------------

If you want more information after watching a video like this, click the "show more" button underneath the video to see the details.
Those details clearly say "The Nexus S device connects to the IOIO board via Bluetooth, and uses the smartphone's camera in conjunction with OpenCV and the external IR sensors to control the vehicle."
Those details also include a link to
"Android Based Robotics".

The OpenCV image processing software runs on the smartphone. In this autonomous application, the image data never leaves the smartphone. The software on the smartphone reduces the image data to two integers -- the X,Y pixel location of the center of the green ball.

The Arduino and the Bluetooth link can easily handle a few integers at over 200 Hz. Neither one is suitable for handling live video data.

The Arduino could probably act as the controller.
The camera could send the X,Y pixel location of the green ball to the Arduino; while the Arduino collects all the other sensor data; then the Arduino could use that to decide what to do; then send the appropriate control signals to the motor drivers.

However, in this autonomous toy car it appears that the the smart phone acts as a controller.
The Arduino collects all the other sensor data, forwards that data to the smartphone; then software on the smart phone takes that data and the X,Y pixel location of the green ball; then the smartphone decides what motors need to turn; then the smartphone sends the appropriate commands to the Arduino, and the Arduino demultiplexes those commands to the motor drivers.

For even more details on building robots using smartphones and Arduino, see

* "Android Based Robotics" ( http://www.socsci.uci.edu/~jkrichma/ABR/ ).

* The Tinkernut video
"DIY Smartphone Controlled RC Car" ( https://www.youtube.com/watch?v=xsJ7176fLNw )
goes into more details of how to connect a smartphone to an Arduino via Bluetooth.

* Android Based Robotics: ground robot manual
( https://groups.google.com/forum/#!topic/android-based-robotics/_H8Zmvbxx-M )

* "Simple RC car for beginners (Android control via Bluetooth)"
( http://solderer.tv/cxemcar/ ) ( via http://english.cxem.net/ ).

* [Communicate with Your Arduino Through Android][2] (using USB cable)
* [ArduinoCommander][3]:
"Control your Arduino board from your Android device over Bluetooth, Ethernet or USB"

  [1]: https://www.youtube.com/watch?v=vkvkfcqEUkk
  [2]: http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/
  [3]: http://www.arduinocommander.info/


message:
Interrupt numbering

I'm using an Arduino Mega and four of its interrupts. Each interrupt is only used to start/stop a timer, depending if it's rising or falling, so effectively runs the same function. Does anyone know if theres a way to differentiate between which interrupt has been triggered? This way I can attach them all to the same ISR and just start/stop different timers.

Thanks,
Shaun

body:
Assuming that by "Mega" you mean the Mega 2560, see sections 15.2.4 and 15.2.5 of the 2/2014 [datasheet][1] referring to the External Interrupt Flags and Pin Change Interrupt flags:

> When an edge or logic change on the INT7:0 pin triggers an interrupt
> request, INTF7:0 becomes set (one). If the I-bit in SREG and the
> corresponding interrupt enable bit, INT7:0 in EIMSK, are set (one),
> the MCU will jump to the interrupt vector. The flag is cleared when
> the interrupt routine is executed. Alternatively, the flag can be
> cleared by writing a logical one to it. These flags are always cleared
> when INT7:0 are configured as level interrupt.

It is not clear from the above when specifically "The flag is cleared when the interrupt routine is executed" happens. It wouldn't be much use if it happened on ISR entry so I'll take a guess that it happens on return from interrupt, in which case the flags would be available to read in the ISR. An experiment would be in order, here. These flag registers are known to the compiler as EIFR and PCIFR, respectively.

  [1]: http://www.atmel.com/devices/ATMEGA2560.aspx?tab=documents


body:
The only sure-fire way of knowing which interrupt triggered your ISR is to examine the GPIO pin that the interrupt is associated with.

You need to use CHANGE interrupts so that you can keep track of the state of the pins - both HIGH and LOW.  When you get an interrupt and read all the GPIO pins you have tied to the ISR you can then compare their values to the previously stored values. Any pins that have changed since the last ISR (or a pre-defined initial state) can be processed and handled accordingly.

Yes, it adds a certain amount of overhead to your code, and using `digitalRead()` may not be the most efficient way of doing it. Instead you may want to use direct port access to read the pin's state directly.


message:
can homemade arduino be powered up with battery?

I am new to arduino. It is costly for me to buy an arduino uno board. Therefore I am going to make a Arduino with breadboard at my home. I also want to make my Arduino portable. Arduino Uno boards can be powered up with battery. But can I do so with my homemade Arduino? If it is possible, what things need to be included in my homemade Arduino?

body:
Yes you can power it from a battery, as long as you add a 5V regulator to your board.  You might get strange behaviour when the battery is running low.

These links all tell you what you need to build the board, good luck.

https://www.arduino.cc/en/Main/Standalone

http://www.instructables.com/id/How-to-make-your-own-Arduino-board/

http://www.instructables.com/id/DIY-Arduino-or-The-DIY-Duino/


body:
First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.

You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.

[![Typical fixed voltage circuit][1]][1]

  [1]: https://i.stack.imgur.com/Apegk.png


body:
I mostly use two AA batteries to power my 'standalone' ATMega328s. One of the downsides of this, is that you can't run the ATMega at 16Mhz, but only at 8Mhz. I don't mind that, as running at a slower speed reduces the current usage.

You could use 3 AA batteries, or 4 rechargeable AA batteries, instead to get a voltage that is closer to 5V

To get your circuit to run for more than a couple of days, you have to implement ways of reducing the current consumption. One of the first things would be to put the processor into sleep mode.


body:
You can use 9 Volt batteries to power most Arduino Boards.  For instance the Mega 2560 has a rated Vin range of 7 to 12 Volts.  A car battery can be used for longer life, although not nearly as portable as a 9 Volt one with a clip.  I'd recommend a common 7809 Positive Voltage Regulator TO-220 between a car battery charged using a car alternator and an Arduino board though, because the Voltage may vary quite a bit above the 12 V maximum.

I've used batteries with microprocessors for years for various embedded applications where access to AC is inconvenient, impractical, or nearly impossible.

The Mega page on the Arduino site explicitly permits battery power 1.

**Helpful Guidelines**

Here are some important criteria to meet.

 - The Voltage is within the published range for the Arduino model you are using
 - The positive of the battery supply connected to Vin (NOT any of the other power pins)
 - The negative of the battery supply is connected to Gnd
 - Critical applications don't run under the assumption that the battery will never drop below the minimum of the published supply range
 - The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

**Connection Safety Using Plug and Jack**

If you are connecting and disconnecting the Arduino from your battery frequently or you just want .

See the Power section of the pageto make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack 2.  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.

**Battery Use in Robotics and Flight Control**

A 9V battery will eventually drop in Voltage below the rated minimum, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 3.

Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 4 has a Brown-Out Detection feature 5.

A simpler approach for critical applications is a resistor divider on an analog input is another related approach.

.....

*[1] See the Power section of this page https://www.arduino.cc/en/Main/ArduinoBoardMega*

*[2] Information about compatible plugs is at http://forum.arduino.cc/index.php?topic=4892.0.*

*[3] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel (See https://electronics.stackexchange.com/questions/177204/will-connecting-two-batteries-in-parallel-increase-current-drawn-in-simple-led-c and http://www.zbattery.com/Connecting-Batteries-in-Series-or-Parallel).*

*[4] http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf*

*[5] The Atmel CPU for the Due and other boards have under-voltage detection too.*


body:
You can also use two 18650 batteries as they have a higher charge capacity

Each battery is about 3.7-4.2 V

That would be perfect for arduino....


message:
Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature

I'm trying to program an Attiny85 chip using an Arduino Uno as an ISP following this two tutorials: [Instructables: Program an ATtiny With Arduino][1] and [Programming an ATtiny w/ Arduino 1.6 (or 1.0)][2] but every time I try to upload the sketch I get this error message:

         avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I have tried different Arduino boards/changing port and different ATtiny chips but the results are all the same. I have also checked the wiring multiple times and it seems to be correct.

This is the full error message (on verbose mode):

         avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM7
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          2    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

         avrdude: AVR device initialized and ready to accept instructions

         Reading | ################################################## | 100% 0.05s

         avrdude: Device signature = 0x000000 (retrying)

         Reading | ################################################## | 100% 0.05s

         avrdude: Device signature = 0x000000 (retrying)

         Reading | ################################################## | 100% 0.05s

         avrdude: Device signature = 0x000000
         avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

         avrdude done.  Thank you.

  [1]: http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/
  [2]: http://highlowtech.org/?p=1695

body:
Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".

In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).

In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.

You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.

And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.


message:
Split Power supply in voltage and gnd?

I am new to electronics and arduino in general. I need to split a power supply in gnd and voltage. Basically, the power supply has one single wire (with the voltage and the gnd passing through it i think), and I need them to be separated. Sorry if this is a noob question, but I am really new to this whole thing.

body:
Do you have a image of this? Logically, and as far as I know, One wire will not carry both GND and Positive.

Are you talking of a DC jack kind of thing?

BTW, I'm starting out here too!


body:
If the cable of the power supply contains voltage and gnd, it's two cables, with a layer between them.

[![enter image description here][1]][1]

On the inside they look much like coaxial cables, so if you softly cut the outer shell(A) you maye see a mesh of blank wires(B,C,D), they're gnd in most cases.
There also is an inner wire(C) which you have to cut softly, too.
That's the voltage carrying wire(D), in most cases. (If it's approx. less than 10 Volts, check with a LED.)

  [1]: https://i.stack.imgur.com/Kcs6b.jpg


message:
Can't upload sketch to arduino Uno board

I'm trying to upload a simple sketch to my Uno board but get this error message: avrdude: stk500_recv(): programmer is not responding (full error message at the end).

I have other Uno boards who work fine so I guess it is something to do specifically with this board (which used to work) and not my system or cables (port,drivers,settings etc..).

I did a loop-back test (http://forum.arduino.cc/index.php?topic=73748.0) on  the board and it worked fine.

I read about possible solutions but nothing seems to solve this.
https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi

I also tried using an Arduino as an AVR ISP but it failed. (https://www.arduino.cc/en/Tutorial/ArduinoISP)

Any help will be appreciated, thanks in advance.

Full error message:

        avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd3
        avrdude: stk500_recv(): programmer is not responding
        avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd3

        avrdude done.  Thank you.

        Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body: Try the different boards in the menu.  I had that with one of my boards and then it worked fine when I used the Due in the IDE instead.  Something to do with one of the chip revisions I think.


body:
In Arduino IDE check that

 * correct port number is selected in Tools -> Port
 * correct programmer is selected in Tools -> Programmer (should be AVRISP mkII if you upload the code via USB cable)
 * correct board is selected in Tools -> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.


message:
COM+ and COM- to RX and TX

I want to connect a Hokuyo scanning range finder to an Arduino Mega, the outputs are labeled like this:

- COM+
- COM-
- Input
- Output
- DC12/24
- GND

I want to read its serial output with Arduino, please help me in details.
Thanks

body:
 You should specify what model of Hokuyo scanning range finder you have.  Some models are USB-interfaced, in which case  COM+ and COM- could possibly correspond to USB D+ and D- leads.

The [Hokuyo URG-04LX](https://www.hokuyo-aut.jp/02sensor/07scanner/urg_04lx.html) has both USB and RS-232 interfacing.  The [linked page](https://www.hokuyo-aut.jp/02sensor/07scanner/urg_04lx.html) shows the following pinout on CN1:

    Pin No.   Signals                                Colors
    1         N.C.                                   Red
    2         N.C.                                   White
    3         OUTPUT(Synchronous output)             Black
    4         GND(5th pin of 9-pin, D-sub connector) Purple
    5         RxD(3rd pin of 9-pin, D-sub connector) Yellow
    6         TxD(2nd pin of 9-pin, D-sub connector) Green
    7         0V                                     Blue
    8         DC5V                                   Brown

Given that pinout, you would connect pin 5, RxD, to a TXD output on the Mega, and pin 6, TxD, to an RXD input on the Mega.  Note, before making any such connection, measure the output voltage on pin 6.  An ordinary Mega supports 0 V and 5 V levels for serial data, but standard RS-232 levels are lower and higher than that; for example, ±12 V.  If you connect  ±12 V RS-232 levels to your Mega, you will damage it.  The several Hokuyo documents I've looked at don't say whether they use traditional RS-232 levels (±12 V) or TTL levels (0-5 V).


message:
Camera switch with ov7670 to output standard A/V signal - composite

I've got 3 OV7670 cameras and would like to create a switch that outputs one of the cameras video as standard A/V out (I'm not sure the correct naming).

I found docs explaining how to use the cameras on the Arduino platform but I'm not sure how to output video signal - composite.

body:
An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see [here][1] the signal specification.

Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

 1. you will need a very fast DAC (a flash one)
 2. you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...

  [1]: http://martin.hinner.info/vga/pal.html


message:
Moisture sensor data will not output data to Serial Monitor?

I am making a Soil Analysis system with an Arduino Uno, but I have run into a problem and was wondering if /r/learnprogramming could help!

The moisture sensor section of my code will not output the data to the Serial Monitor in Arduino 1.7.1 IDE. I am not sure why it's not working. Running the moisture sensor code by itself works, and I just copied and pasted that code into my combined code file since I'll I am running 4 sensors at once with my Arduino Uno.

These are the four values I need to output data on one baud rate:

* pH value
* EC
* DHT temperature reading
* Moisture Sensor Value
I am currently missing Moisture Sensor Value when I run Combined1.ino

Here is the Combined1.ino code of the code from four sensors together that's uploaded to the Arduino:
[Combined Code Link][1]
[Moisture Sensor Link][2]

Any help would be much appreciated!

  [1]: https://github.com/trooper5010/Soil-Analysis-System/blob/master/Combined1.ino
  [2]: https://github.com/trooper5010/Soil-Analysis-System/blob/master/Moisture_Sensor.ino

body:
Your second print section will always fail.

You have:

    if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator

However, a bit before then you have:

    if(millis()-printTime>=printInterval)
    {
      printTime=millis();

So `millis() - printTime` can never be greater than `printInterval` since you have just set `printTime` to `millis()`. So `millis() - printTime` will always be somewhere between `0` and `printInterval - 1`.

Consider combining your different printing routines into one single printing routine so you are comparing (and changing) the `printTime` only once.


message:
RS485 Multimaster Communication with collision avoidance

I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.

My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.

I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found [this library][1] which apparently does implement what I need, but I haven't been able to understand how it works.

My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.

What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

  [1]: https://github.com/MichaelJonker/HardwareSerialRS485

body:
Collision avoidance is a tricky subject. You can never completely avoid collisions - all you can do is work out how to a) detect them, and b) recover from them.

There's many different ways of doing it, and how you implement it is very much dependent on what your hardware can do, and how you are actually using the protocol.

The best way of detecting a collision is to arrange it so that your master is always reading the bus even when it is sending. You require separate receiver and transmitter modules, so that as you place a byte on the bus you attempt to also receive that byte. If it doesn't get received, or the wrong byte gets received, then you have a collision.

That is a 100% guaranteed way of detecting a collision as it happens. If you know that what you sent didn't make it onto the wire properly then it collided.

A simpler scheme is to be watching the bus before you send. If there has been no sign of any traffic for more than a certain threshold time then you can assume that the bus is currently quiet. You can then try and send your data. You don't know if it got through OK though, since something else could have decided that the bus was quiet long enough for it to send too.

So you would have to have some kind of ACK signal coming back from the other end that says the packet got received OK. Keep retrying until you get that ACK back. Of course, the ACK could be colliding as well, so it may have been received, but you just haven't been told. So your remote device would have to be able to gracefully handle receiving the same packet multiple times and discarding (yet still ACKing) the repeated packets.

What you should do when you do detect a collision (or fail to receive an ACK) is also kind of tricky.  You have to wait and try sending again. But if there are two devices both waiting to send again, how can you be sure that they won't both be waiting for the same time, and thus collide again?

You have to ensure that both devices delay for a random period - and make sure that the random period truly is random. Using the default `random()` function, unless you can seed it from a truly random source of entropy, will generate the same sequence of numbers for all the devices - so each device would get the *same* "random" number. And collisions ensue.

So you see, you can't just throw a random library at it and say "This library will stop collisions" - the best you can say is "This library can help reduce collisions, detect them when they do occur, and gracefully recover from them."

For the library you link to it appears to attempt to implement the latter system:

> * Collision avoidance is implemented through the assignment of a message priority. A node will not start transmission before the bus has been idle for a time determined by the priority. Note that the highest priority is given to messages with the lowest priority number.
>
> * Collision detection is implemented by read-verified-write, i.e. all data written is checked on the fly for proper echo-back. If the software detects a frame error or a data mismatch when the echo character is received, it will disable the RS485 transmission and flag the collision status. The included transaction management will resend the message after the bus is idle again.

It waits for the bus to be free of traffic for a specific amount of time (the time is variable depending on the message priority), and expects the message to be sent back again as a form of ACK.

It makes no mention of random back-off times though to avoid collisions between different masters sending messages with the same priority.


body:
There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).

The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.

In ‘understanding the library’ there are two aspects: how it works, and how to make it work.

The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.

However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.

So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.

The preferred way to contact me on these matters is by creating an issue on my Github project page:

https://github.com/MichaelJonker/HardwareSerialRS485/issues

BTW one of the issues addresses the same topic.

I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).

Best regards

MichaelJonker


body:
I did a [post about rolling masters](https://arduino.stackexchange.com/a/15835/10794) here on Arduino Stack Exchange.

The general idea is that you can set up multiple Arduinos to take turns becoming a master, based on waiting for its own "turn" in a time-based sequence, with provision for recovering from one of the units not responding.


message:
Arduino IDE "Tools > Serial Port" grayed out (Ubuntu)

I know this has been asked before, but no one's solutions I've seen have worked so far. I just got started with Arduino and downloaded Arduino IDE from the Software Center. When trying to to set up my Serial Port, the option in the toolbar is gray/unaccessible.

I also downloaded it as a tar.xz instead of from the Software Center and had the same problem.

When I plug in my Uno, the green light turns on so I know it's being connected at least.

One solution I saw said it was a problem with my user group. However, I entered

`sudo groups <username>`

and came up with `<username> tty dialout sudo audio video plugdev input
`
so I think my groups are okay, right?

Anyway, I would really appreciate some help if anyone knows of a fix. I run 12.04 Ubuntu (I recently re-installed trying to fix this problem; I'm going to update to 14.04) on a Chromebook.

body:
I did what  Chris Stratton's comment suggested,

> To investigate this, edit the output of ls -l /dev/ttyUSB* and ls -l /dev/ttyACM* (done while the board is connected) into your question. Also if you recently changed any group memberships make sure you have logged out (or more simply, rebooted) since.
> If neither of those is turning up anything, then it sounds like nothing is recognizing your USB serial device. You can look for differences in the output of lsusb when it is and isn't connected, or you can check for error messages shortly after connection with demsg. At this point it could be anything - bad board, bad cable, damaged connector, missing kernel modules, or bad/atypical rules for udev or similar.

and there was no difference between the output of `lsusb` with or without the arduino in it (arduino Mega 2560, and my pc is debian 8.6). I tried it with a diffrent cable but that made no difference. I tried it with an other arduino (uno) and then I did saw differnce in `lsusb` and I could select a port. My mega had the 'on' led on. So even though lights are on and/or binking, it might be that your arduino is broken. If you can, try it with an other arduino. Otherwise you can try an other cable and usb port on your pc.


message:
Using Sprintf() to left pad a string?

I've been at this all day, and I just can't seem to wrap my mind around how to use sprintf() to set a width for my string so that my characters are right justified.

What I'm trying to do is scooch my output over to the right on my touchscreen when the value is positive.
My output string is always a predictable length, so it seems like it should be easy.
I tried concatenating a string with just a space in it, and every other way I could think of to add a space to the beginning of my string. No luck.

    char stringval[8] = 1.08;
    char juststringval[8];
    if (hashpos > 0 && hashpos < 10) {

     sprintf(juststringval,  " %5s" , stringval);
           Serial.println(juststringval);
    }
output:

    1.08 (no spaces in front)

In case you're curious why I need to use a string, my touchscreen will print floats, but my library won't rotate them properly.
Only strings can be rotated the way I need them.

Isn't there some simple way of doing this?

**EDIT:**

It seems I can use the width trick as long as I include some character besides an empty space.
For example:

    void setup()
    {
 char stringval[33] = "1.08";
 char juststringval[33];
 char space[] = "rr";         ////THIS WORKS: OUTPUT IS  rr      1.08
 float hashpos = 1.08;
 if (hashpos > 0 && hashpos < 10) {

  sprintf(juststringval, "%s  %7s", space, stringval);
  Serial.println(juststringval);
 }
    }

    void setup()
    {
 char stringval[33] = "1.08";
 char juststringval[33];
 char space[] = " ";     ////THIS DOESNT WORK. OUTPUT IS 1.08 LEFT JUSTIFIED
 float hashpos = 1.08;
 if (hashpos > 0 && hashpos < 10) {

  sprintf(juststringval, "%s  %7s", space, stringval);
  Serial.println(juststringval);
 }
    }

But I can't live with other characters in my string.
Isn't there something I can do?

body: The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. `"% 5s"` not `"%5s"`


message:
What is VREF pin?

Was searching for some help on connecting Flir camera w/ Lepton board to arduino and found this thread
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Zdc9H.png

*for power you can reroute the 3-5V to the VREF pin, then you have a nice clean solution.
You have to use a Ardunio with at least 16k or ram so you can buffer the image.*

Was that a typo and he meant AREF?  If so would the VIN from the camera be connected to the VIN on arduino otherwise?

Thread:
https://forum.arduino.cc/index.php?topic=266361.0

body: VREF normally means Voltage REFerence.  Such pins are usually associated with ADCs (Analog to Digital Converters).  For example a 3.3 volt microprocessor may have a VREF pin fed by 2 volts.  The 10 bit ADC inside the microprocessor sees this as the upper limit.  That is, a 2 volt input to the ADC will produce the maximum value or 2^10 or 1024.


body:
Yes, he meant AREF.  What he is showing there is the board plugged direct into the Arduino's header, but the VIN of the Lepton board connects to AREF not a voltage pin. By connecting your supply voltage (5V) direct to that AREF pin you are then able to provide power to the Lepton board, and it has no noticeable effect on the Arduino since connecting 5V to AREF is a perfectly valid thing to do (though pretty pointless).

AREF and VREF are both pretty much interchangeable. Analog REFerence, and Voltage REFerence. It could be said that one is the Analog voltage REFerence, and the other is the Voltage REFerence for analog. Some chips call it AREF and some VREF. Some even provide VREF+ and VREF- or AREF+ and AREF- depending on the complexity of the ADC in the chip.


message:
Sending a text message through a arduino wifi shield

I am using an Arduino uno and need to send text messages and email messages from the device based on certain events occurring.  I have the logic figured out of when to send the text message or email but don't know what shield I need to send these messages.

body:
Sending an email you need a network connection of some form.  Options include:

* Ethernet Shield
* WiFi Shield
* GSM Shield (can be expensive, but will work almost anywhere)

To send a text message you need access to a text message service. That can either be directly through a mobile phone operator or through an on-line SMS gateway service. For an on-line service the options are as above, since it's almost the same as sending an email (in fact, some gateways offer an email-to-SMS gateway option). For direct mobile provider access you can only use a GSM shield.

So really it boils down to how mobile you need it to be, and how much you are willing to spend (both on the initial hardware outlay and service provider fees and charges).


body:
In one of project I had seen recently, they used esp8266 for home automation and used TEMBOO.com to send SMS. I am sorry I can't help u further than this, but i am sure, Google will..

You can also refer this tutorial from adafruit on sending an sms with Temboo

https://learn.adafruit.com/sending-an-sms-with-temboo/


body:
If you are trying to send `test messages` and `emails` over INTERNET using ETHERNET or WIFi you might need some REST API. There are two ways to get that part done.

 1. You might create your own REST API that contains some AUTHENTICATION KEYS, USER ID, RECEIVER ID etc for emails and same for test messages.
 2. You can use third part REST API that provides these functionality.

I am attaching some link you for help that will tell you how to send emails and text messages over internet.[for emails](https://circuitdigest.com/microcontroller-projects/sending-email-using-arduino-and-esp8266-wi-fi-module) [For Text Messages](https://circuitdigest.com/microcontroller-projects/sending-sms-using-esp8266)

**NOTE :-** Email api might get expired, don't get stuck over it found some other ways or third party API for that.


message:
Power motor with Uno

I am trying to power a small peristaltic pump using an UNO R3. I have it powered using usb, and I tried running the blink program to see if I could power it using digital write, and extended the delay to troubleshoot voltages using a multimeter. The motor doesn't do anything connected to the digital pins even when the digital write is set to high. If I connect the motor to the 5 V power pin the motor turns on so I know 5 V is enough voltage. I've looked at tutorials for DC motors and they explain how to set it up with motor reversing using components I don't have, and I don't need it to reverse. How can I get the motor to turn for a specific length of time?

body:
Most likely the motor you are trying to drive requires much higher current than what the UNO can provide through its digital outputs.

Check out [this summary][1] to find out detailed specs for the I/O ports.

What you could do is to draw power from the 5V line provided by the Arduino. If that can drive your motor, then use the line to power an output stage, driven by the digital I/O. See [this example][2].
In general, the idea is that the digital I/O provides the control logic, while the output stage provides the power required by the specific load.

The typical loads that can be driven directly by GPIOs are low power LEDs.
Anything that involves moving parts is generally out of reach, power-wise.

  [1]: http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
  [2]: http://www.opencircuits.com/Driving_Large_Loads_with_the_Arduino


message:
Can an arduino tell between being powered by USB or by the jack?

I have an arduino mega that will be communicating through serial to a pc. One of the things I want it to tell the pc is whether or not it is connected to a wall power to 12V converter (where there is a switch between the arduino and the wall power). I was just wondering if there was a way to do that in software without having any additional hardware.

Thanks!

body:
No, you can't do it without extra hardware.

You need to pass VIN through a voltage divider so it sits within 0-5V when powered by 12V, then feed that into an ADC input. Protect the on-board voltage regulator with a diode between 5V (anode) and VIN (cathode). Then you can measure the voltage on VIN and make a decision on if it is around 4.5V or 11.5V

A 22K/10K voltage divider will reduce 12V down to 3.75V, which gives plenty of "headroom" for over-voltage situations (where your 12V unregulated power supply actually provides, say, 15V):

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/gp3tB.png


message:
How to 'label' module using electric techniques

I am in a project where it makes set of 'modules(set of separate circuits that will work as a sensor when connected to the board' that would be connected to Arduino Mega.

Currently, I'm planning to connect 'modules' with the Mega board using RJ-45(also known as LAN cable) cables.

At first, using voltage divider circuit, I tried to identify these 'modules' by attaching a resistor to it, so that if the board sends 5V to the 'module', it gets the resistance of the resistor inside the module.

But, as soon as I tested, this way seemed a bit unstable, because the measured resistance of the resistor kept changing.

Now, is there any other way to 'label' the module? I'm a beginner in this thing, so I'll appreciate any help that is provided.

Thanks in advance.

Ps. the voltage divider circuit that I used can be found in here:

Ps2. the resistor in the module does not mean the total resistance of the circuit in the module. It's separate.

body:
If you are unable / unwilling to change your interface into a purely digital system whereby a small microcontroller in the sensor module interfaces the sensor with a communication bus, the best method is probably to include a small 1-wire EEPROM with each module.

An ideal one would be the [DS2431](https://www.maximintegrated.com/en/products/digital/memory-products/DS2431.html) which provides 1024 bits (128 bytes) of EEPROM storage using just 1 wire to both communicate and provide power.

Programming in a unique identifier for the module would be a simple enough task, and that unique ID can then be used to work out what the module is.

The DS2431 is pretty cheap too, available at prices around  $1.50 and below (much less for bulk and surface mount).

You can also get bigger versions for storing more data should you want to.


message:
What happens if I draw too much current from ATMEGA IO pin?

I revisited an older device that I made and discovered, that I had an 8 Ohm speaker connected directly to ground and an IO pin of an Atmega328P. According to my calculation that means that the pin would have to source 625 mA, which is way above the 40 mA that any single port should be able to source and even above the 200 mA that the Vcc and GND support. Yet it somehow worked and the chip seems to be working just fine. The application uses a duty cycle of 50%, so in the best case it would use maybe 312.5 mA, which is a little better but still way above the ratings.

So my question is, what happens if the output pin is asked to source more than it's rating?

I've seen chips that just release their magic smoke while others just can't keep up with supplying that kind of voltage, so only the voltage drops without any other problems. How does the Atmega328P handle this?

The Atmega clearly didn't burn through, but what other kind of damage should I expect?

body:
There's a few crude calculations you can do using some numbers from the datasheet.

This graph is in the datasheet:
[![enter image description here][1]][1]

It shows the voltage dropped by the high-side MOSFET driver in the IO pin for different amounts of current draw. From that we can get its resistance R(DSON).

For instance at 10mA, at 25C, the output voltage would be 4.75V. That's a 0.25V drop from the 5V supply voltage. So we can calculate the resistance as:

* *R=V/I = 0.25V / 0.01A = 25Ω*

Now we have that resistance we can use it to calculate the actual current from the IO pin with an 8Ω load.  Simply add the two together:

* *25Ω + 8Ω = 33Ω*

Now we can calculate the current through that circuit:

* *I=V/R = 5V / 33Ω = 0.152A*

That is, of course, way above what the IO pin can actually supply (or so the datasheet says).

So what happens? Well, two things, basically:

1. The voltage on the IO pin will be below the 4.2V specification for the minimum of an output pin when HIGH, and
2. It will get hot.

The actual voltage will be, of course, *V=I×R = 0.152A × 25Ω = 3.8V* droped, so *5 - 3.8 = 1.2V*

What is more critical, though, is the heat.  152mA through a 25Ω resistance generates *P=I²R = 0.152 × 0.152 × 25 = 0.5776W*. That's quite a lot. Enough to melt the internal circuits in the chip and release the Magic Smoke™.

Running at 50% duty cycle, though, makes a difference. That's 50% of the power, which makes a big difference to the heat.

What would the actual allowable heat be? Well, at 40mA, with 25Ω, that is *0.04 × 0.04 × 25 = 0.04W*.

So you're generating more than 14 times the amount of heat you are allowed to. Even at 50% duty cycle, that's over 7x the limit.

Will it kill the chip? Well, possibly, possibly not. It depends how rugged the chip is and how well it can withstand the heat. Short bursts may be OK since the heat doesn't build up enough to melt things. Extended use, though, will make it get too hot, and things will go pop.

  [1]: https://i.stack.imgur.com/zrsHB.png


message:
Works for 2-3 hrs, then LED blinks rapidly - Sleep Mode and Watchdog timer wakeup

I hope somebody can shed some light on this problem. I've researched the internet and forums and noticed that others have experienced similar problems.

This sketch runs fine for a couple of hours...it activates a relay approximately every hour, has a 10 second loop for an LED flash and then enters sleep mode. The watchdog timer is set to 8 seconds and wakes it up from sleep. I don't know why it works for a couple of hours and then gets caught into some sort of loop with the LED flashing rapidly. The requirements for disabling and resetting the watchdog might be the problem but I just don't know where to go next. I have seen a few discussions on memory leakage but not sure what that means or how to check for it. I also wonder if need to add any short delays after resets, etc. Additionally, when I press the reset button it has no effect on restarting the sketch. The sketch is running on a breadboard atMega328p-pu. Any help would be greatly appreciated.

ps. in the preview I noticed the # statements are not shown. They are the following libraries: avr/sleep.h, avr/power.h, avr/wdt.h

    // In this sketch, the LED's flash every 10 seconds, then at each approximately 1 hour period, the relay is activated
    // for 12 seconds.  It uses the WDT at its maximum 8 second delay to wakeup the circuit from low power sleep.

    // Source: citizen-sensing.org/2013/07/arduino-watchdog/

    // Check this out for good explanation on the Watchdog timer and code.
    // http://www.leonardomiliani.com/en/2013/impariamo-ad-usare-il-watchdog-2/

    // SEE NOTE at the end on known WDT reset issue

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>

    int j = 1; // Elapsed time multiplication factor
    int j2 = 0; // previous j value
    float tCumm = 0.0; // Cummulative time
    float hSet = 1.0; // Set relay activation once per hour
    float hSet2 = 0.0; // Previous hSet value

    // Create sleepNow function

    void sleepNow() {

      wdt_reset();
      wdt_disable();

      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Selecting the lowest power setting

    // Set watchdog parameters
      MCUSR &= ~(1<<WDRF); // reset status flag
      WDTCSR |= (1<<WDCE) | (1<<WDE); // required to enable configuration changes
      WDTCSR = (1<<WDP0) | (1<<WDP3); // set the pre-scalar for 10, ie 8 seconds delay
      WDTCSR |= (1<<WDIE); // enable interrupt mode

    // Disable the ADC
      ADCSRA &= ~(1<<ADEN); // Set bit 7 in ADC register to 1 to disable the ADC

    // Ready for sleep
      sleep_enable(); // Enable sleep function
      sleep_mode(); // Go to sleep.  Will wake up upon interrupt via Watchdog timer in this sketch.

    // disable sleep after waking up
      sleep_disable(); // Disable sleep for now after Watchdog timer interrupt activation
    }

    void setup() {

      pinMode(4, OUTPUT); // set pin 4 as output for LED
      pinMode(7, OUTPUT); // set pin 7 as output for relay
    }

    void loop() {

      // 10 second LED flashing + sleep loop

      for (int i = 0; i < 2; i++) {
      digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(200);               // wait for 0.2 sec
      digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
      delay(200);              // wait for 0.2 second
    }

      // Add delay for total approx 2 sec
      delay(1200);

      // Start sleep / Low power / Watchdog interrupt
      sleepNow();

      // Cummulative time in increments of 10 seconds
      tCumm = ((2.0 + 8.0)*j)/3600.;

      // Time multiplication factor. Used to increment tCumm. Never resets to zero.
      j2 = j;
      j = j2 + 1;

      // Check to see if tCumm exceeds the user defined period (hSet) before activating relay
      if (tCumm > hSet) {

      // Activate relay for 12 seconds
        digitalWrite(7, HIGH);
        delay(12000);
        digitalWrite(7,LOW);

      // Reset hSet for next relay activation time
        hSet2 = hSet;
        hSet = hSet2 + 1.0;

        }
    }

    ISR (WDT_vect) {

    }

NOTE from an online discussion: The problem is that a RESET does not turn off the watchdog timer once it has been turned on, and neither does the bootloader.  So you set things up to have the watchdog cause a reset in 15ms, and the reset occurs. Now the bootloader starts up, and starts its LED-flashing, and OOPS another 15ms has gone by with no one feeding the watchdog, and it resets again.  This repeats until a power cycle turns off the watchdog.
(This behavior is explicitly described in the ATmega datasheet...)

body:
You have a watch dog timer for 8 seconds and when you activate the relays you do a delay of 12.
This means that your watchdog will trigger when you activate the relays.


body:
Looking at this declaration

    int j = 1; // Elapsed time multiplication factor
    int j2 = 0; // previous j value

and then this code

    // Cummulative time in increments of 10 seconds
      tCumm = ((2.0 + 8.0)*j)/3600.;

     // Time multiplication factor. Used to increment tCumm. Never resets to zero.
      j2 = j;
      j = j2 + 1;

along with the associated comments seems to indicate that this variable "j" which is a (signed) `int` only increments without ever resetting, and is critical to the process of calculating the next time at which your code will act.

Your includes indicate that you are building for an AVR-based Arduino, and under the compiler used, an `int` on this platform is only 16 bits, meaning it has a range of -32768 to 32767.  Most modern platforms including this one use 2's complement representation, and most non-DSP platforms including this one do not use saturating arithmetic.  **Therefore, incrementing a positive number beyond the positive limit will actually product a negative value.**  Once your target time exceeds the maximum possible result of a calculation that has a positive `int` as an input, it becomes a target you will never be able to achieve.

Given the the amount of time your loop takes to execute, such integer overflow may not be not the issue you are hitting *first*, and does not seem perfectly correlated to your rapid-cycling failure mode.  But if your loop takes around 10 seconds, it seems like this would be an issue in a little less than four days.


message:
Arduino I/O Shield relay won't switch

I have an Arduino Uno and the I/O Shield wired up and I'm trying to switch (i.e. engage) a relay on the I/O Shield, but nothing seems to be working.

I've identified the input pins correctly and am able to send digital signals to it and it responds correctly. I also see the LED next to the relay light up when I do a digital write on the Arduino to a specific relay pin.

I'm starting to think that I might need to use an alternative power source or that I am not using the Arduino API correctly to switch the relay. At the moment I do a `digitalWrite(13, HIGH)`, delay, and then do a `digitalWrite(13, LOW)` - pretty simple.

The shield is just powered by the Arduino at the moment, and I haven't been able to find where I might be able to plug in power, so I'm assuming the Arduino supplies it with all of the power it needs.

    #include <Arduino.h>

    int relayPin = 13;

    void setup() {
        pinMode(relayPin, OUTPUT);
    }

    void loop() {
                digitalWrite(relayPin, HIGH);
            delay(5000);
            digitalWrite(relayPin, LOW);
            delay(5000);
    }

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/u8oFH.jpg

body:
Unless you share a schematic, it will be very difficult to provide a good answer.

Here are the things that you might be doing wrong:

1) Using a power supply which is not able to provide enough current to the relay.

2) Using a power supply of wrong voltage as required by relay coil. The relay might be needing 12 V and you might be trying to power it up with a 5 V power supply.

3) You might be trying to drive the relay directly with your GPIO pin (without using any external transistor switch).

4) Trying to raise a dead relay. There is a possibility that the relay is damaged. Check it by powering it up directly using a battery or another adequate power supply that you got.


body:
Based on your newly-added [photo](http://www.velleman.co.uk/contents/media/a05-3.jpg), you are using the [Velleman VMA05 I/O Shield](http://www.velleman.co.uk/contents/en-uk/p626_vma05.html) (or the [KA-05 kit version](http://www.velleman.co.uk/contents/en-uk/p582_ka05.html)).

This shield **requires** a 12V 500mA (minimum current capability) power supply input to the Arduino Uno, as that board uses relays with a 12V coil.  Your symptoms (LED lights but relay does not switch) suggest that you are using a lower voltage, or lower current, power supply to your Arduino. If so, then the fix is: Use the required power supply to the Arduino.

> I'm assuming the arduino supplies it with all of the power it needs.

Yes - but *only* if you meet the minimum requirements of the power supply which you connect to the Arduino. As documented in the Vellemen VMA05 [datasheet](http://www.velleman.co.uk/contents/en-uk/vma05d.pdf) and [manual](http://www.velleman.co.uk/contents/en-uk/vma05.pdf), this must be a 12V supply (not lower, not higher) capable of a minimum of 500mA.

(You would likely be able to use a 12V supply capable of a slightly lower current output, if you only wanted to have one or two relays active at the same time. However if more relays were active simultaneously, the risk would increase of incorrect or erroneous behaviour, due to the additional current necessary for each relay coil, in addition to powering the Arduino, eventually exceeding the capabilities of the power supply.)


body: Yes, 12V / 500mA supply is the minimum required for this board to work correctly. 9V will make the LED turn on but not pull the relay contacts properly.  Also, I have had two of these boards where the back EMF diodes across the relay coils have gone short circuit causing excessive heating in the associated switching transistors.  The solution is to replace these diodes with a more suitable 1N4001 type since the 1N4148 that is supplied with the kit is really a small signal diode and really not suitable for this purpose.


message:
ATSAMD21 sleep + watchdog?

Has anyone got sleep/standby + watchdog to work together on their Arduino Zero or Sparkfun SAMD mini?

I am able to get the WDT to reset the device, and am able to put it to sleep - but can't get the WDT to bring it out of sleep.  Every time I try, it pops right back out of sleep mode again as if `SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk` was never even called

body:
use this:

    attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
        USBDevice.detach();
        SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
        __DSB();
        __WFI();

    void wakeupFunction(){
      NVIC_SystemReset();
    }


message:
sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler

My existing Arduino Mega set up has been in use for about 4 years controlling my gas CH system & heat pump HW system using an Arduino mega & 13 'wired' DS18B20 sensors; 2 of these sensors monitor the main room (lounge) temperature & 1 sensor monitors the outside temp. These 3 sensors control the CH by gas boiler using an algorithm that constantly adjusts the room temp setting as the outside temp changes. The others monitor HW tank temps, heat pump inlet & outlet temps.

I want to change this 'single zone' CH control to a 'multi zone' control using many more temp sensors (DS18B20 or ESP8266?) but laying in hidden wiring would be a real pain.

I've been looking at using ESP8266-07 as a wireless temp sensor for each 'zone', sending its data to the Mega for processing by the above refered to algorithm, so that the Mega can control the CH system better but I can't find any reference to receiving this wireless data at the Mega for processing within the IDE sketch.

I've tried testing the nRF24L01 & nRF24L01+ but my house has many 'black' reception areas & transmission is unreliable.
My 2.4GHz wireless LAN has 3 extenders around the house so this would be my prefered wireless solution.

Could a wireless 'master' be used at the Mega to process data coming in from the 'slave' sensors or am I misunderstanding this?

My programming skill is limited to 'basic IDE' & I find 'wireless' a bit of a black art (I'm a retired mechanical engineer!)

body:
I am also in the middle of converting the control of my heating, multi-zone, but using Ciseco / Wirelessthings units as temperature sensors both inside and out. See [https://www.wirelessthings.net][1]

Simple serial interface is all you need from the Arduino to run these on a network. The coin cell battery lasts for over 1 year running 1 sample / 10min - the sample rate is configured but obviously the more samples you send the more the battery drains. Range seems to be OK and gets through 3 floors in the house and from the outside. I do use external antenna on the Arduino wireless unit to ensure I get all of the sensor readings.

However sounds like your house is BIG if running 3x WIFI extensions where as a single WIFI base station does me fine.

  [1]: https://www.wirelessthings.net


message:
How to bootload a atmega328-pu using arduino uno?

I have some Atmega328-Pu micro-controllers without boot-loader program. Now I need to burn boot-loader to them all. I have two arduino uno boards having Atmega328 P-Pu micro-controllers on board. I used this circuit [![enter image description here][1]][1] from this page [Installing an arduino boot-loader][2]
It does not work. The boot-loader is not uploaded. Can you please help me out? If you need any more informations please ask. I have been struggling with this kind of boot-loading techniques for more than a week. I am using arduino IDE 1.0.1 and the board is Arduino uno R3

  [1]: https://i.stack.imgur.com/lyzW8.jpg
  [2]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader

body:
Hi friends thanks for your support. It worked well as it is. No external capacitor I used.
I made the connection as shown in the above picture taken from [LINK1](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader).
I modified the file "boards.txt" and "avrdude.conf" as given in step 4 of [LINK2](http://www.instructables.com/id/Burning-the-Bootloader-on-ATMega328-using-Arduino-/?ALLSTEPS)
I first uploaded the ArduinoISP sketch to the board on the left.
And then I opened an "EMPTY ARDUINO SKETCH".
From that empty sketch I made the following changes
     Tools->Board = "Arduino328"
            Port  = COM4 in my pc
            Programmer = Arduino as ISP
Last step "Burn Bootloader"
Ta Da....
It worked. When I posted this question I burnt the boot-loader having the arduino ISP sketch opened. Only thing I changed now is I opened an empty sketch and hit burn from that sketch. Anyway.. thank you all. I dont think I wasted your time. If so, I apologise.