message:
Will 5V 2A current input to the power port kill my Arduino?

I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

body:
"*I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?*"

No! It won't. Even tough the reason has been already explained [in this other post][1], I want to add something.

First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly **ok**, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....

You're missing a key point, here: **the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!**

In other words:

 - if you have a device that requires a very little amount of current to properly operate (*as an example, [this DHT22 sensor][2], requires as little as 2.5mA, or 0.0025 A*) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;

 - if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);

 - if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (*Which kind of problems you'll encounter is a matter for a different question!*)

To be more specific:

 - a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
 - an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

 - you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to **not** require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" [are strongly related][3].

In your OP you mentioned "*mobile charger ... 5V*" so I bet that you've an USB power-supply, rated at 2A/5V.

People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed _exactly_ to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

  - as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;

  - as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).

As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a [barrel-jack][4], providing a voltage inline with what specified by [official documentation][5]:

> [...]
> The board can operate on an external supply of 6 to 20 volts. If
> supplied with less than 7V, however, [...] the board may become unstable. If using more than 12V,
> the voltage regulator may overheat and damage the board. The
> recommended range is 7 to 12 volts.
> [...]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

 1. from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;

 2. apply some "magic" to such a current and bring it down _to_a_very_precise_ 5V flow;

 3. provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.

 You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a **fundamental** concept to be kept in mind is that **such a reduction will produce "heat"**! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!

Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)

  [1]: https://arduino.stackexchange.com/a/18812/13193
  [2]: https://www.adafruit.com/products/385
  [3]: https://en.wikipedia.org/wiki/Ohm's_law
  [4]: https://en.wikipedia.org/wiki/DC_connector#Cylindrical_connectors
  [5]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


sender: user

message:
Proper Attiny85 timer/delay

Im having problems with Attiny85 programming. I am making something similar like [this project][1]. But i added function that every day on some time it turns on output - something like alarm clock. The real struggle is to make it active for longer time as one minute.. If current time is equals alarm time `wake_HOUR==hour()& wake_MINUTE==minute()` then it will run only for a minute so I added changeable field for the time how long output should be active - for example 5 minutes despite 1 minute. I tried to make timer with `millis()` and after those 5 minutes [reset timer][2] but this is where i stuck, because compiling for attiny it shows error, but if i use same code sample just for arduino then its working.. Code below:

    #include <avr/sleep.h>
    #include <TinyWireM.h>
    #include <EEPROM.h>
    #include "ssd1306.h"
    #include "WDT_Time.h"

    #define TIMEOUT 6000            //display timeout
    #define UNUSEDPINA 1            //RESET
    #define ALARM 4                 //ALARM
    #define BUTTONPIN  3            //GND
    unsigned int wake_HOUR = 0;     //Hours when it should wake up
    unsigned int wake_MINUTE = 0;   //Minutes when it should wake up
    unsigned int wake_SECOND = 0;   //Seconds when it should wake up - Not using
    unsigned long ALARM_TIME;       //How long alarm should be active- changable in display
    unsigned long new_millis = 0;   //Timer
    unsigned long interval;         //How long alarm should be active
    extern volatile unsigned long timer0_millis;
    unsigned int ACTIVE_ALARM = 0;  //alarm activated?

    #define SET_UP_BUTTON_THRESHOLD 100   //100k
    #define UP_DOWN_BUTTON_THRESHOLD 600  //7k
    #define PRESSED_BUTTON_THRESHOLD 1000 //NO resistance

    // enum
    typedef enum {
    normal, sleeping
    }  run_status_t;

    typedef enum {
    time_mode, debug_mode, alarm_mode
    }  display_mode_t;

    // button field constant
    #define NO_FIELD 0
    #define YEAR_FIELD 1
    #define MONTH_FIELD 2
    #define DAY_FIELD 3
    #define HOUR_FIELD 4
    #define MINUTE_FIELD 5
    #define SECOND_FIELD 6
    #define ALARM_HOUR_FIELD 7      //Alarm Hour
    #define ALARM_MINUTE_FIELD 8    //Alarm Minute
    #define ALARM_FIELD 9           //How long should alarm be active - minutes
    #define SET_ALARM_FIELD 10      //Activate alarm
    #define FIELD_COUNT 10
    //#define ALARM_SECOND_FIELD 9

    // variables
    SSD1306 oled;
    static uint32_t display_timeout = 0;
    static run_status_t run_status = normal;
    static display_mode_t display_mode = time_mode;
    static display_mode_t last_display_mode = time_mode;
    static bool time_changed = false;
    static bool alarm_changed = false;
    static uint8_t selected_field = NO_FIELD;

    uint8_t wake_SET = 0;
    //const char wake_BACK[15] = "GO BACK";

    void setup() {
      // setup input pins, also pullup unused pin for power saving purpose
      pinMode(UNUSEDPINA, INPUT_PULLUP);
      pinMode(BUTTONPIN, INPUT_PULLUP);
      pinMode(ALARM, OUTPUT);
      digitalWrite(ALARM, LOW);
      interval = ALARM_TIME*60000;

      // init time
      init_time();

      // init I2C and OLED
      TinyWireM.begin();
      oled.begin();
      oled.fill(0x00); // clear in black

      // init display timeout
      set_display_timeout();
    }

    void loop() {
      // detect and handle button input
      check_button();
      unsigned long currenTime = millis();
      //unsigned long new_value;
      //setMillis(new_value);

      if (run_status == sleeping) {
        // return to sleep mode after WDT interrupt
        system_sleep();
      } else { // not sleeping
        if (millis() > display_timeout) { // check display timeout
          enter_sleep();
        } else { // normal flow
          readRawVcc();
          readRawTemp();
          draw_oled();
        } // normal flow
      } // not sleeping
      if (ACTIVE_ALARM==1)
      {
        if (wake_HOUR==hour()& wake_MINUTE==minute())
        {
        digitalWrite(ALARM, HIGH);
        new_millis = millis();
        }
        else if (currenTime -new_millis <= interval)
        {
        new_millis = millis();
        digitalWrite(ALARM, HIGH);
        }
        else if (currenTime -new_millis >= interval)
        {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
        }}
      else if (ACTIVE_ALARM==0)
      {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
      }
    }
    //void setMillis(unsigned long new_millis){
    //  uint8_t oldSREG = SREG;
    //  cli();
    //  timer0_millis = new_millis;
    //  SREG = oldSREG;
    //}

    void enter_sleep() {
      oled.fill(0x00); // clear screen to avoid show old time when wake up
      oled.off();
      delay(2); // wait oled stable

      run_status = sleeping;
    }

    void wake_up() {
      run_status = normal;

      delay(2); // wait oled stable
      oled.on();

      // update display timeout
      set_display_timeout();
    }

    void set_display_timeout() {
      display_timeout = millis() + TIMEOUT;
    }

    /*
     * UI related
     */

    void draw_oled() {
      if (display_mode != last_display_mode) {
        oled.fill(0x00);
        last_display_mode = display_mode;
      }
      oled.set_font_size(1);
      if (display_mode == time_mode) {
        // 1st row: print info
        oled.set_pos(5, 0);
        oled.print("TIME");
        oled.set_pos(80, 0);
        oled.print("AcALARM=");
        oled.print(digitalRead(ACTIVE_ALARM));
        oled.set_pos(80, 1);
        oled.print("A_TIME=");
        oled.print(digitalRead(ALARM_TIME));
        oled.set_pos(80, 2);
        oled.print("ALARM=");
        oled.print(digitalRead(ALARM));

        // 2nd row: print date
        print_digit(7, 1, year(), (selected_field == YEAR_FIELD));
        oled.write('-');
        print_digit(7 + (5 * FONT_WIDTH), 1, month(), (selected_field == MONTH_FIELD));
        oled.write('-');
        print_digit(7 + (8 * FONT_WIDTH), 1, day(), (selected_field == DAY_FIELD));

        // 3rd-4th rows: print time
        oled.set_pos(30, 4);
        oled.print("SET ALARM");
        oled.set_pos(3, 5);
        oled.print("HH:MM-->ALARM MIN");
        oled.set_pos(95, 5);
        oled.print("ON/OFF");
        oled.set_font_size(2);
        print_digit(0, 2, hour(), (selected_field == HOUR_FIELD));
        oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 2, 2, 2, 0b00011000);
        print_digit(2 * FONT_2X_WIDTH + 5, 2, minute(), (selected_field == MINUTE_FIELD));
        oled.draw_pattern(4 * FONT_2X_WIDTH + 6, 2, 2, 2, 0b00011000);
        print_digit(4 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 2, second(), (selected_field == SECOND_FIELD));
        print_digit(0, 6, wake_HOUR, (selected_field == ALARM_HOUR_FIELD));
        oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 6, 2, 2, 0b00011000);
        print_digit(2 * FONT_2X_WIDTH + 5, 6, wake_MINUTE, (selected_field == ALARM_MINUTE_FIELD));
        print_digit(6 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 6, ALARM_TIME, (selected_field == ALARM_FIELD));
        print_digit(80, 6, ACTIVE_ALARM, (selected_field == SET_ALARM_FIELD));
      }
      else if (display_mode == debug_mode) { // debug_mode
        print_debug_value(2, 'I', get_wdt_interrupt_count());
        print_debug_value(3, 'M', get_wdt_microsecond_per_interrupt());
        print_debug_value(4, 'V', getVcc());
        print_debug_value(5, 'T', getRawTemp());
      }
    }

    void print_digit(uint8_t col, uint8_t page, int value, bool invert_color) {
      oled.set_pos(col, page);
      if (invert_color) oled.set_invert_color(true);
      if (value < 10) oled.write('0');
      oled.print(value);
      if (invert_color) oled.set_invert_color(false);
    }

    void print_debug_value(uint8_t page, char initial, uint32_t value) {
      oled.set_pos(0, page);
      oled.write(initial);
      oled.set_pos(14, page);
      oled.print(value);
    }

    // PIN CHANGE interrupt event function
    ISR(PCINT0_vect) {
      set_display_timeout(); // extent display timeout while user input
    }

    void check_button() {
      int buttonValue = analogRead(BUTTONPIN);

      if (buttonValue < PRESSED_BUTTON_THRESHOLD) { // button down
        set_display_timeout(); // extent display timeout while user input

        if (run_status == sleeping) {
          // wake_up if button pressed while sleeping
          wake_up();
        } else { // not sleeping
          if (buttonValue > UP_DOWN_BUTTON_THRESHOLD) { // down button
            handle_adjust_button_pressed(-1);
          } else if (buttonValue > SET_UP_BUTTON_THRESHOLD) { // up button
            handle_adjust_button_pressed(1);
          } else { // set button
            handle_set_button_pressed();
          }
        } // not sleeping
      } // button down
    }

    void handle_set_button_pressed() {
      display_mode = time_mode; // always switch to time display mode while set button pressed

      selected_field++;
      if (selected_field > FIELD_COUNT) { // finish time adjustment
        selected_field = NO_FIELD;
        if (time_changed) {
          wdt_auto_tune();
          time_changed = false;
        } //time changed
      } // finish time adjustment
    }

    void handle_adjust_button_pressed(long value) {
      if (selected_field == NO_FIELD) {
        // toggle display_mode if no field selected
        display_mode = (display_mode == time_mode) ? debug_mode : time_mode;}
      else {
        long adjust_value;
        if (selected_field == YEAR_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY * (leapYear(CalendarYrToTm(year())) ? 366 : 365);
        }
        else if (selected_field == MONTH_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY * getMonthDays(CalendarYrToTm(year()), month());
        }
        else if (selected_field == DAY_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY;
        }
        else if (selected_field == HOUR_FIELD) {
          adjust_value = value * SECS_PER_HOUR;
        }
        else if (selected_field == MINUTE_FIELD) {
          adjust_value = value * SECS_PER_MIN;
        }
        else if (selected_field == SECOND_FIELD) {
          adjust_value = value;
        }
        else if (selected_field == ALARM_HOUR_FIELD)
        {
          if (wake_HOUR >= 23)
          {
          wake_HOUR=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           wake_HOUR--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           wake_HOUR++;
           }
            }
        else if (selected_field == ALARM_MINUTE_FIELD) {
          if (wake_MINUTE >= 59)
          {
          wake_MINUTE=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           wake_MINUTE--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           wake_MINUTE++;
           }
            }
          else if (selected_field == ALARM_FIELD) {
          if (ALARM_TIME >= 59) //MAX 1h
          {
          ALARM_TIME=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           ALARM_TIME--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           ALARM_TIME++;
           }
            }
          else if (selected_field == SET_ALARM_FIELD) {
          if (ACTIVE_ALARM >= 1)
          {
          ACTIVE_ALARM=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           ACTIVE_ALARM--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           ACTIVE_ALARM++;
           }
            }

        adjustTime(adjust_value);
        time_changed = true;
      }
    }

