message:
LED bar graph script not working

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

    #include <Wire.h>

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

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

    void loop() {

      ledBarSetup(5);
    }

    void ledBarSetup(int v) {

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

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

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

      Serial.println(convert);

      ledBar(convert);

    }

    void ledBar(int n) {

      int startingPin = 2;

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

        if (thisPin <= n) {

          digitalWrite(thisPin, HIGH);

        } else {

          digitalWrite(thisPin, LOW);

        }

      }

    }

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


sender: user

message:
Set EEPROM from PC before program

I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.

All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?

Thanks for your help!

-sam

sender: assistant

body:
I think here is a confusion about the three types of memory. EEPROM, FLASH and SRAM are completely separate. EEPROM is like your file storage. FLASH contains you program and static values. SRAM is the memory the program is working with.

Static values are loaded from FLASH into SRAM upon start unless you declare your static content not to load automatically by using the according Macro `PROGMEM`. In that case it does not eat up your SRAM until you manually read it from FLASH into SRAM. `#include <avr/pgmspace.h>` is used for this ([pgmspace.h][1]).

EEPROM is not loaded automatically and therefore must be read explicitly. `#include <avr/eeprom.h>` contains all the functionality ([eeprom.h][2]).

I'm not sure about the Arduino IDE but with avrdude you can program the EEPROM separately without having the values been predefined in your program. The [third example][3] in the AVRdude manual shows how to flash the program, eeprom and fuses at once.

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html
  [3]: http://www.nongnu.org/avrdude/user-manual/avrdude_6.html


body:
The simplest way would be to have **two** sketches.

One that will store all the strings into EEPROM.

After that you can upload the second actual sketch that uses the values stored in EEPROM.

You only need to upload the first sketch if any of the strings change.

There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.


body:
You don't need two sketches:

    #include <avr/eeprom.h>

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

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

    void loop() {}

Compile (Sketch>Verify/Compile) the source above and you should find file named `<sketch-name>.ino.eep` in project's build directory.

For Arduino Nano, you can just run `avrdude` with `-U eeprom:w:<path-to-eep-file>:i` option before Sketch>Upload.

For Arduino Uno, however, you must first program it's EEPROM using programmer, since Optiboot doesn't support writing to EEPROM. <s>Or you can burn it with Arduino Nano bootloader once (Tools>Board>Arduino Nano, Tools>Processor>ATmega328, Tools>Burn Bootloader) and then use the procedure for Arduino Nano.</s> (Arduino Uno and Nano bootloaders use different baud rates).


message:
Problems with running multiple ESC

I've written a program which allows me to use my `Arduino Uno` to send a `PWM` to an **Electronic Speed Controller**. 5 seconds after startup the ESC is sent a config via `PWM` to signal the low to high `PWM` range to be used by the ESC. Then I can type into the `Serial Monitor` a single digit 0-9 to pick the `PWM` I want to send to my ESC. *(n\*2 = pwm)*

This works great when running code for *one* ESC, but adding code for a *second* ESC causes significant issues (I only have one ESC plugged in). When I send a `serial` command to specify `PWM` rate, my ESC only receives the `PWM` change *sometimes*. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.

***What's going on here?***

# Code

**WorkingESCSoftware** *(main file of .eno)*

    #include <SoftwareServo.h>
    #include "TestClass.h"

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

    TestClass t, t2;

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

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

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

**TestClass.h**

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

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

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

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

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

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

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

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

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

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

body:
You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.

[Semiphoras][1] are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.

In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.

  [1]: https://en.wikipedia.org/wiki/Semaphore_(programming)


message:
[Arduino UNO]Receive Serial Data from multiple sources

I have the following system:

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

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

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.

The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!

**I can't use SoftwareSerial as I don't want any delay on master board!**
I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.

So there are are my approaches:

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

Anyway, what possibilities would I have to play around?

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


body:
[This answer](https://arduino.stackexchange.com/questions/26240/which-pins-of-an-arduino-uno-can-be-used-as-tx-and-rx-pins-for-connecting-to-gsm/26277#26277) summarizes the possibilities:

1) `HardwareSerial` is always best.  You are using that for WiFi.

2) [`AltSoftSerial`](https://github.com/PaulStoffregen/AltSoftSerial) is the best software serial library, but it requires pins 8 & 9.  Very efficient and non-blocking!  Strongly recommended for the GPS connection.

3) [`NeoSWSerial`](https://github.com/SlashDevin/NeoSWSerial) is next best, but it supports only 9600, 19200 and 38400.  It is non-blocking on receive, so it could be used for the GPS connection.

4) `SoftwareSerial` is the worst.  :P  Not suitable for the GPS connection, as you have discovered.

I'll also mention my GPS library, [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It is smaller and faster than other libraries, and there are examples that show how to make it run *during* the RX character interrupt, saving even more time.  It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.


message:
Power ESP01 in forest

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

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

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

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue.
The battery, if SLA, is going to be a great big lump that could be dangerous if damaged.
The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.

Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.


message:
Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload?