I would like to reset timer then when wake_hours&minutes and changeable alarm activation time `interval = ALARM_TIME*60000` have passed.

          if (ACTIVE_ALARM==1)
      {
        if (wake_HOUR==hour()& wake_MINUTE==minute())
        {
        digitalWrite(ALARM, HIGH);
        new_millis = millis();
        }
        else if (currenTime -new_millis <= interval)
        {
        new_millis = millis();
        digitalWrite(ALARM, HIGH);
        }
        else if (currenTime -new_millis >= interval)
        {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
        }}
      else if (ACTIVE_ALARM==0)
      {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
      }

Any ideas what kind a timer/delay i could use to make my code work?

  [1]: http://www.instructables.com/id/ATtiny-Watch-Core/step3/Power-Down-WDT-and-Time/
  [2]: https://arduino.stackexchange.com/questions/22994/resetting-millis-and-micros

sender: assistant

body:
As noted in the comment of IgnacioVazquez-Abrams, in the instances at hand you should be using the `&&` (logical AND) relational operator, rather than the `&` (bitwise AND) arithmetic operator.

That aside, you should separate things out so that instead of an ungainly `if - else` series you have some independent cases.  For example:

    if (wake_HOUR==hour() && wake_MINUTE==minute()) {
       digitalWrite(ALARM, HIGH);
       alarmMillis = millis();
    }
    if (millis()-alarmMillis > interval) {
       digitalWrite(ALARM, LOW);
    }

This will do the job, as follows:

• During the match-minute, `ALARM` will be driven high over and over, and `new_millis` will update to the current `millis()` value over and over.  Which is OK.

• After the match-minute but before the end of the timed interval, `ALARM` will remain high and `new_millis` will remain fixed with the time of the end of the match-minute.  OK, that's as desired.

• After the end of the timed interval, ie, when `millis()-new_millis > interval`, `ALARM` will be driven low over and over.  Which is OK.

Note, I don't see a declaration of `currenTime` or anywhere it is updated.  Hence, it does not represent current time and should not be used as such.

Note, `interval` should be declared as something like a `const unsigned long int`, with a value that is a minute shorter than the total length of interval that you want.  (`new_millis` represents the *end* of the first minute of the interval.)

Note, `new_millis` should *not* be zeroed at the end of the interval.  If the original code were magically made to mostly work, because of  `new_millis` being zeroed it still would have a bug.  During the first few minutes after each `millis()` overflow, a false alarm would sound.  `millis()` overflows are about 49.71 days apart.


body:
So i fixed my problem. I didnt use timer what i wanted in the beginning but as the code it self's running clock i used current clock as to activate output and then based on clock to turn off output.
Not always the hardest way is better.
Basically this is what i needed to change:

    if (ACTIVE_ALARM==1)
    {
    if (start_wake_HOUR==hour()&& start_wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    }
    if (end_wake_HOUR==hour()&& end_wake_MINUTE==minute())
    {
    digitalWrite(ALARM, LOW);
    }
    }
    else if (ACTIVE_ALARM==0)
    {
    digitalWrite(ALARM, LOW);
    }


message:
How to connect IR Transmitter and Receiver Module?

The IR Transmitter and Receiver module has both receiver and transmitter in same board. I tried Arduino IR Remote library example to decode Remote signal using below connection, but its not working.

 - IR MODULE:   ARDUINO
 - Ground   ->  Ground
 - 5V       ->  5V
 - RXD      ->  PIN 11
 - TXD      ->  PIN 10

The board also has 3 pin connector (Gnd, 5v, S). How to connect pins to Arduino to receive/decode and send IR signals? (Can't able to find any tutorial for this type of board)

[![IR Transmitter and Receiver Front][1]][1]
[![IR Transmitter and Receiver Back][2]][2]

  [1]: https://i.stack.imgur.com/nzzmom.jpg
  [2]: https://i.stack.imgur.com/hHbVIm.jpg

**Example Code:**

    #include <IRremote.h>
    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      delay(100);
    }

body:
The device in the question is commonly sold on aliexpress.com and the likes of ebay.com.  As you might guess there is little in the way of documentation.  Without documentation we can only speculate.  As such, I expect that the module handles all the modulation and demodulation.  It is likely all you need to do is use the [Arduino serial library][1] and connect the TX and RX to the Arduino's RX and TX pins.  However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the [Arduino software serial library][2] which will "emulate" a serial port an an unused (alternate) set of pins.

([This][3] is an example of a similar well documented device with access to the schematic and source code.  Armed with this type of knowledge you can turn this device into what ever you want.  In other words, you probably don't even need an Arduino.  You can just program this device and be done with your project.)

  [1]: https://www.arduino.cc/en/Reference/Serial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [3]: http://dangerousprototypes.com/docs/USB_IR_Toy_v2


body: I think you need to switch RX and TX in your code. Looking at the video that @nick-gammon reffered to. TX on audrion is RX on device.


body:
it use UART protocol so your code is wrong.

[Here link with code][1]

  [1]: https://forum.arduino.cc/index.php?topic=359707.0


message:
Made a Adafruit Flora unusable

I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs.  After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights.  When this orange color appears, it seems to indicate that the Flora has crashed.  If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.

The time between boot and crash is short enough that I can't upload a new sketch.

So how would I go about rescuing the Flora?
Is there a couple pins I can jumper to put it into bootloader mode?  Or some other way of resetting the Flora so as to remove the offending code?

body:
> 42 pixels in the strand all set to bright white.

This exceeds the power supply capability of either a USB port or the Arduino's regulator.

Likely the circuit starts out working, then once the LEDs are all on drawing high power either a protective device such as a polyfuse / PTC fuse activates trips or the supply simply sags under load.  At this point the circuit either shuts down or starts misoperating, the ATmega may go into brownout protection mode, etc.

Disconnect power to your LEDs and you will probably find that the Flora is fine.

You will need to use a suitable higher current power supply if you want to light more than a few pixels of this type at any given time.


message:
Reading the DotStar datasheet - power requirements

I'm trying to figure out my power requirements for a strand of [Adafruit DotStar][1] LEDs - APA102 Cool White, not the RGB. I'm not sure how to interpret the [datasheet][2].

In the middle of the product spec table on page 1, under Power Consumption, it says `0.2W (MAX: 1W)`.  Which would mean at 5V, MAX would be 0.2A, or 200mA.

Then on page 3 in the electrical characteristics table under the symbol/Parameter "LOL/Sink Current Voltage" it says `typ. 24.5mA; max. 26.5mA`.

I plan on having the strand on full brightness most of the time.

So which is it?  200mA? or 26.5mA?

  [1]: https://www.adafruit.com/products/2432
  [2]: https://cdn-shop.adafruit.com/product-files/2343/APA102C.pdf

body:
[![datasheet spec][1]][1]

You have correctly worked out:

    I(A) = P(W) / V(V)

    I = 0.2 / 5
    I = 0.04A

    MAX:
    I = 1 / 5
    I = 0.2A

From that it seems it will use between 40 - 200mA depending on brightness.

Sink current refers to the current required to drive the led's digital input from your MCU's digital output.

[![Sinking Output][2]][2]

[More information on current sinking][3]

  [1]: https://i.stack.imgur.com/lsbDW.png
  [2]: https://startingelectronics.org/articles/current-sourcing-sinking/current-source-sink.png
  [3]: https://startingelectronics.org/articles/current-sourcing-sinking/ "Sinking Output"


body:
I expect you will have to run an experiment and measure how much current each unit draws at full brightness.

The APA102C spec sheet seems to mix together data about the whole unit (controller chip plus three LEDs) and the controller chip itself.  The “LOL/Sink Current Voltage (RGB)” line that shows “min. 22.5, typ. 24.5, and max. 26.5 mA” appears to apply to the controller, and probably to single outputs on that controller, which anyway would give a 3X multiplier.  (The Cool White strips have three white LED chips per unit, instead of 1 each R, G, B.)

Note, the [Adafruit DotStar LED Strip - APA102 Cool White](https://www.adafruit.com/products/2432) webpage suggests using their 5V 4A power supply to drive “a half meter or meter” and their 5V 10A supply to drive  “a couple meters”, which at 30 units per meter works out at 2/3 to 5/6 W of power supply capacity per unit.


message:
Using Arduino GSM with WiFi

I have a project that requires  data to be sent online from a moving bus. I am using ESP8266F modules to send the data.

I am wondering what Arduino modules to buy that will act as an access point with wifi and will connect to the internet through GSM.

In this configuration, the ESP8266 will connect to the access point and will upload the data online.

I want to connect a DF robot "SIM808 GPS/GPRS/GSM Shield For Arduino" to an Arduino Yun and use them as a wifi access point to connect to the internet through GSM connection.

The ESP8266 (5 of them) will connect to the Arduino Yun and will then send variables to the internet through the internet connection provided by the GSM.

body: ESP is a full stack WiFi module. If you are intended to collect some data from several ESPs you can configure one more as an access point and collect those data from other ESPs as stations. At access pint you can make a small web server as well. To send aggregated data through GSM then you can use a GSM module wire-connected to this ESP. To avoid RF interference while GSM sends data, you should use different power sources and shielded twisted pair for connection. It may happan, that you will need to place GSM module at some distance from ESP access point to avoid overload of the receiver. Even better to use external antennae outside the bus for GSM and shield it inside the bus to minimise the interference. I do not see how Arduino can help here.


message:
VLcd pin to ground?

I just bought an ERC12864-655 LCD screen.

On the [datasheet][2] it says that I need to connect the vlcd pin to GND.

However in [this][3] (page 8) datasheet it says that vlcd is the main power supply. As far as I know ground is no power supply. That doesn't make sense to me.

So what should I do with this pin?

  [2]: http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf
  [3]: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

body:
It appears that the LCD is powered/switched by the chip, not directly powered externally. The 10K to ground would be a pulldown to keep pin 20 from floating when the LCD is not being powered, and the .33 uF cap would be for power filtering.

The datasheet pointed to by your second link is a quality-control document; not quite what most of us call a datasheet, but Note B on page 1 suggests more documentation is available on the manufacturer's website. Their interfacing description and demo code should help.


message:
Time.h rollover after 49.7 days

I'm developing a arduino based system, which includes a alarm system.

Searching on the Internet, I found these lybraries ["Time.h"](http://www.pjrc.com/teensy/td_libs_Time.html) and ["TimeAlarms.h"](http://www.pjrc.com/teensy/td_libs_TimeAlarms.html).

In the requirements, it says: *"Time does not require any special hardware. Internally, Time depends upon **Arduino's millis()** function to keep track to elasped time."*

Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?

I don't think that waiting 49.7 days to test it is the better way.

body:
As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.

Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).


body:
You should simply buy a real time clock such as the common DS3231. They work well and don't have any problems with resting or continuous data reading. It also dictates the date!

Hope I helped :)


body:
I have a lengthy [post about this](http://www.gammon.com.au/millis).

To avoid going to the link if you don't want to, the simple answer is to subtract when calculating time intervals, eg.

    unsigned long startTime = millis ();
    unsigned long interval = 60000;

    ...

    if (millis () - startTime >= interval)
      {
      // do something
      }

This *always works!* - even after 49.7 days - because of the way that unsigned arithmetic works.

The only time it would fail is if you needed to time an interval of over 49.7 days - in which case a real-time clock is an obvious answer.

Another example:

    startedFeedingFish = millis ();

    ...

    if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
      {
      // stop feeding the fish
      }


message:
Can't get ESP8266 working

I have received an ESP8266 (ESP-07) Wi-Fi module from DealExtreme (Link: http://bit.ly/2dFJdxE).

It is a 4-pin module with the following pins: RX, TX, VCC and GND.
The module has a switch so you can switch between the following modes: Program & UART. The module also has a RESET-button.

Here's a picture of my module:

I've connected the module to my Arduino Uno like this:

RX > RX,

TX > TX(TX>RX & RX > TX, like mentioned in manuals, results in no connection),

VCC > 3.3v (not using any level shifters because the module has on board level shifters),

GND > GND.

I found a lot of manuals to test the module, but apparantly I can't get my module working. I am using Windows with the Arduino IDE.

The boards mentioned on the manuals/tutorials also seem to differ from my module because most of the manuals are talking about a board that has 8-pins (with an extra GPO0, GPO2 CH_PD and RST pin).

I've tried to upload the BareMinimum sketch to the module, which only finishes uploading if I disconnect and reconnect the 3.3v input that's feeded to the ESP-board when the Arduino IDE says "Uploading...... " while the ESP-board is in Program-mode.

I have installed the ESP8266 library within the Arduino IDE and the **Generic ESP8266 Module** is selected.

Then when I open the serial monitor in the Arduino IDE, to test the AT commands (on different BAUD values), it does not respond (neither in Program-, nor in UART-mode).

Strange thing is when I keep the serial monitor on at 74880 BAUD (and UART-mode on the module) and I push the RESET button on the module, it gives the following message:

    ets Jan  8 2013,rst cause:2, boot mode:(3,7)
    ets_main.c

I've tried several things.  But none of them seem to work; like trying to flash new firmware (for example 'v0.9.5.2 AT Firmware.bin' and 'esp8266-2016-05-03-v1.8.bin') with **esptool.py** with the following command:

    esptool.py -b 115200 -p COM3 write_flash 0 FIRMWARE.bin

It says that the writing is finished and no errors appear after running the esptool. This is what is printed + command that is used:

`esptool.py -p com3 -b 115200 write_flash 0 firmware.bin
esptool.py v1.2-dev
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0000
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 44.2 seconds (94.1 kbit/s)...
Leaving...`

A strange thing is when I open the serial monitor in the Arduino IDE after that moment (without resetting the module/unplug from 3.3v or change to UART mode), it keeps printing the following at 115200 BAUD:

`Fatal exception (28):
epc1=0x4000228b, epc2=0x00000000, epc3=0x00000000, excvaddr=0x000000b5, depc=0x00000000
`

I even tried it with the erase_flash before and 0x00000 instead of 0. Also tried to run the command with a variety of flash_sizes (with the command --flash_size=Xm).

Esptool looks like the only tool where I can flash new binaries successfully, tried some others that where on some manuals but without success.

When I run `esptool.py -p flash_id`

I get the following response:

`Connecting...
Manufacturer: e0
Device: 4014`

Who knows how to fix this problem so I can send AT commands to the module through the serial monitor in the Arduino IDE.

Thanks in regards (this is my first post so if some things are unclear, please let me know)

**Edit:** Note that I have to disconnect and reconnect the 3.3v to the module EVERY time to successfully run a command (like write_flash, flash_id et cetera).
 Also tried connecting it to 5v and using an external power supply next to the USB.

body:
Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.

I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board.  I'm pretty sure that you have now shagged it totally by trying to write programs to it.  However you might be able to recover it if you can find the original program and upload that to it.  You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.

I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes.  As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)

If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.


message:
Having trouble using RTC if I set an ISR for a 1 second timer

I built a sketch using some timer ISR code to get a trigger every second.  (for the Atmega328 chip I use the following code I got form the internets.  It works)

It runs fine and I get a trigger/callback every second.

    void setupAtmega328()
    {
    #ifdef __AVR_ATmega328P__

//     traceDebug("setupAtmega328() entry");

     cli();  // stop interrupts
  //   traceDebug("setupAtmega328() 1");

       //set timer1 interrupt at 1Hz
     TCCR1A = 0;// set entire TCCR1A register to 0
     TCCR1B = 0;// same for TCCR1B
     TCNT1 = 0;//initialize counter value to 0
         // set compare match register for 1hz increments
     OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
          // turn on CTC mode
     TCCR1B |= (1 << WGM12);
     // Set CS12 and CS10 bits for 1024 prescaler
     TCCR1B |= (1 << CS12) | (1 << CS10);
     // enable timer compare interrupt
     TIMSK1 |= (1 << OCIE1A);
    // traceDebug("setupAtmega328() 2");
     sei();//allow interrupts
    // traceDebug("setupAtmega328() 3");

    #endif
    }

I also wanted to add the capability of a real time clock (RTC) so I got a [DS3231][1].

I downloaded and ran the sample app from [this RTCLib on github][2]

The sample code works fine when running under the Arduino IDE

However, when I add the RTC code to my sketch I don't get the results I want/expect.

**Specifically, the program seems to hang/halt** at the call to:

    cli();

I am new to the Arduino platform and not sure what I am missing.
What do I need to do to get the RTC to work in conjunction with an ISR?

I wired the RTC according to the [directions from Adafruit's site][3]

I have other arduino boards that use different ISRs, but I have not tried them yet with the rtc since the 328 seems to be the standard arduino boars that is used to do initial work/testing.

**How can I use the 3231 RTC AND a 1 second ISR/callback?**

**EDIT:**
I removed the trace/serial output - I had originally added those to track the code to see where I got but i think I exacerbated or added problems in doing that.

for those interested the code is at https://github.com/tjurik/Intervalometer

  [1]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/
  [2]: https://github.com/adafruit/RTClib
  [3]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test

body:
In the Arduino you don't have control how are some essential parts implemented.

For example `delay` function requires interrupts to be enabled or it'll be deadlocked (for sure).

Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your `traceDebug` is little bit longer.

In general `ISR` should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.

    volatile bool flag = false;

    ISR(...) {
      flag = true;
    }

    int main() {
      init();

      while (1) {
        if (flag) {
          do_something();
          flag = false;
        }
      }
    }


message:
DC Motor Pinning the Ada Fruit Moto Shield with the Mega2560 R3

I picked up an [AdaFruit Motor Shield V2.3][1] .  The example on the site shows how to code the DC Motor connection

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // Or, create it with a different I2C address (say for stacking)
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

    // Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
    // You can also make another motor on port M2
    //Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2)

What I'm unclear about is how to connect the shield to the mega board.  Which pin on the shield should connect to which pin on the board in order for `Motor 1` to run at that speed?

  [1]: https://www.adafruit.com/product/1438

body:
Well because an Arduino Mega2560 is pretty much and UNO with a longer rear end, try seeing the UNO in the MEGA if that makes any sense. Then just put the shield in like a normal shield that you would put on a UNO. Most UNO shields are compatible with MEGAs. Then you just use your shield like if it was on an UNO.

[![The UNO in the MEGA][1]][1]

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


message:
Arduino Uno R3 not working with Cytron shield GPS 53

My project is to find latitude and longitude of certain places. I am using an Arduino Uno R3 with a Cytron GPS 53 shield to get the position of places but, my device cannot run because COM4 already in use. How to fix this error?

body:
Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port.  The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).

The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.

If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).

Hopefully that should give you a start.


message:
Get pin input status without using the arduino library

I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

    #define bitRead(value, bit) (((value) >> (bit)) & 0x01)

Following digitalRead back to pgmspace.h:

    #define __LPM_enhanced__(addr)  \
    (__extension__({                \
        uint16_t __addr16 = (uint16_t)(addr); \
        uint8_t __result;           \
        __asm__ __volatile__        \
        (                           \
            "lpm %0, Z" "\n\t"      \
            : "=r" (__result)       \
            : "z" (__addr16)        \
        );                          \
        __result;                   \
    }))

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.

body:
For reading, e.g., PB2, you would test

    PINB & _BV(PB2)

where PINB is the port input register and `_BV(x)` is a macro defined as
`(1 << (x))`.

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on
[port manipulation](https://www.arduino.cc/en/Reference/PortManipulation).


message:
Can I use the same Data Registry for both input and output pins?

This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:

    //Global pointers
    unsigned char *portDDRB = (unsigned char *) 0x24;
    unsigned char *portDataB = (unsigned char *) 0x25;
    unsigned char *portPinB = (unsigned char *) 0x23;

    void setup () {
      //For the led output I know that I would do this
      *portDDRB |= 0x80;
    }

    void loop () {
       //And here the code would be like this to light up the light:
       if (condition to turn on light) {
         *portDataB |= 0x80;
       }
       // To Turn off the LED:
       if (condition to turn off the light) {
         *portDataB &= 0x7F
       }
    }

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

I am using the Arduino Mega ATmega2560 btw.

From the comments I have this:

    //Global pointers
    unsigned char *portDDRB = (unsigned char *) 0x24;
    unsigned char *portDataB = (unsigned char *) 0x25;
    unsigned char *portPinB = (unsigned char *) 0x23;

    void setup () {
      //For the led output I know that I would do this
      *portDDRB |= 0x80;
    }

    void loop () {
       //And here the code would be like this to light up the light:
       if (portPinB & 0x10) {
         *portDataB |= 0x80;
       }
       // To Turn off the LED:
       else {
         *portDataB &= 0x7F
       }
    }

body:
Assuming the button is connected between GND and pin 10, without any pull-ups or pull-downs.

    void setup () {
        //For the led output I know that I would do this
        DDRB = 0;             // set all pins on port B to INPUT
        DDRB |= _BV(DDB7);   // set PB7 to OUTPUT
        PORTB = 0;            // set all pins on port B to LOW
        PORTB |= _BV(PORTB4); // enable the pull-up resistor on PB4
    }

    void loop () {
        if( PINB & _BV(PINB4) )
        {
            // if bit PINB4 is set, the button is not pressed
            PORTB &= ~_BV(PORTB7); // turn off led
        }
        else
        {
            PORTB |= _BV(PORTB7); // turn off led
        }
    }


body:
> When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

----

**Clarification**

I take that question to mean "When I *assign* the value to 0x80 to DDRB". For example:

    DDRB = 0x80;

In the code above that question, you were not assigning, you were "or"ing the value.

----
Yes. Typically you would "or" in the value if you want to affect only one pin, eg.

    DDRB |= 0x80;

The conventional way to make it an input again would be:

    DDRB &= ~0x80;

That is, "and" in the negated bit pattern for that pin.

Remember, you have 3 registers (per port) where "x" is "A", "B", "C" etc.:

 * DDRx - data direction - a 1-bit is output, a 0-bit is input
 * PORTx - output value - a 1-bit is HIGH, a 0-bit is LOW

    However, if the data direction is input, then a 1-bit is input-pullup, and a 0-bit is not input-pullup.
 * PINx - read the input from the port - a 1-bit is HIGH, a 0-bit is LOW

    Note that writing a 1-bit to PINx toggles the output value of that port.

---

These remarks apply to the AVR chips, not the SAM ones.


message:
Supply 5V to Arduino

I am building a quadrocopter with an Arduino Uno as control unit. I know I can [supply 5 volts to the 5V pin][1], but my ESCs produce 5.5 volts, which I measured with my multimeter. Will this voltage drop to 5 volts when I connect the Arduino and if not are 5.5 volts to the 5V pin a problem?

Edit:

My Arduino was running well for a couple of days on this setup with 5.5 volts to the 5V pin but died yesterday. By dying I mean the ATmega doesn't execute any code anymore, the L LED doesn't blink, and even a loopback test fails, which is a sign of a defective USB connector. But I am faced with the same challenge. Should I run my Arduino on 14.4 Volts from my 3S LIPO to Vin or supply 5.5 volts to the Vin pin?

Actually I just realised when I measure the voltage from the ESCs they deliver 9 point something volts for half a second when connecting the multimeter, I guess this voltage spike killed the Arduino.

  [1]: https://electronics.stackexchange.com/questions/65576/arduino-uno-r3-directly-supply-regulated-5v-to-5v-pin

body:
I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.

According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v.
You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.


body: Most Arduinos won't mind 5.5v if your are sure that is the max. The ATmega328 is design to be used from 2.7V to 5.5V so that is the very max. No, the voltage will not drop down to 5V when you connect it to the Arduino but I believe you are quite safe with 5.5V. Just don't make a short because you'll be pushing your ATmega328 to it's designed max. You might wanna look at the datasheet for it. All it specs are in there.


body: You're better off applying that 5.5V to the Vin pin. You may end up with slightly less than 5V at the Arduino, but it'll tolerate that much better than going above 5.5V on the 5V rail.


body:
> Actually I just realised when i measure the voltage from the escs they deliver 9 point something volts for half a secound when connecting the multimeter ...

Yes, that won't be good for it. I suggest a LDO (low dropout) 5V voltage regulator. Something with a 0.5V dropout will get rid of that extra 0.5V and also handle the initial spike.


body:
Okay - it looks like that voltage spike might be the cause of death for your board.
As an answer to your question though - I would recommend applying the 14.4 volts to vin, as 5.5 volts is not enough (the regulator needs 6 volts as a minimum, and the absolute maximum is 20 volts).
Just make sure you apply the 14.4 volts to the *vin* pin and **NOT** the *5v* pin, as that would kill the board.

Please tell us how it worked out - good luck!


message:
How to set up one second interrupt/ISR for ds3231 RTC

I am able to set up one hz interrupts using millis and other timers, but would like to do it instead using the RTC I have attached ([DS3231][1])

I am not sure how I can do that.  Can someone point me to a reference for this?

**EDIT/UPDATE**

I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.  I followed what I thought was the wiring diagram [here][2] and
[here][3] and [here][4]

I also added a led in the circuit to see if I could figure out something that way, but no dice.

Here is some simple code for a sketch that I think should trigger a 1 second interrupt and call my function:

    #include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
    #include <Time.h>         //http://www.arduino.cc/playground/Code/Time
    #include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

    const int rtcTimerIntPin = 2;
    bool flag = false;

    void setup(void)
    {
     Serial.begin(9600);
     setSyncProvider(gRTC.get);   // the function to get the time from the RTC
     if (timeStatus() != timeSet)
      Serial.println("Unable to sync with the RTC");
     else
      Serial.println("RTC has set the system time");

     bool stopped = gRTC.oscStopped();
     if (stopped)
     {
      Serial.println("Detected clock power loss - resetting RTC date");
      time_t newTime = cvt_date(__DATE__, __TIME__);
      adjustTime(newTime);
      setTime(newTime);
     }
     else {
      Serial.println("Clock did not lose power");
     }

     pinMode(13, OUTPUT);    // onboard LED
     pinMode(rtcTimerIntPin, INPUT);
     attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
     gRTC.squareWave(SQWAVE_1_HZ);

     digitalClockDisplay();
    }

    void rtc_interrupt(void)
    {
     flag = true;
    }

    void loop(void)
    {
     //digitalClockDisplay();

     if (flag) {
      digitalWrite(LED_BUILTIN, HIGH); // flash the led
      digitalClockDisplay();    // this just prints time to serial port
      delay(500);       // wait a little bit
      digitalWrite(LED_BUILTIN, LOW);  // turn off led
      flag =  false;      // clear the flag until timer sets it again
     }
    }

    void digitalClockDisplay()
    {
    // do something
    }

  [1]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview
  [2]: https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test
  [3]: https://learn.adafruit.com/ds3231-precision-rtc-featherwing/pinouts
  [4]: https://learn.adafruit.com/ds3231-precision-rtc-featherwing/downloads

body:
Try the following code. It pretty much detects a change in time and when a change has been detected, it will do something. In this case, it will print "do something".

    #include <DS3231.h>
    DS3231 rtc(SDA, SCL);
    String t; //time as a string
    String s;    //second
    String Ps;   //previous second

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

    void loop() {
      t = rtc.getTimeStr();             //finding time
      s = t.substring(6, 8);            //finding seconds

      if(s != Ps)                       //if the time has changed
      {
        Serial.println("do something"); //put whatever you want here
        Ps = t.substring(6, 8);         //redeclaring the previous second because it has advanced
      }
    }


body: Use [this DS3231 library](https://github.com/JChristensen/DS3232RTC). It has a method to set the squarewave `RTC.squareWave(SQWAVE_1_HZ)`


body:
> I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.

<!-- language: lang-c++ -->

>      bool flag = false;
>      ...
>      void rtc_interrupt(void)
>      {
>          flag = true;
>      }

Flags set in interrupts should be declared `volatile` otherwise the compiler may optimize away the comparison to the flag. That is:

    volatile bool flag = false;

---

If you are using the Adafruit library (from the page you linked to) then it should have a couple of functions that can be used to detect when the second has changed, for example:

<!-- language: lang-c++ -->

    DateTime now = rtc.now();
    int second = now.second();
    unsigned long unixtime = now.unixtime();

In either case you just have to check if either one has changed in `loop`. For example:

<!-- language: lang-c++ -->

    void loop(void)
    {
      static unsigned long previousTime = 0;
      DateTime now = rtc.now();
      unsigned long timeNow = now.unixtime();

      if (timeNow != previousTime) {
          digitalWrite(LED_BUILTIN, HIGH);    // flash the led
          digitalClockDisplay();              // this just prints time to serial port
          delay(500);                         // wait a little bit
          digitalWrite(LED_BUILTIN, LOW);     // turn off led
          previousTime = timeNow;             // remember previous time
        }
    }


body:
This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

---

## Interrupt vs pin number

First, this is wrong in your code:

<!-- language: lang-c++ -->

>     attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);

You need an interrupt number, not a pin number. This is correct:

<!-- language: lang-c++ -->

      attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

---

## Pull-up resistor

Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT_PULLUP like this:

<!-- language: lang-c++ -->

      pinMode (rtcTimerIntPin, INPUT_PULLUP);

---

## Testing

I used [this library](https://github.com/adafruit/RTClib/archive/master.zip) from Adafruit.

Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!

<!-- language: lang-c++ -->

    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS3231 rtc;

    const byte rtcTimerIntPin = 2;

    volatile byte flag = false;

    void rtc_interrupt ()
    {
      flag = true;
    }  // end of rtc_interrupt

    void setup () {

      Serial.begin(115200);

      while (!Serial); // for Leonardo/Micro/Zero

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
      }

      // enable the 1 Hz output
      rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

      // set up to handle interrupt from 1 Hz pin
      pinMode (LED_BUILTIN, OUTPUT);
      pinMode (rtcTimerIntPin, INPUT_PULLUP);
      attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
    }

    void loop () {
      if (flag) {
        digitalWrite(LED_BUILTIN, HIGH);    // flash the led
        delay(100);                         // wait a little bit
        digitalWrite(LED_BUILTIN, LOW);     // turn off led
        flag =  false;                      // clear the flag until timer sets it again
      }
    }


message:
Problem building a smart shopping cart

I'm building a smart shopping cart with Arduino for my final year project.

The cart is supposed to be able to follow its user while shopping. I don't know of many feasible indoor positioning systems to use.

**Proposed solution 1**

I have recently seen some RF/ultrasonic positioning systems that make use of:

- one ultrasound transmitter and one RF receiver, carried by the person,
- and two ultrasound receivers and one RF transmitter carried by the robot.

The robots RF transmitter sends out a signal, which when received by the person's RF receiver, triggers the person's ultrasound transmitter to transmit a signal. This signal is received by the robot's two ultrasound receivers (with a distance, d between them), and the distance and angle to the target person can be calculated.

That sounds very feasible, but my question is, if the robot is in a crowded place, where the other people are also carrying ultrasound transmitters and RF receivers:

1. Will the RF signal meant for the owner of the robot be accidentally received by the RF receiver on another person, or is there some kind of unique ID shared between RF receiver/transmitter pairs that could prevent this problem, or maybe some kind of frequency hopping system, so there would be no mistaken identity.
2. How will the ultrasound receivers on the robot be sure that the received signal is from its matching ultrasound transmitter. Again, is there some kind of special ID systems employed by some ultrasonic transmitter/receivers.

**Proposed solution 2**

I have also read about this new device called Trackr, it makes use of bluetooth low energy to track objects based on their proximity to bluetooth enabled devices like smart phones.

Considering a scenario where various bluetooth devices (beacons) are placed at specific points in a room, and the target to be tracked is equipped with a bluetooth emitter/bluetooth chip/dongle.

When the target passes each of those beacons, the signal strength intensity is received and distance from the target is calculated.

I understand this concept, but have some questions:

1. When distance is calculated between beacon and target, what about the angle, how would the robot follow the target based on distance alone?
2. If this method is not accurate enough to be used in a crowded space, what other method can be used, I have checked out some indoor GPS devices and they are way to expensive (above $200).

Would a camera-based tracking system be better and how easy would it be for a non expert like me to implement.

body:
Try keeping it simple. I'd have the person wear and infrared transmitter. Then on the cart have an array of IR-receivers pointing in all directions. That way the cart knows which direction to go.

Next you need to get the distance to the target using e.g. an ultrasonic distance sensor.

Lastly you need to add some bumper sensor, so the cart known when it's running into an obstacle.

Your camera solution might also work, combined with OpenCV. But you can't run that on a measly Arduino.


body:
I have a couple of ideas for you but know these are only suggestions. No hate please.

Have you tought of IR following?

IR is a almost unique signal that only you have. You can either use multiple IR sensors to determine where the emitter is or you can use the servo motor to do it as a radar. Note that you have to isolate each sensor so it knows where you are and it doesn't captures the wave from a different angle by accident.

Extra safety?

You can also incorporate an untrasonic distance sensor so that the cart doesn't bump into you or any one. Like you can say, if the distance is smaller then 12 inchs / 30 cm, stop the cart. It is practically an extra safety feature.


body:
Another solution, along the lines of your camera option, would be to seed the store with Kinect (or Kinect-like) camera systems.  These systems are already designed to track multiple people at once.

Using this method you don't need to equip the shopper with any device, which lowers logistics (how do I get that device back when the shopper exits the building) and tech support costs.

You *might* need to equip the carts with some kind of marker - I don't believe the Kinect systems are designed to track inanimate objects, but I could be wrong.

So challenges to overcome with this system would be:

1. How to track the carts?
2. Kinect doesn't have a very large focal distance so you will need some kind of system to hand shoppers off to the next Kinect when they pass out of range of the one currently tracking them.


body:
I'm going to get a bit ambitious here and suggest something along the lines of what the [Vive](https://www.vive.com/anz/product/) virtual reality system uses. You can see from some of the photos on that site that the headset has lots of sensors on it. Judging by [this article](https://www.gadgetdaily.xyz/heres-exactly-how-the-htc-vive-works/) they detect signals from two base stations. I presume the base stations send IR beams (because radio would not be directional enough). The sensors on the headset are recessed a bit, which would shield them from anything but a line-of-sight beam from a base station.

## The store

Now you don't need anything quite that sophisticated, but something like this might work. First, you have some IR transmitters located around the store, pointing in a criss-cross pattern, like this:

[![Shopping trolley system][1]][1]

The green box is the cart and the bigger boxes the shelving. Now with sensors on the corners of the trolley, pointing in different directions, and with each transmitter sending a differently-coded IR beam, the trolley should be able to work out its position fairly accurately.

## The trolley

By a process of exclusion (if you don't see a particular base station then you are not near it) and inclusion (if you *do* see a base station from a certain sensor then you can deduce a possible area you are in) you should be able to work out your position.

In this case we might expect that the bottom-left-diagonal sensor would be picking up signals from station 1003, and the bottom-right-diagonal sensor would be picking up signals from station 1004. Plus the forward sensor may be getting signals from station 1000 (depending on the range) and the rear sensor from station 1005.

## The shopper

Now we also need to know where the shopper is. If you gave the shopper a vest or belt with sensors on it in a similar way (eg. front, back, diagonal) then similar calculations can work out where the shopper is. Let's assume that each shopper and each trolley are given a unique ID pair (that is, a trolley is associated with a vest). Effectively, each shopper would transmit, every second or so "shopper 5677 is at position x=543, y=666 in the store".

Now we can use radio transmission (from the shopper) to its paired trolley, to tell the trolley where its "owner" is. And assuming the trolley knows where *it* is, then it can work out if movement is required, and if so, in what direction.

## Collision detection

In addition to the above, you would need some proximity sensors on the trolley (eg. ultrasonic) to stop the trolley from driving into other shoppers, display cases, its owner, etc.

## Maze solving

The trolley could have software on it to solve the problem of reaching the shopper. For example, if its way is blocked for too long on the shortest path, it might take an alternative which would be to go to the end of the aisle, go down a different aisle, and then back to where its owner is.

## Extra credit

1. You could make a button on the trolley you push when you are finished. The trolley could then "lead" you to the checkout with the shortest queue at it (or an empty checkout).

2. You could have some buttons on the trolley with major grocery types on it (eg. dairy food, bread, frozen foods). When pressed the trolley could lead you to the appropriate aisle.

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


message:
Soldering Arduino Pro Mini's disaligned pins

I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.

Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

[![Arduino Pro Mini][1]][1]

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

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.

body:
As you are soldering to perf board, perhaps you don't have a printed circuit board specific to your project. If you did, you could modify it, or could make a little intermediate PCB to accept connections from A4 A5 and shift them onto the grid.

If you have some 90°-angle headers, try removing a couple of pins from the plastic former, and 0.05" or 0.15" out from the line of the short side of the L, bend the long leg 90°.  Point the jog along the X or Y axis to align the pin with your perf board grid.


body:
That's indeed quite an problem.

If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.

But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.

[![modify arduino pro-mini][1]][1]

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


body: Easy! I like these ProMinis and use them in lots of projects. Simply exchange one of the 12 way header pin strips for a 14 way one (cheap to buy long lengths of these strips from eBay) add small neatly soldered wires to extend A4 and A5 to the extra pins you’ve added and job done.


message:
Serial.read() is getting a whole string rather than just a character?

From the arduino documentation, the `Serial.read()` function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:

    #include "SPI.h"

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

    void loop() {
      if (Serial.available() > 0) {
        char data1 = Serial.read();
        Serial.print(data1);
      }
    }

And I open the serial monitor and send `"Hello, World!"` I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?

body: You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.


message:
Is analogWrite() inferior to writing directly into registers?

I'm trying to control a DC motor's speed with my Arduino Mega `analogWrite()`, but it doesn't seem to function properly. The motor never completely slows down, just slows down a bit (which is still pretty fast) and then stops spinning completely.

I'm trying to create a robot with different speeds, and it just has to have a slow speed. I know it isn't the code, since the relay and motor works just fine when I use the `digitalWrite()`.

Is it better to write directly into the timer registers to implement the PWM, OR what else could be causing the problem?

body:
1. `analogWrite()` is already PWM, Arduino doesn't produce a true analog signal

2. Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET

3. If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.


message:
Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328

Is it possible to take a bare ATmega328 chip, and with an Arduino as ISP, burn a sketch directly to the chip (e.g. not needing a bootloader), or is the bootloader required to run Arduino sketches? I want to embed the ATmega328 into a different device, and do not want the overhead of the entire Arduino board.

I have looked at https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard and https://www.arduino.cc/en/Tutorial/ArduinoISP, and want to do the "minimal circuit" approach (as my application does not require 16MHz).

The tutorial described has steps to first burn a bootloader, then remove the chip from the Arduino, and then install the sketch. Ideally, I would like to skip the bootloader and removing the chip from my Arduino. Ideally, I would like to do it all from Arduino Studio (not AVRDUDE CLI).

I don't mind "dedicating" my Arduino to this (as I assume it's just burning the ArduinoISP sketch whenever I want to burn to a new ATMega328).

Thanks

body: The bootloader only enables serial programming of the device; it is perfectly possible to run Arduino programs without it provided that the code is compiled with the same hardware options (MCU model, clock speed, etc.) that the standalone device/board uses.


body: It is possible to skip the **Burn Bootloader** step. When you do **Upload Using Programmer** the bootloader is overwritten and thus serves no purpose. However, there is another reason for the **Burn Bootloader** step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the **Burn Bootloader** step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom **Tools** menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.


message:
neopixel not blinking

I have some neopixels, and I have one hooked up to my teensy.
I want to have the color change, when the push button is pressed vs not pressed. The LED will change colour when I upload the code, if I have the button pressed, green, if the button is not pressed, red.

The serial monitor reports changing button press statuses, so I'm not sure why the neopixel isn't changing.

The adafruit website is confusing to me, they have wonderful and involved project examples, but they never have just a basic IO example.

I would appreciate it, if someone could point out where Im going wrong with this code:

    #include <Adafruit_NeoPixel.h>

    #define PIN            0

    // How many NeoPixels are attached to the Arduino?
    #define NUMPIXELS      1

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
    const int buttonPin = 2;
    int buttonState = 0;

    void setup() {
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      pinMode(0,OUTPUT);
      Serial.begin(9600);
      pixels.begin(); // This initializes the NeoPixel library.

    }

    void loop() {

    buttonState = digitalRead(buttonPin);
    Serial.println(buttonState);

        // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
          if (buttonState == LOW) {
              pixels.setPixelColor(PIN, pixels.Color(0,33,0)); // green
              pixels.show();

          }else{
              pixels.setPixelColor(PIN, pixels.Color(66,0,0)); // red
              pixels.show();
            }
            delay(500);
      }

this code compiles, without errors, and uploads just fine, but pressing the button won't change the LED color.

body:
I had a wiring Problem, the device wasn't properly grounded, but still illuminating.

Its working now on pin0, but the idea to use PWM pins is valid. Duly noted.


body: I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.


message:
How to handle an interrupt that interrupts a serial communication?

I am at the moment trying via ros to publish a status message about how many steps a motor has moved.
Problem, is that value doesn't to be readable, or the only thing I am able to read from the topic is a zero.

The value i want to publish is being incremented inside a ISR routine, so i have a single thread that continuesly publishes the messages, and then when an ISR is called, increment it the value.

I tested with serial to see what might have been wrong, but the output of the serial doesn't seem to make any sence, isn't readable.. Is outputs alot of "??" eventhoug I am using the right baudrate and so on. So what is the problem here?

speed_profile.cpp

    #include "speed_profile.h"

    volatile speed_profile profile;
    ros::NodeHandle nh;

    std_msgs::Int16 status_step_count;
    ros::Publisher chatter("tipper_status", &status_step_count);

    void output_pin_setup()
    {
      pinMode(en_pin,OUTPUT);
      pinMode(dir_pin,OUTPUT);
      pinMode(step_pin,OUTPUT);
      nh.initNode();
      nh.advertise(chatter);
    }

    void timer1_setup()
    {
      // Tells what part of speed ramp we are in.
      profile.run_state = STOP;

      // Timer/Counter 1 in mode 4 CTC (Not running).
      TCCR1B = (1 << WGM12);

      // Timer/Counter 1 Output Compare A Match Interrupt enable.
      TIMSK1 = (1 << OCIE1A);
    }

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
    {
      digitalWrite(en_pin,HIGH);
      delay(1);

      unsigned int steps_to_speed;  // Steps required to achieve the the speed desired
      unsigned int acceleration_step_limit; // If desired speed is not achieved, will this variable contain step_limit to when to stop accelerating.

      if (motor_steps < 0)
      {
        profile.dir = CCW;
        motor_steps = -motor_steps;
        digitalWrite(dir_pin,LOW);
      }
      else
      {
        profile.dir = CW;
        digitalWrite(dir_pin,HIGH);
      }

      delay(1);

      // If moving only 1 step.
      if (motor_steps == 1)
      {
        // Move one step
        profile.accel_count = -1;
        // in DECEL state.
        profile.run_state = DECEL;
        // Just a short delay so main() can act on 'running'.
        profile.first_step_delay = 1000;
        OCR1A = 10;
        // Run Timer/Counter 1 with prescaler = 8.
        TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
      }
      else if (motor_steps != 0)
      {
        // Set max speed limit, by calc min_delay to use in timer.
        // min_delay = (alpha / tt)/ w
        profile.min_time_delay = A_T_x100 / motor_speed;

        // Set accelration by calc the first (c0) step delay .
        // first_step_delay = 1/tt * sqrt(2*alpha/accel)
        // first_step_delay = ( tfreq*0.676/100 )*100 * sqrt( (2*alpha*10000000000) / (accel*100) )/10000
        profile.first_step_delay = (T1_FREQ_148 * sqrt(A_SQ / motor_accel)) / 100;

        // Find out after how many steps does the speed hit the max speed limit.
        // steps_to_speed = speed^2 / (2*alpha*accel)
        steps_to_speed = (long)motor_speed * motor_speed / (long)(((long)A_x20000 * motor_accel) / 100);
        // If we hit max speed limit before 0,5 step it will round to 0.
        // But in practice we need to move atleast 1 step to get any speed at all.
        if (steps_to_speed == 0)
        {
          steps_to_speed = 1;
        }

        // Find out after how many steps we must start deceleration.
        // n1 = (n1+n2)decel / (accel + decel)
        acceleration_step_limit = ((long)motor_steps * motor_decel) / (motor_accel + motor_decel);
        // We must accelrate at least 1 step before we can start deceleration.
        if (acceleration_step_limit == 0)
        {
          acceleration_step_limit = 1;
        }

        // Use the limit we hit first to calc decel.
        if (acceleration_step_limit <= steps_to_speed)
        {
          //profile.decel_length = steps_to_speed - motor_steps;
          profile.decel_length = -(motor_steps-acceleration_step_limit); //---
        }
        else
        {
          //profile.decel_length = -((long)steps_to_speed * acceleration_step_limit) / motor_decel;acceleration_step_limit
          profile.decel_length = -((long)steps_to_speed * motor_accel) / motor_decel; //--
        }
        // We must decelrate at least 1 step to stop.
        if (profile.decel_length == 0)
        {
          profile.decel_length = -1;
        }

        // Find step to start decleration.
        //int steps_in_run = motor_steps - steps_to_speed-profile.decel_length;

        profile.decel_start = motor_steps + profile.decel_length;
        //profile.decel_start = motor_steps - steps_to_speed-steps_in_run;

        // If the maximum speed is so low that we dont need to go via accelration state.
        if (profile.first_step_delay <= profile.min_time_delay)
        {
          profile.first_step_delay = profile.min_time_delay;
          profile.run_state = RUN;
        }
        else
        {
          profile.run_state = ACCEL;
        }

        // Reset counter.
        profile.accel_count = 0;
        OCR1A = 10;
        // Set Timer/Counter to divide clock by 8
        TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
        profile.moved_steps = 0;

      }

      while(1)
      {
        cli();
        status_step_count.data = profile.moved_steps;
        Serial.print("profile.moved_steps: ");
        Serial.println(profile.moved_steps);
        Serial.print('\n');
        sei();
        //chatter.publish( &status_step_count);
        //nh.spinOnce();
        delay(1);
      }

    }

    ISR(TIMER1_COMPA_vect)
    {
      // Holds next delay period.
      unsigned int new_first_step_delay;

      // Remember the last step delay used when accelrating.
      static int last_accel_delay;

      // Counting steps when moving.
      static unsigned int step_count = 0;

      // Keep track of remainder from new_step-delay calculation to incrase accurancy
      static unsigned int rest = 0;

      OCR1A = profile.first_step_delay;

      switch (profile.run_state)
      {

        case STOP:
          step_count = 0;
          rest = 0;
          TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
          break;

        case ACCEL:
          digitalWrite(step_pin,!digitalRead(step_pin));
          //delay(1);
          //digitalWrite(step_pin,LOW);
          step_count++;
          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);

          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            profile.run_state = DECEL;
          }

          // Chech if we hitted max speed.
          else if (new_first_step_delay <= profile.min_time_delay)
          {
            last_accel_delay = new_first_step_delay;
            new_first_step_delay = profile.min_time_delay;
            rest = 0;
            profile.run_state = RUN;
          }
          break;
        case RUN:
          digitalWrite(step_pin,!digitalRead(step_pin));

          //delay(1);
          //digitalWrite(step_pin,LOW);
          step_count++;
          new_first_step_delay = profile.min_time_delay;
          // Chech if we should start decelration.
          if (step_count >= profile.decel_start)
          {
            profile.accel_count = profile.decel_length;
            // Start decelration with same delay as accel ended with.
            new_first_step_delay = last_accel_delay;
            profile.run_state = DECEL;
          }
          break;
        case DECEL:
          digitalWrite(step_pin,!digitalRead(step_pin));
          step_count++;
          profile.accel_count++;
          new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest)/(4 * profile.accel_count + 1));
          rest = ((2 * (long)profile.first_step_delay)+rest)%(4 * profile.accel_count + 1);
          // Check if we at last step
          //digitalWrite(step_pin,!digitalRead(step_pin));
          if(profile.accel_count >= 0)
          {
            digitalWrite(en_pin,!digitalRead(en_pin));
            profile.run_state = STOP;
          }

          break;

      }
        profile.first_step_delay = new_first_step_delay;
        profile.moved_steps = step_count;
    }