I've been asked to do a small project using an Ada BlueFruit board. It has a [ATMega32U4][1]. The 32U4 [comes from the factory with a bootloader pre-installed][2]. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?

Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

[1]: http://www.atmel.com/devices/ATMEGA32U4.aspx
[2]: http://www.atmel.com/Images/doc7618.pdf

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

You would have to ask Adafruit that.

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

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

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

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

---

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

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

> and if I can use the Flip tool to upload

I don't see why not. Or you could use the dfu-programmer as I describe in my post [How to flash the USB chip on the Arduino Uno](http://www.gammon.com.au/forum/?id=11635&reply=2#reply2).


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


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

The Arduino IDE allows you be lazy about #includes and forward references to functions, but it won't get in your way if you choose to write correct code.

I write standard C/C++ and switch back and forth between Eclipse (no over-helpful pre-processing) and the Arduino IDE. The Arduino IDE knows better; it just CYA (covers your assumptions :) in case you don't.


message:
How to configure 2nd Quadrature Decoder IO pins in Arduino IDE

I am working to read two quadrature encoders using a single Arduino DUE, as part of my summer vacations project. According to the following link
http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP, the SAM3X8E has 2 quadrature decoders in it. Now I am not being able to understand how can I initialize this second quadrature decoder. According to **Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483**  _Pg16_ we have to first configure the IOPINS for QDEC1. I have to do that same task in Arduino IDE instead of Atmel Studio.