speed_profile.h

    #ifndef speed_profile_h
    #define speed_profile_h

    #include <Arduino.h>
    #include <ros.h>
    #include <std_msgs/Int16.h>

    // Timer/Counter 1 running on 3,686MHz / 8 = 460,75kHz (2,17uS). (T1-FREQ 460750)
    //#define T1_FREQ 460750
    #define T1_FREQ 1382400

    //! Number of (full)steps per round on stepper motor in use.
    #define FSPR 1600

    // Maths constants. To simplify maths when calculating in compute_speed_profile().
    #define ALPHA (2*3.14159/FSPR)                    // 2*pi/spr
    #define A_T_x100 ((long)(ALPHA*T1_FREQ*100))     // (ALPHA / T1_FREQ)*100
    #define T1_FREQ_148 ((int)((T1_FREQ*0.676)/100)) // divided by 100 and scaled by 0.676
    #define A_SQ (long)(ALPHA*2*10000000000)         // ALPHA*2*10000000000
    #define A_x20000 (int)(ALPHA*20000)              // ALPHA*20000

    // Speed ramp states
    #define STOP  0
    #define ACCEL 1
    #define DECEL 2
    #define RUN   3

    // Pin numbering
    #define en_pin 13
    #define dir_pin 12
    #define step_pin 11

    // Motor direction
    #define CW  0
    #define CCW 1

    typedef struct
    {
     volatile unsigned char run_state : 3; // Determining the state of the speed profile
     volatile unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
     volatile unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
     volatile unsigned int decel_start; //  Determines at which step the deceleration should begin.
     volatile signed int decel_length; // Set the deceleration length
     volatile signed int min_time_delay; //minium time delay c0
     volatile signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
     volatile unsigned int moved_steps; // Used by ros to publish current tipper position

    }speed_profile;

    void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
    void timer1_setup(void);
    void output_pin_setup(void);
    #endif

main.ino

    #include "speed_profile.h"

    void setup() {
      // put your setup code here, to run once:
      cli();
      Serial.begin(9600);
      output_pin_setup();
      timer1_setup();
      sei();
    }

    void loop()
    {
      // put your main code here, to run repeatedly:
        Serial.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        int motor_steps = -3000;//-9600; //23400 -  100%
        // Accelration to use.
        int motor_acceleration = 500;//500;
        // Deceleration to use.
        int motor_deceleration = 500;//500;
        // Speed to use.
        int motor_speed = 1000; // 1000
        compute_speed_profile(motor_steps, motor_acceleration, motor_deceleration, motor_speed);
        while(1)
        {

        }
    }

body: That is QUITE a high baud rate. You might want to lower it. I know that Arduinos running at 8MHZ can barely handle 112500. Do not push it too far. I do not know what Arduino you are using but at 16MHZ, don't push it too far. Also make sure that at that baud rate you supply a lot of juice to your Arduino so that it can run more smoothly.


body:
The problem may be due to something you haven't told us about, so the following suggestions are just general ideas.

First, try out whether serial communication works ok at 230400 when your stepper code isn't running.  For example, add some debug lines to skip over whatever code turns on interrupts to run the stepper, and see if serial  communication is ok.

If serial  communication still fails with stepper interrupts off, try lower serial rates, eg 19200 or 9600.  In addition, in your Publisher add a reasonable delay, eg half a second or a second, between serial writes.  You might also not issue a write whenever the total steps has changed less than a hundred counts, or some similar number.