This is the code that I have found and works well to read encoder using QDEC0. However, I now need to read the encoder using the second quadrature decoder, whose input pins are TIOA6 , TIOB6 which correspond to Pin 5 and 4 of Arduino DUE. After reading the Atmel SAM3X datasheet, I think I should change "TC0" with "TC2" to make the second decoder work. However, this doesn't work. I think it does not work because channel 2 is busy in time base calculations.
In Application Note _5.52_ **QDEC Speed Measurement Mode** point 2 says to Initialize TC0, TC1, TC2. If I wanted to used other encoder which timer instance will be used.

    /*
    ** Quadrature Encoder on Arduino Due in "Speed Mode"
    ** Will not work on other Arduino types because of a specific hardware requirement.
    **
    ** @bungle99 / 2014-02-28
    **
    ** Many thanks to @Designservicecorp (notably post #32 and post #42) that gave me the base to work from.
    **
    ** Uses *hardware* to do the heavy lifting of interpreting the Encoder output, which gives it significant
    ** advantage over other Arduino's for this use case. Eg many people have reported their Unos maxing out
    ** or skipping counts when interpretting high RPMs, whereas people using the Due in hardware mode have
    ** reported better success with high RPMs.
    **
    ** This particular example puts the hardware into "Speed" mode, whereas other examples in this thread use
    ** "Position" mode (see posts 32, 42). The one example in the thread that attempts Speed calcs uses Position
    ** Mode and uses an interrupt on the Z Index axis to manually apply a time period (needed to caculate speed)
    ** on each rotation.
    **
    ** This code below has been used in tests (using Lego NXT and a gear train for driving / comparison) to
    ** ~3,500 RPM with a 1,024 PPR Encoder (4 x 1,024 Edges). The Arduino didn't seem to struggle and the
    ** numbers (eg RPM) matched fairly closely with the Lego (eg as a sanity check, the calcs in the code look
    ** correct).
    **
    ** I bought one of these encoders, which seems ok;
    **
    **   * http://proto-pic.co.uk/rotary-encoder-1024-p-r-quadrature/
    **
    ** Great service from proto-pic. The encoder specs are officially
    **
    **   * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/E6B2Encoders.pdf
    **
    ** But look an awful lot like this one too (which is easier to read)
    **
    **   * http://www.ia.omron.com/product/item/e6b27032r/index.html
    **
    ** Note that this Encoder is rated at 5V min. I've successully powered it off the 5V Arduino pin header,
    ** and it doesn't work off the 3.3V one. At 5V, the outputs need to be run through some resistors to bring
    ** them into tolerance of the Arduino inputs.
    **
    ** The inputs are 2 and 13 (and optionally A6 for the index).
    **
    ** The test hardware (some Lego NXT servos and gear train) was unable to turn any faster (more gears
    ** stalled the servos) - eg the Arduino Due was not the limiting factor. At this speed, the Due Hardware
    ** is dealing with approx 238,000 edges per second.
    **
    ** This example offloads the speed calculation onto the hardware, meaning no interrupt is required.
    ** In addition, the index is not required either, so it allows speeds to be seen even for rotations that
    ** don't pass the index marker (for example, slow rotations needing a speed before a complete rotation).
    ** That said, index is available if you want it and the docs suggest you can still use it (and others) as
    ** interrupt if you wish.
    **
    ** NB There appears to be a myriad of features on the Chip that have not been touched. Eg you can still add
    ** interrupts to this code to do other things; eg passing the Z index, direction changes. There are also
    ** filters available if your encoder suffers from noise (eg vibrations). All this is available to play with
    ** another day :)
    **
    ** Code appears to work, but no guarantees. Understand it. Test it. Feedback to the group. YMMV. Don't blame
    ** me if it doesn't work or expolodes!
    */

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

    void setup() {

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

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

      REG_PMC_PCER0 = PMC_PCER0_PID27
                    | PMC_PCER0_PID28
                    | PMC_PCER0_PID29;

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

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

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

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

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

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

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

    void loop() {

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

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

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

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

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

Motor with Encoder I am using is:
[![enter image description here][1]][1]

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

body:
TC blocks are pretty much identical (except TC1 doesn't have wired some signals to pins)

So you have to copy registers containing `*_TC0_* =` and replace TC0 to TC2.

Plus PC25 and PC24 should be set to its alternate function PIO_PERIPH_B. Something like this:

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

Also TC6, TC7 and TC8 clocks must be enabled by:

    REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

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

[![TC_CMR WAVE=0][1]][1]

[![TC_CMR WAVE=1][2]][2]

Full configuration:

      REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
      REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

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

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

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

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

  [1]: https://i.stack.imgur.com/kRDgl.png
  [2]: https://i.stack.imgur.com/amN6y.png


message:
NodeMCU : Input pullup in A0

I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.

I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.

I am setting up the gpio in the setup method like this:

    void setup(void){
        pinMode(sensorPin, INPUT_PULLUP);
        ...

And my sensorPin variable is declared in the beginning of the sketch

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

body:
As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:

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

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

Special thanks to Majenko for his time and patience. Cheers!


message:
Sensirion library for SHT7x humidity sensor

I have following code (and it works great!) for SHT75 Sensirion sensor.
<!-- language-all: lang-cpp -->

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

    #include <Sensirion.h>

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

    Sensirion sht = Sensirion(dataPin, sclkPin);

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

    byte shtState = 0;
    byte ledState = 0;

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

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

    void loop()
    {
      curMillis = millis();

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

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

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

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

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


message:
What is the variable pot exactly for in arduino sensors boards?

I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.

Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

body:
It's for sensitivity adjustment.

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

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


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


message:
External power supply?

I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).

Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.

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

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

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

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

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

No.


message:
Supplying power to arduino by 5V and 2A adapter

Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?

More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

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

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

Yes, you can.


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


message:
EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected

I am having a very weird and frustrating issue with this ESP01. I am creating a shield on protoboard, and everything checks out as far as I can tell. I am using a 3.3v voltage divider (1k and 2.2k) from arduino TX to ESP RX.

When I connect the ESP straight to the arduino Mega 2560, it works fine. When I connect the ESP to my protoboard, the blue led stays lit. Now here's he weird part.

I broke out the protoboard header with jumpers to the ESP, 3.3v to vcc and ch_pd, gnd to gnd in my header. Bypassing the logic voltage divider on my protoboard results in a working ESP8266.

While still powered up, I moved the Tx/Rx to the header, through the voltage divider, and it still works! But when I disconnect USB from the Arduino, then reconnect, the blue led stays lit, until I bypass the voltage divider, connect to the ESP, then connect back to the divider.

I am currently testing my code with a simple serial relay sketch, ESP on Serial3.
I have nothing else connected to ESP besides vcc, ch_pd, gnd, tx and Rx.
I am connecting to the arduino and ESP on 115200 baud. The ESP replies without garbage on 115200 when connected straight to Serial3 rx/tx

I thought insufficient power may have been an issue, using the mega's 3.3v for vcc, so I built a voltage regulator circuit converting a 9v battery to 3.3v (well 3.75, using an LM317T with R1=330ohm/R2=660ohm because it's what I had on hand) and there was no change in performance, besides the LEDs being slightly brighter. The ESP still functioned with RX/TX straight to the mega while connected to the 3.75v supply.

I know pics would help a lot, and I can post some later tonight after work. My wife, sensing my frustration, told me to set everything down and go to work so I wouldn't break anything, so I am asking around for possible fixes for when I get home.

I appreciate any and all replies, and will provide any necessary clarification.

Thanks,
Vl4d

body:
A wiring diagram would help.

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


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


message:
How to connect Arduino to headphone jack?

I would like to connect a headphone jack to my Arduino and make it as an output. I mean I would simply send some simple beeps.

I know that there is a breadboard friendly headphone jack, but I don't know how to wire it. I really don't know if I can simply connect the Arduino to the headphone jack, or I will need some resistors, etc. Will I need some voltage measurements?

Also, can I do this simply by connecting the parts of the jack ( right, left, GND) to the Arduino?

So could you please help me with this?

body:
[This][1] project connects the headphones directly to a digital pin.  Here is the schematic:

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

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

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

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.

The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.

  [1]: http://www.echanter.com/home/howto-build
  [2]: https://i.stack.imgur.com/oWNwS.png
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardUno


body:
I had the same problem and here how I figured out a solution,

Assume your stereo jack is connected to the folowing pins;
Pin 9 = Left stereo
Pin 10 = Right stereo
GND = Ground

The solution relies on using arduinos inner circuitry.
Pin 9 and Pin 10 are our pins to control left and right stereo sounds.
We need a third pin which will be the main output source for stereo both(left and right) condition.

Say this pin be Pin8.
Connect Pin8 to Pin9 and Pin10 by two resistors of 1kOhm or similar depending on your sound level choice.

When you seet pin8 mode to OUTPUT, pin 9 and pin 10 modes to INPUT, and when you play a tone  at pin8 as tone(pin8,duration,frequency) will play stereo on the headphone.

On the other hand if pin9 is set to OUTPUT and pin10 set to INPUT, playing tone at pin8 will flow the current through right pin of the stereo jack, right sound.

Similarly if pin10 is set to OUTPUT and pin9 is set to INPUT,and tone played at the pin8 send the current through left stereo jack connected to pin9, left sound is played.

Hope this helps.


message:
User-Agent question

I've seen a few different User-Agents used in demo sketches and am curious as to what the various User-Agent options are and how to determine which one to use.

For example...

    `User-Agent: Mozilla/4.0`

    `User-Agent: Arduino/1.0`

    `User-Agent: ESP8266`

    `User-Agent: ArduinoWiFi/1.1`

I've used Arduino/1.0 successfully with an Uno/WiFi101 but want to use an ESP8266 now.  Do I continue using Arduino/1.0 or switch to ESP8266 (Arduino IDE 1.6.5)?

When would someone use Mozilla?

Any guidance is appreciated.

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


message:
Ignore event until x minutes

I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.

Here is the code I come up with:

    if (digitalRead(sensor_event)==HIGH)
      {

          if (RTC.read(tm)) {

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

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

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.

The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).

Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.

Thanks

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

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

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


body:
Calculate target time, rollover if necessary and check if time is already passed that point. As long as you are checking the time multiple times per minute you shouldn't run into any issues.

    if (digitalRead(sensor_event)==HIGH)
    {

      if (RTC.read(tm)) {

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

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


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

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

    void loop()
    {
        uint32_t now = millis();
        static uint32_t last_event = -hold_time;

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

If you can have 49.7 days without a single event, then this approach
fails because `last_event` is ambiguous. The simplest solution is
probably to implement a state machine with only two states, as the event
detection is either “on hold” or it is not:

    void loop()
    {
        uint32_t now = millis();
        static bool on_hold;
        static uint32_t last_event;

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

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

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

[millis rollover]: https://arduino.stackexchange.com/a/12588


body:
Just to save a lot of headaches for everybody who wonders here and still have  a problem with this code:

    uint32_t hold_time = 1*60*1000; // 1 minute will never work

    uint32_t hold_time = 60000; // 1 minute will work

You must define the value as an EXACT number, not putting in multiplication and rely on the compiler to calculate it for you.

Probably because it's unsigned long and screws up something with the multiplication but with the first example you will be put on hold for days, maybe forever.


message:
Delaying pushbutton input to microcontroller while it's busy processing I/O

I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.

Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.

Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.

I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?

Below is the simplified code

    #include <SPI.h>
    #include <Wire.h>
    byte Input=1;
    volatile byte Check=1;
    volatile byte Output=1;

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

    int interruptPin=2;

    int espPin=7;

    char arduinoStatus[100]="\0";

     void pin_read(){

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

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

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

         digitalWrite(latchPin, HIGH);

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

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

        Check = Check<<1;

        }

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

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

    }//pin_read

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

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

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

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

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

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

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

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

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

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

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

body:
Without looking any further than the first `delaymicroseconds()` command I would say that that's where the trouble lies. The `delay()` functions are very handy for getting the beginner's first LED to blink and are a big problem after that. The problem is that the CPU is completely tied up during the delay and can't do anything else other than interrupts and you only have a limited supply of those. Your button press is missed.

You need to develop your own timers in the code and keep the main loop running constantly checking on each pass to see if the delay is complete.


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


message:
Connecting Bluetooth module to Arduino Uno without RX/TX pins

Can I connect a Bluetooth module to usual digital pins, other than D0/D1 (RX/TX) pins as the shield is already using the D0 and D1 pins?

My Bluetooth module is an HC-05 MODULE.

body:
Classic Arduinos use pins 0 and 1 for serial communication to the host computer, so it is problematic to connect a bluetooth module there anyway - it can be done, but basically means that programming the board and communicating with it by serial will not work (at least not reliably) until the interfering bluetooth module is removed or disabled.  For these boards you need to use a software serial instance to talk to the module, and you can put it on most any digital pins.

ATmega32u4 boards like the Leonardo do not have debug/programming on pins 0 and 1 but do have a hardware UART there, so those would be the best choice for a bluetooth module, but you can still use software serial.

The Arduino Mega has additional hardware serial pins that would be good choices, but you can use software serial.

Various ARM based boards with Arduino ports typically have additional hardware serial pins which you should use.  Software serial may or may not be an option on these (it's not that an implementation cannot exist, but that software serial is generally disadvantageous, so when a chip has more hardware UARTs that particular function may not be ported).


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


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

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


message:
Problem with wrapping Adafruit Motor Controller function calls in a class

I'm working on an Arduino robot and I ran into a problem when reorganizing my code. I have an Adafruit Motor Shield v2.3 connected to an Arduino Uno. My robot can be controlled using a bluetooth connection (BlueSMIRF module) or it can be told to avoid obstacles using an ultra sonic range finder.

Everything worked fine and the robot moved nicely until I decided I wanted to organize the code better, so that my code for moving the robot would be in a separate class, my code for servo movement also in a class as well as my code for the logic for movement (received bluetooth command - do this, or avoid obstacles like so, etc.). Suddenly, none of the motors respond or just one.

I'm not sure if I have a problem with my C++ and passing pointers to my functions or what is going on...

Here is my main .ino file, its relevant parts, I left out stuff that concerns the bluetooth connection etc. And yes, I know the hardcoded include paths look ugly, I'll figure out what to do with includes at some point... :

    // bluetoothRobot.ino

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

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

    MotorController* motorController;

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();

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

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

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

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

Here is my MotorController.h:

    // MotorController.h

    #ifndef MotorController_h
    #define MotorController_h

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

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

    #endif

And here is MotorController.cpp:

    // MotorController.cpp

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

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

                case 'B':
                  moveBackward();
                  break;

                case 'L':
                  turnLeft();
                  break;

                case 'R':
                  turnRight();
                  break;

                case 'S':
                  stopRobot();
                  break;

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

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

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

      }

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

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

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

      }

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

I used to have a constructor for MotorController with the Motor Shield library `AFMS.begin()` call in it and all. But this caused the Arduino to constantly reset for some reason. I coudn't understand why but I moved the motor configurations and call to `begin()` to my .ino file where the problem doesn't occur.

**Problem:** What happens with the code as it is, is which ever pointer to motor is passed last seems to work and that particular motor turns but the others won't. If I comment out the call to `setRobotSpeed` in `MotorController::start`, nothing happens with any motor even though speed is also set in the relevant functions.

As said, the robot worked fine when the code was in my .ino file. Although, for some reason I had to call the Motor Shield library's `begin()` function always before any other commands to motors. So it was called every time the user told the robot to move forward, move backward etc. Otherwise nothing happened with the motors. Now, if I add a call `AFMS->run()` to my MotorController.cpp, the Arduino starts to constantly reset...

Also, none of the other stuff (blueSMIRF, the range finder code etc.) should interfere since they were also there when it worked and I even commented out that stuff.

I'm baffled. Maybe its some silly mistake with my C++? Or is there really something weird going on here?

Any help would be much appreciated, I've spent hours trying to figure this thing out! Thanks in advance!

body:
One thing about instantiating classes before `setup()` is called is that `init()` (which you don't see) may undo all of your careful setup.

Your code starts:

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

but these are constructed before `setup()`. And then you call `MotorController::start()` with those values. You haven't provided the code for `AFMS::getMotor()` - so it may be doing things internally that is undone by `init()`.

Instead of creating the whole pointer, why not do this:

    const byte rightRearMotor = 1;
    const byte leftRearMotor = 2;
    const byte rightFrontMotor = 3;
    const byte leftFrontMotor = 4;

and then callig `AFMS.getMotor()` inside `MotorController::start()`:

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


body:
The obvious issue in your current code is that `motorController` is a pointer to your class but I don't see any place it was instantiated properly.

Hence, it points **anywhere** the first time you use it, which can explain resets of the MCU.

Now, either you keep it as a pointer:

    MotorController* motorController;

**And then you instantiate it in place**:

    MotorController* motorController = new MotorController();

**Or you can also instantiate it in `setup()` as first line (ie before it is used anywhere else)**:

    void setup() {
        motorController = new MotorController();
        ...
    }

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

    MotorController motorController;

Now everywhere you were using `motorController->xxx` you'll have to replace it it with `motorController.xxx`.

That should remove the most important bug of your current code (I can-'t tell if there are other issues but this one must be fixed in priority).


message:
SOLVED: Soft Power On SIM900 module - JP pads missing!

I have this SIM900 board and working just fine.
But i can't find a way to soft power on this board from arduino.
I read for JP pads. They need soldering first, but from my board this JP pads missing.
Know someone other way to soft power on this from arduino?
[![enter image description here][1]][1]

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

body:
OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:

      pinMode(9, OUTPUT);
      digitalWrite(9,LOW);
      delay(1000);
      digitalWrite(9,HIGH);
      delay(2000);
      pinMode(9, INPUT);

I don't know how it works, but it solves my problem.

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

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


body:
Near C6 and J15 you have 2 points.  You need to solder it.
Before soldering yon can hold wire on one of it (down pin , during code execution).

![1]][1]

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


message:
Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module

I'd like to receive on my arduino live coordinates of planets of solar system. Because there are already websites listing every planet coordinates, I thought it would be easier to just use a wifi module (in my case an ESP8266) and connect the arduino to one of these website.

I have the option of getting it from [this][1] website, but I have no idea how to do that.

The other way of doing it may be to connect to [Horizon][2] via their telnet server at this adress :telnet://horizons.jpl.nasa.gov:6775

Though I know how establish a connection with this server on my computer using Putty, I have no idea how to connect my arduino to it, execute commands, and, more importantly, get data (RA and DEC) of every solar system main objects.

This is my first time using Arduino wifi module, so I have no experience with it, and I don't know what it is capable of.

Thanks a lot for your attention,

Thomas

  [1]: http://theskylive.com/planets "Live coordinates of planets"
  [2]: http://ssd.jpl.nasa.gov/?phys_data

body:
That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.

A much easier task is to *scrape* the website since that just returns text which you then need to search through a bit at a time looking for the information you need.


message:
NFC 'dynamic' UID database

Hi SE (and Majenko in particular, if I'm lucky) -
I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE [sic] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

body:
You got me ;)

Since a UID is a fixed size you don't need to think in "lines", only in bytes.

The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).

You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.

    myFile.seek(recordNumber * 8);

If `.seek()` returns `false` then you have reached the end of the file.

So to find a tag you can:

    myFile.seek(0); // Start at the beginning of the file
    int recno = 0;
    char foundUID[8];
    bool found = false;
    while (myFile.read(foundUID, 8)) {
        if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
            found = true;
            break;
        }
        recno++;
    }

At the end of that `found` will be `true` if there is a match, and `recno` will be set to the record number. Now the magic begins...

If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:

    myFile.seek(recno * 8);
    for (int i = 0; i < 8; i++) {
        myFile.write(0xFF);
    }

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.

Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.

It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.

If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the `\r\n` line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

----

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.


message:
Issues graduating to AVR-C

I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers.

I don't have an ISP, so I'm using one of my Arduino UNOs with the ArduinoISP sketch. The problem is that when I try to run avrdude it gives me this error:

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

However, when I try to run the command with the sugested -F it uploads the code to the Arduino UNO I'm using as an ISP instead of the ATmega328p on my breadboard.

Does anyone have any idea about whats going on here, or how to fix it?

body: "invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).


message:
Strange adding behaviour

I have an Arduino Nano and was adding up some values `2^i from 0..7`:

    void setup() {
      Serial.begin(9600);
      int i,k;
      k = 0;
      for (i=0;i<8;i++){
         k += pow(2, i);
         Serial.println(k);
      }
    }

Those numbers should sum up to `255`, but that's the output:

    1
    3
    6
    13
    28
    59
    122
    249

Is my Arduino not working or what can be the reason for this behaviour?

body:
No, there is nothing "wrong" there. In fact it's the expected results.

The problem here is that `pow()` returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.

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

        int t = 0;
        for (int i = 0; i < 8; i++) {
            float f = pow(2, i);
            int d = f;
            t += f;
            Serial.print("2^");
            Serial.print(i);
            Serial.print(": float = ");
            Serial.print(f, 10);
            Serial.print(" int = ");
            Serial.print(d);
            Serial.print(" total = ");
            Serial.println(t);
        }
    }

    void loop() {
    }

    2^0: float = 1.0000000000 int = 1 total = 1
    2^1: float = 2.0000000000 int = 2 total = 3
    2^2: float = 3.9999995231 int = 3 total = 6
    2^3: float = 7.9999980926 int = 7 total = 13
    2^4: float = 15.9999961853 int = 15 total = 28
    2^5: float = 31.9999885559 int = 31 total = 59
    2^6: float = 63.9999771118 int = 63 total = 122
    2^7: float = 127.9999542236 int = 127 total = 249

Instead you should use bit-shifting to perform the same operation on an integer:

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

        int t = 0;
        for (int i = 0; i < 8; i++) {
            int d = 1 << i;
            t += d;
            Serial.print("1<<");
            Serial.print(i);
            Serial.print(": int = ");
            Serial.print(d);
            Serial.print(" total = ");
            Serial.println(t);
        }
    }

    void loop() {
    }

    1<<0: int = 1 total = 1
    1<<1: int = 2 total = 3
    1<<2: int = 4 total = 7
    1<<3: int = 8 total = 15
    1<<4: int = 16 total = 31
    1<<5: int = 32 total = 63
    1<<6: int = 64 total = 127
    1<<7: int = 128 total = 255


body:
Granted that integer arithmetic is a computationally better approach to this problem; if your intent was to learn to use floating point and float to int conversions, then you need to round up the floating result before the conversion truncates it. As you saw in @Majenko's example, the floating results are close but not quite exact. In your own example, you'd change

    k += pow(2, i);

to

    p = pow(2, i); k += (p < 0. ? -0.5 : 0.5);

to so the float would truncate to the nearest int instead to the next lower int.


message:
interrupting an interrupt

What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.

body: It won't be called until the current interrupt is finished. As soon as the current interrupt function returns the pending interrupt would trigger and call the ISR again.


body:
1. the timer will set the Timer Interrupt Flag (TIFR0 register)
 2. The ISR will be called, and the flag will be cleared
 3. you do some long calculations or something
 4. the timer will match OCR0A, and set the interrupt flag again.
 5. you calculations are done, and the ISR function will end.
 6. the uC will jump back to the main loop code, and execute 2 1 instructions.
 7. The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.

You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.


message:
Why is one LED more luminous (brighter) than the other?

Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.

If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

[![Arduino UNO and Breadboard setup][1]][1]

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

body:
Just like men, all LEDs have been made different.

Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, **luminous intensities**) when they are traversed by the same current (**forward current**).

LED luminous intensity is a function of the current that traverses it (among other factors).

If you want the same brightness for those 2 LEDs, then you'll have to:

1. Get both LEDs datasheets (should be a couple of A4 pages for each)
2. Find the luminous intensity/forward current function curve in each
3. Determine which brightness you want for both
4. Deduce the current for each
5. Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.

**Simpler,** you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.

**Be careful with pot manipulation though,** as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).


message:
Sketches won't upload to Uno

Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:

    Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
    D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
    An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.

The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.

The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

body:
assumption is windows, so with the old ide's a reboot to free up the usb ports, or sometimes simply swapping the usb port, and changing the port in the tools > port menu.

does it identify the board you are using when you choose the port? (Genuino / Arduino)


body:
You can set the verbosity level in the Arduino IDE:

* File menu
* Preferences
* Settings tab
* "Show verbose output during" => check "upload"
* Click OK

Upload again, and note the additional output telling you what is wrong.

It should also point you to [this URL][1], which points out the most occurring issues.

The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).

  [1]: https://www.arduino.cc/en/Guide/Troubleshooting#upload