I'd probably factor toggling `step_pin` out of the `switch`, via code like the following.

    if (profile.run_state != STOP) {
       // Toggle step_pin by writing 1 to its bit in PINB
       PINB = step_pin_mask; // pin 11 = PB3, so mask is 1<<PB3, ie, 1<<3
       step_count++;
    }
    switch (profile.run_state) {
       ...

 Using `digitalRead()` and `digitalWrite()` adds a fair amount of overhead, undesirable in an ISR.  (See their source code at garretlab links, [`digitalRead()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/digitalRead.html) and [`digitalWrite()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_digital.c/digitalWrite.html)) That extra overhead could possibly account for glitches in serial communications.

By contrast, writing a mask bit to an input port is about the fastest way for software to toggle a bit or set of bits.  It is, of course, less flexible and less obvious.


body:
This is highly inadvisable:

>     cli();
>     status_step_count.data = profile.moved_steps;
>     Serial.print("profile.moved_steps: ");
>     Serial.println(profile.moved_steps);
>     Serial.print('\n');
>     sei();

Doing serial prints with interrupts off could hang your sketch because the Serial output routines require interrupts on to work.

Later versions of the IDE might not hang completely but will block until the data can be written.


message:
LCD not doing anything

I just bought an LCD. I connected everything as explained in [this][2] sheet.

This is the code I am using:

    #define RST 3
    #define CE 2
    #define DC 4
    #define DIN 6
    #define CLK 5

    void LcdWriteCmd(byte cmd) {
      digitalWrite(DC, HIGH); //DC pin is low for commands
      digitalWrite(CE, HIGH);
      shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
      digitalWrite(CE, LOW);
    }

    void setup() {
      pinMode(RST, OUTPUT);
      pinMode(CE, OUTPUT);
      pinMode(DC, OUTPUT);
      pinMode(DIN, OUTPUT);
      pinMode(CLK, OUTPUT);
      digitalWrite(RST, LOW);
      digitalWrite(RST, HIGH);
      LcdWriteCmd(0xAE); // LCD set display enabled
      LcdWriteCmd(0x21); // LCD set power COntrol
      LcdWriteCmd(0x14); // LCD bias mode 1:40
      LcdWriteCmd(0xA2); // LCD basic commands
      LcdWriteCmd(0xA9); // LCD all segments on
    }

    void loop() {
    }

The commands I used are in the [command table of this sheet][3]. (page 12)
It is supposed to turn all pixels on now. However nothing happens. All pixels are staying off.

Can you see a problem?

  [1]: http://www.buydisplay.com/default/blue-2-8-inch-128x64-display-serial-lcd-module-spi-with-touch-panel
  [2]: http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf
  [3]: http://www.buydisplay.com/download/ic/UC1701.pdf

body:
I am not so sure the command that you used to turn all pixels on is right. It might say it in the document but you should try to manually turn a couple of pixels on yourself. check the link bellow if you need more assistance with LCDs.

Also be sure that you connected some power and a potentiometer to the contrast pin and/or backlight of the LCD.

https://www.youtube.com/watch?v=dZZynJLmTn8


message:
Arduino Debounce Sketch

I want to use 4 Push Buttons and 4 leds in my project. What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds? So my sketch is only for one push button and one led. So tell me how I can solve this problem.

Here is the code:

    const int buttonPin =2;    // the number of the pushbutton pin
    const int ledPin = 13;      // the number of the LED pin

    // Variables will change:
    int ledState = HIGH;         // the current state of the output pin
    int buttonState;             // the current reading from the input pin
    int lastButtonState = LOW;   // the previous reading from the input pin
    long lastDebounceTime = 0;  // the last time the output pin was toggled
    long debounceDelay = 50;
    void setup() {
    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, ledState);
    }

    void loop() {
    int reading = digitalRead(buttonPin);
    if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
    }

    if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
      }
      }

      // set the LED:
     digitalWrite(ledPin, ledState);
     lastButtonState = reading;
     }

body: Well you declared only one pushbutton and one led. Now do like push1, push2, push3, push4 and led1, led2, led3, led4, and so on. You can also do that with your buttonStates1... Do not forget to declare them as INPUTs or OUTPUTs. Copy paste will help you with this task.


body:
>  What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:

1) study your code to understand how it debounces one input;

2) isolate those parameters / variables used to debounce that specific input;

3) group those parameters / variables into a struct and pass a pointer to that struct to your code;

4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;

5) use that code on as many inputs as you wish.

that's the general approach you take to coding any task.

hope it helps.


body:
I hope this will work for you.

    const int buttonPin1 = 2; // Button 1
    const int buttonPin2 = 3; // Button 2
    const int buttonPin3 = 4; // Button 3
    const int buttonPin4 = 5; // Button 4

    const int ledPin1 = 6; // LED 1
    const int ledPin2 = 7; // LED 2
    const int ledPin3 = 8; // LED 3
    const int ledPin4 = 9; // LED 4

    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;
    int ledState4 = HIGH;

    int buttonState1, buttonState2, buttonState3, buttonState4;

    int lastButtonState1 = LOW;
    int lastButtonState2 = LOW;
    int lastButtonState3 = LOW;
    int lastButtonState4 = LOW;

    long lastDebounceTime1 = 0;
    long lastDebounceTime2 = 0;
    long lastDebounceTime3 = 0;
    long lastDebounceTime4 = 0;

    long debounceDelay1 = 50;
    long debounceDelay2 = 50;
    long debounceDelay3 = 50;
    long debounceDelay4 = 50;

    void setup()
    {
      pinMode(buttonPin1, INPUT);
      pinMode(ledPin1, OUTPUT);
      digitalWrite(ledPin1, ledState1);

      pinMode(buttonPin2, INPUT);
      pinMode(ledPin2, OUTPUT);
      digitalWrite(ledPin2, ledState2);

      pinMode(buttonPin3, INPUT);
      pinMode(ledPin3, OUTPUT);
      digitalWrite(ledPin3, ledState3);

      pinMode(buttonPin4, INPUT);
      pinMode(ledPin4, OUTPUT);
      digitalWrite(ledPin4, ledState4);
    }

    void loop()
    {
      led1Fun();
      led2Fun();
      led3Fun();
      led4Fun();
    }

    void led1Fun()
    {
      int reading1 = digitalRead(buttonPin1);

      if(reading1 != lastButtonState1)
      {
        lastDebounceTime1 = millis();
      }

      if((millis() - lastDebounceTime1) > debounceDelay1)
      {
        if(reading1 != buttonState1)
        {
          buttonState1 = reading1;

          if(buttonState1 == HIGH)
          {
            ledState1 = !ledState1;
          }
        }
      }

      digitalWrite(ledPin1, ledState1);
      lastButtonState1 = reading1;
    }

    void led2Fun()
    {
      int reading2 = digitalRead(buttonPin2);

      if(reading2 != lastButtonState2)
      {
        lastDebounceTime2 = millis();
      }

      if((millis() - lastDebounceTime2) > debounceDelay2)
      {
        if(reading2 != buttonState2)
        {
          buttonState2 = reading2;

          if(buttonState2 == HIGH)
          {
            ledState2 = !ledState2;
          }
        }
      }

      digitalWrite(ledPin2, ledState2);
      lastButtonState2 = reading2;
    }

    void led3Fun()
    {
      int reading3 = digitalRead(buttonPin3);

      if(reading3 != lastButtonState3)
      {
        lastDebounceTime3 = millis();
      }

      if((millis() - lastDebounceTime3) > debounceDelay3)
      {
        if(reading3 != buttonState3)
        {
          buttonState3 = reading3;

          if(buttonState3 == HIGH)
          {
            ledState3 = !ledState3;
          }
        }
      }

      digitalWrite(ledPin3, ledState3);
      lastButtonState3 = reading3;
    }

    void led4Fun()
    {
      int reading4 = digitalRead(buttonPin4);

      if(reading4 != lastButtonState4)
      {
        lastDebounceTime4 = millis();
      }

      if((millis() - lastDebounceTime4) > debounceDelay4)
      {
        if(reading4 != buttonState4)
        {
          buttonState4 = reading4;

          if(buttonState4 == HIGH)
          {
            ledState4 = !ledState4;
          }
        }
      }

      digitalWrite(ledPin4, ledState4);
      lastButtonState4 = reading4;
    }