body:
In my experience, sketch upload error occurred due to 4 different mistakes:
(1) Silly mistake: did not connect the serial cable to the PC
(2) I did not choose the right com port (Tools/port).
(3) I chose the wrong board type (Tools/board). connected a Nano, but selected Uno while uploading.
(4) While updating my Arduino IDE to the a version, I failed to select 'download USB drivers' option. There are 2 or 3 of them.


body:
This is a guess based on what I have encountered previously. With all the information given remember I just took a guess!

Is it possible you are experiencing a serial flood, ie it is constantly sending something to the console.
Take these steps several tries may be needed:
1) Power off the board completely
2) Remove the USB cable
3) Hold down the Reset button
4) keep it held down (or, run a jumper wire from the RESET pin to the GND pin).
5) Still holding down Reset reconnect the USB cable.
6) Start uploading a sketch that does not have this problem (I use the Blink sketch).
7) When you see the Receive light blink, release the Reset button
Note: I have seen this happen several times when I flood the serial output. An indication is the tx light is on.

You can check the hardware as follows.
Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.


message:
Arduino - stepper motor wrong steps number

I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.

In order to clarify, please see the image below:

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

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

The code is as follows:

    #define negativeSteps -55
    #define positiveSteps 55
    #define Speed 7500

    int motorPin1 = 11;
    int motorPin2 = 10;
    int motorPin3 = 9;
    int motorPin4 = 8;

    int steps;
    unsigned int tmp2;

    byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
    byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

    void setup() {

      Serial.begin(115200); //Opens serial connection at 115200 baud.

      pinMode(11,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(8,OUTPUT);

      pinMode(3,OUTPUT);    // Enable pin motorA
      pinMode(2,OUTPUT);    // Enable pin motorB

      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
    }

    void loop()
    {
        while (Serial.available())
        {
          char cmd = (char)Serial.read();
          if (cmd == 's')   while(1) Seek();
        }
    }
    void motorR(){
      int bitMask=B00001111; // bitmask to modify only last 4 bit

              for (int id = 0; id <4; id++) {
                PORTB = (PORTB &~bitMask) |  modeR[id];
                while (tmp2++<Speed);
                tmp2=0;
              }
    }
    void motorF(){
      int bitMask=B00001111; // bitmask to modify only last 4 bit

              for (int id = 0; id <4; id++) {
                PORTB = (PORTB &~bitMask) |  modeF[id];
                while (tmp2++<Speed);
                tmp2=0;
              }
    }
    void Seek() {
      steps = negativeSteps;      //Init Steps
      while (1)
      {

        while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
        {
           if (steps<0) motorF(); // if steps = 0 it will change the direction
           else motorR();

          Serial.println(steps);
          steps++;
       }
     }
    }

body:
You're driving the stepper too fast, unintentionally though.

The while loop you use to delay is likely optimized out by the compiler:

    while (tmp2++<Speed);

Easiest way to fix would be to declare **tmp2** as a *volatile* variable when you declare it up in the top of your program.  Thusly:

    volatile unsigned int tmp2;

This will inform the compiler that **tmp2** might possibly change at any time and not to optimize it away. It's more complicated than that really, but it'll fix your issue in a single tweak.

Better, would be to use the **delay()** function, to pause execution for some specified **milliseconds**, much like you're attempting to do with the empty while loop.

You're using an UNO, so probably running at 16Mhz, so your delay of 7500 loops is technically about 5 instructions long, multiplied by 7500... so 37,500 instructions executed, and at approximately 16,000,000 instructions per second, that's (37500/16M) that's about 2.34 milliseconds.  So maybe a **delay()** of 3-5 milliseconds would be useful.

Basically, you're trying to step the motor too fast, and it can't keep up.  Mass, inertia and all that stuff are involved too.

Try replacing the while statements with delays, start with big delays (25 or so), and work lower as long as stepper motion is consistent.  As you said, 200 steps **should** be 180°.

replace:

    while (tmp2++<Speed);

with:

    delay(Speed);

and change **Speed** to an appropriate value (25 or so to begin with, play with it!).

There are many improvements to your code which could be discussed, but you need to crawl before you walk, before you run.  Get THIS code working, then finesse it.


message:
Arduino Uno VIN 2A

Trying to get started with the Arduino, so I'm trying to do something kinda simple. I'm following this tutorial: [Build Your Own Dynamic Ambient Lighting For A Media Center](http://www.makeuseof.com/tag/build-your-own-dynamic-ambient-lighting-for-a-media-center/)

However, I'm still confused about one, most likely simple and self-explainatory, thing:
Take a look at [this image](http://i.1n9i9c7om.com/r3tnBj.png) - is that DC connector on the bottom left the one that's one my Arduino? Do I simply have to connect the 12V wire from the RGB LED stripe to Vin?

After using google for a bit, I read this: `the diode and trace width are other limiting factors. The diode is rated at 1 amp and the board traces can't handle much above 2 amp.`
Does that mean I can only use 1A because of the diode? If so, why does it matter how much the board traces can handle?

I'm trying to power a 12V 2A RGB LED stripe.

I'd appreciate your help and I hope this is the correct subreddit to ask that. :S

body:
No, that connector is a completely separate one.

You can connect a power supply to the on-board power socket of the Arduino and take power out from the VIN pin to power other things.  However the *total current* that is used by both the Arduino *and* whatever you power from it *cannot* exceed 1A.

So to have more than 1A available you have to have the power connected externally to the Arduino. That doesn't mean that the Arduino can't share that power, just that the Arduino can't *provide* that power.

You can connect the +12V of the LED strip to VIN on the Arduino as long as the 12V power supply is connected to the LED strip not to the Arduino - that way the power for the Arduino comes *from* your external circuit.


body:
It will be dangerous to take 12V from VIN pin. Please have a look at following picture. That is the diode you mentioned. the diode can burn out if the current get exceeded.

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

there are three ways to solve this.

 1. Use two different supplies. Use a 6V battery(or 5V USB power) to power arduino and 12v supply for LED strip. You should connect both grounds( grounds of supplies)

2. Solder a wire from bottom(from the point shown in picture) of arduino board for 12v

3. connect 12v power directly to VIN (not by using power jack)

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

  [1]: https://i.stack.imgur.com/3zgKh.png
  [2]: https://i.stack.imgur.com/YMyb9.png


message:
connecting two keypad with arduino

I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

body:
It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.

I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


message:
Arduino which library for led 4x20

I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.

So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

body:
0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).

The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.

The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.


message:
How to power Arduino and shields with 4 rechargeable AA batteries?

To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.

My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.

The rechargeable batteries I have are [these][1] 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.

So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?

This is a list of the current equipment that will require power:

 - [Arduino Mega 2560][2]
 - [SIM900 GPRS/GSM Shield][3]
 - [Sparkfun GPS Logger Shield][4]
 - [Sparkfun Wifi Shield - ESP8266][5]

The shields will be stacked on top of each other.

  [1]: https://www.duracell.co.uk/en-gb/products/duracell-rechargeable/duracell-rechargeable-batteries
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [3]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [4]: https://www.sparkfun.com/products/13750
  [5]: https://www.sparkfun.com/products/13287

body:
Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.

The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:

    V_IH = 0.6Vcc = 0.6 x 5 = 3V

    V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...

You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.

However, it is important to note that you have so far measured the *open circuit* voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.

The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.


message:
How do I find names of components I don't know?

I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

body:
The Arduino webpage has a section about their [Starter Kits][1], including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for [actuators][2] (there are more categories to the left of the image).

There is a blog by Aaron Eiche, [Arduino Starter Rundown][3], that if you scroll down, there is a chart that labels the main components.

There are several websites that have pages that identify components by image - an example is the uCHobby webpage [Identifying Electronic Components][4], with pictorial menus of the main types of components.

In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.

  [1]: https://www.arduino.cc/en/Main/ArduinoStarterKit
  [2]: https://store.arduino.cc/category/31
  [3]: https://aaroneiche.com/2009/07/16/arduino-starter-rundown-part-2/
  [4]: http://www.uchobby.com/index.php/2007/07/15/identifying-electronic-components/


body:
A slightly more general answer to this question would be to browse the catalogue of a component supplier. Printed catalogues seem to be becoming rarer (Maplin used to sell a catalogue, but it seems to be discontinued this year), but RS and Farnell still seem to have printed ones.

I'm not suggesting you find specific components by searching the catalogue, but skimming through a catalogue will give you an idea about some of the components that do exist, and will help you to narrow things down a little.


message:
How to interface an arduino to load sensor with darlington transistor?

I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

body:
What you have there is (or sounds like) a full wheatstone bridge.

You require either a special amplifier (such as the [HX711](https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide)) or a highly sensitive and accurate differential ADC (such as the [MCP3428](http://ww1.microchip.com/downloads/en/DeviceDoc/22226a.pdf) - ([on  a shield](http://majenko.co.uk/hpdaq.php))).