message:
How to get the rightmost four bits from a byte

I have a byte that I am looking to break into 2 nibbles. The leftmost nibble I can get easily via shifting right 4 times. However, I can't figure out how to get the rightmost nibble. Any ideas?

body:
Just mask it with an AND operator:

    val = var & 0xF;


message:
Using SoftwareSerial to send data to itself

I'm debugging a project which includes SoftwareSerial. I'm not convinced the serial connection behaves as expected, so I came up with the following simple test:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10,11); // RX, TX

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

      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i=0; i <= 10; i++){
        delay(10);
        mySerial.write(i);
      }
    }

I connected pin 11 to pin 1 (arduino Uno), hence forwarding the data of the software serial connection via the default (hardware) serial connection to my computer. But no data is coming through.

Am I missing something?

body:
If you are hoping to see the results in the serial monitor, you need to read it in and send it back (so it ends up on the USB port). Like this:

<!-- language: lang-c++ -->

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX

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

      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i = 0; i <= 10; i++) {
        delay(10);
        mySerial.println(i);

        while (Serial.available ())
          Serial.write (Serial.read ());
      }
    }

Now you have to connect pin 11 to pin **0** (not pin 1) because that will now be the Serial Rx pin.

I think your method failed because with Serial active the Serial hardware was trying to drive pin 1 high (ie. idle) which was conflicting with the data from pin 11.

---

An alternative is to not do a `Serial.begin()` - which therefore does not initialize the serial hardware and it doesn't conflict any more. This also works:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup() {
      // starting the software serial
      mySerial.begin(4800);
    }

    void loop() {
      for (int i = 0; i <= 10; i++) {
        delay(10);
        mySerial.println(i);
      }
    }

Now you connect pin 11 to pin 1 as you originally wanted.

---

Notice I changed your `mySerial.write(i);` to `mySerial.println(i);` so you get correct data output (numbers, not control characters).


message:
How to represent -1 as a byte

I want to initialize the value of byte to -1. When I just use `byte num = -1` the value ends up being a decimal 255. I've also tried `int8_t number = -1` and then `byte num = number` but this didn't work either.

body:
A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a `char` (-128 to +127) or an `int` (-32768 to +32767).