message:
Arduino Mega and other modules power consumption

I have an Arduino Mega 2560 to which I have connected:

 - Arduino GSM Shield 2
 - Waveshare 10 DOF IMU sensor
 - Waveshare NEO-7M-C (B) GPS module
 - HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

body:
**You should not try to power your arduino with more than 12 V**.  The barrel jack connector can take between 7 and 12 V and from there steps it down to the proper voltage for the Arduino (5V).  Anything being powered by the arduino is limited to how much current it can output, so if you have too many modules, you may need to have a separate power supply for those.  If you do this, there several things you need to consider:

 1. **What voltage does each module need?** (This is probably 5V, but you should check the datasheets or any documentation you have)
 2. **How much power does it consume?** You might find this in documentation, but you can also calculate it yourself: P = I*V  Once you know how much power each module/sensor consumes, you know how much your power supply needs to supply.

If you use a separate power supply for any of your modules/sensors,  make sure the ground pin is also tied to Arduino's ground.


sender: user

sender: assistant

body:
Power applied to the VIN pin is regulated down to 5V by the on-board regulator on the Mega. The minimum voltage is about 6.2V because of the regulator dropout (that is, the regulator needs at least 1.2V above it's 5V output in order to operate.) 9-12V is recommended.

Applying a higher and higher voltage will not provide any more power to the Mega and it's peripherals/shields. Instead, the excess power is dissipated in the regulator as heat.

If you experience low-power situations, the solution is to power the peripheral devices from a separate regulator than the one built-in to the Mega, which is really intended to power the Mega board/processor and maybe 1 shield.

You could obtain a high-current (3A or more) 5V supply, and connect the peripherals' power inputs to it, as well as power the Arduino in via the 5V pin (leaving VIN disconnected!). Be sure to tie the grounds of all peripherals and the arduino and power supply together.

Be sure also to pay attention to the voltages required by the peripheral modules, as it's common now to find modules that are rated for 3.3V and would be damaged by 5V. This is probably not the case for you, since your system is working sometimes.


body:
The Arduino GSM shield 2 demands 700mA-1000mA current. It is recommended to power the board with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current when the modem is in heavy use.

The modem can pull up to 2A of current at peak usage, which can occur during data transmission.

The GPS module takes only 35mA, so the fault is in the GSM shield.


body:
You can't fix it with more voltage. The board you are using ([schematic here][1]) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.

You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.

Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf


body:
arduino nano(5v usb)(3.3v).
arduino uno(12v dc jack)(5v).


message:
NRF24L01 receiving even if no data sent

I am using nRF24L01 to communicate between two micro controllers. Both are Arduino Uno.

The question i have here is , even if i do not send any data from sender to receiver , the receiver device is constantly checking for the data, and the blank data is being received per second. And also no data is received by receiver which is sent by sender.

I am sharing the code for both sender and receiver.

Please suggest me what wrong i am doing.

Receiver Code :

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String response;
    boolean done = false;

    void setup() {

     delay(500);
     Serial.begin(9600);

     radio.begin();
     radio.setPALevel(RF24_PA_MIN);
     radio.openReadingPipe(0, 0xF0F0F0F0AA);
     radio.startListening();

    }

    void loop() {

       if (radio.available()) {

       radio.read(&response, sizeof(response));
       done = true;

    }

    if (done) {
      Serial.println(response);
    }

    done = false;
    delay(1000);

    }
Sender Code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String request;

    void setup() {

    delay(500);
    Serial.begin(9600);

    radio.begin();
    radio.openWritingPipe(0xF0F0F0F0AA);
    radio.setPALevel(RF24_PA_MIN);
    radio.stopListening();

    }

    void loop() {

       while ( Serial.available() > 0 )  {

       request = Serial.readString();

       Serial.println(request);
       radio.write(&request, sizeof(request));

       delay(1000);

     }
    }

body:
You may have reversed the wire:

    RF24 radio(7, 8); //  CE,CNS


body:
I've written a code for NRF24L01+ based on the datasheet.run them on your arduino and test them.CE pin is PIN7 in arduino and CSN is PIN8 in arduino.
NRF_monitorRegisters() shows all Registers of NRF.It's nice to test your NRF
maybe it helps:

for transmitter:

    #include <SPI.h>

    int sending = 1;
    int data = 7;

    void IRQ() {
      Serial.println("STATUS register from IRQ ISR :  ");
      digitalWrite(8, 0);
      SPI.transfer(0x07);
      delay(10);
      Serial.println(SPI.transfer(0xff), BIN);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x08);
      delay(10);
      Serial.println(SPI.transfer(0xff), BIN);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);
    }

    void NRF_transmitterBegin() {

      //reading
      /*digitalWrite(8, 0);
        SPI.transfer(0x00);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      pinMode(7, OUTPUT);  //CE
      pinMode(8, OUTPUT);  //CSN
      delay(100);
      digitalWrite(8, 1);
      digitalWrite(7, 0);

      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV4);
      SPI.begin();
      delay(1000);

      digitalWrite(8, 0);   //flush TX_FIFO
      SPI.transfer(0xe1);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x00 + 0x20);
      delay(10);
      SPI.transfer(0x0e);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      /*digitalWrite(8, 0);
        SPI.transfer(0x11 + 0x20);
        delay(10);
        SPI.transfer(0x3f);
        delay(10);
        digitalWrite(8, 1);*/

      //Down for DYNPL
      digitalWrite(8, 0);
      SPI.transfer(0x1c + 0x20);
      delay(10);
      SPI.transfer(0x01);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x1d + 0x20);
      delay(10);
      SPI.transfer(0x04);
      delay(10);
      digitalWrite(8, 1);
      //Up for DYNPL

      digitalWrite(8, 0);
      SPI.transfer(0x01 + 0x20);
      delay(10);
      SPI.transfer(0x3f);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x02 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x03 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x04 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x05 + 0x20);
      delay(10);
      SPI.transfer(0x4c);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x06 + 0x20);
      delay(10);
      SPI.transfer(0x06);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x0a + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x10 + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);
      delay(10);

    }

    void NRF_transmit(int whatIsData , float data , float hum) {    //hum is used just for temp&humidity
      /*
         byte 0 says what is our data:  1 -> data and humidity    2 -> movement   3 -> gas

         1(float) :   byte 1 -> integer part of temp  byte 2 -> fractional part of temp   byte 3 -> integer part of humidity    byte 4 -> fractional part of humidity    byte 5 -> �ttery
         2(binary) :  byte 1 -> �ttery
         3(float) :   byte 1 -> integer part of gas   byte 2 -> fractional part of gas    byte 3 -> �ttery

         �ttery feature is in progress ...
      */

      int byte0 = 0 , byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
      float buf = 0;

      byte0 = whatIsData;

      switch (whatIsData) {
        case 1: {

            byte1 = data;
            buf = data - byte1;
            byte2 = buf * 10;

            byte3 = hum;
            buf = hum - byte3;
            byte4 = buf * 10;

            break;
          }
        case 2: {

            break;
          }
        case 3: {

            byte1 = data;
            buf = data - byte1;
            byte2 = buf * 10;

            break;
          }
        default: {
            break;
          }
      }

      digitalWrite(8, 0);
      SPI.transfer(0xe1);   //flush TX_FIFO empty
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0xa0);   //write on TX_FIFO
      delay(10);
      SPI.transfer(byte0);
      delay(10);
      SPI.transfer(byte1);
      delay(10);
      SPI.transfer(byte2);
      delay(10);
      SPI.transfer(byte3);
      delay(10);
      SPI.transfer(byte4);
      delay(10);
      SPI.transfer(byte5);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(7, 1);   //CE High
      delay(1);
      digitalWrite(7, 0);   //CE Low

    }

    void NRF_monitorRegisters() {

      for (int i = 0; i < 30; i++) {
        digitalWrite(8, 0);
        SPI.transfer(i);
        delay(10);
        Serial.print(i , HEX);
        Serial.print(" -> ");
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);
      }
      Serial.println("");

    }

    void setup() {

      Serial.begin(115200);

      NRF_transmitterBegin();
      NRF_monitorRegisters();

    }

    void loop() {

      NRF_transmit(3 , 15.1 , 0);

      delay(1000);
    }

for receiver :

    #include <SPI.h>

    long int lastTime = 0;

    void IRQ() {

      int whatIsData = 0;
      int byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
      float data = 0 , hum = 0 , buf = 0;

      /*Serial.println("STATUS register from IRQ ISR :  ");
        digitalWrite(8, 0);
        SPI.transfer(0x07);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      digitalWrite(8, 0);
      SPI.transfer(0x61);
      delay(10);
      whatIsData = SPI.transfer(0xff);
      delay(10);
      byte1 = SPI.transfer(0xff);
      delay(10);
      byte2 = SPI.transfer(0xff);
      delay(10);
      byte3 = SPI.transfer(0xff);
      delay(10);
      byte4 = SPI.transfer(0xff);
      delay(10);
      byte5 = SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      switch (whatIsData) {
        case 1: {

            buf = byte2;
            data = byte1 + buf / 10;
            buf = byte4;
            hum = byte3 + buf / 10;

            Serial.print("Received data from DHT22 -> temp:");
            Serial.print(data);
            Serial.print("  humidity:");
            Serial.println(hum);

            break;
          }
        case 2: {

            Serial.println("Received data from PIR -> Move detected");

            break;
          }
        case 3: {

            buf = byte2;
            data = byte1 + buf / 10;

            Serial.print("Received data from gas sensor -> %gas:");
            Serial.println(data);

            break;
          }
        default: {

            Serial.println("a problem accured");

            break;
          }
      }

    }

    void NRF_receiverBegin() {

      //reading
      /*digitalWrite(8, 0);
        SPI.transfer(0x00);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      pinMode(7, OUTPUT);  //CE
      pinMode(8, OUTPUT);  //CSN
      delay(100);
      digitalWrite(8, 1);
      digitalWrite(7, 0);

      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV4);
      SPI.begin();
      delay(100);

      digitalWrite(8, 0);   //flush TX_FIFO
      SPI.transfer(0xe1);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      digitalWrite(8, 0);
      SPI.transfer(0x00 + 0x20);
      delay(10);
      SPI.transfer(0x0f);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      /*digitalWrite(8, 0);
        SPI.transfer(0x11 + 0x20);
        delay(10);
        SPI.transfer(0x01);
        delay(10);
        digitalWrite(8, 1);*/

      //Down for DYNPL
      digitalWrite(8, 0);
      SPI.transfer(0x1c + 0x20);
      delay(10);
      SPI.transfer(0x01);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x1d + 0x20);
      delay(10);
      SPI.transfer(0x04);
      delay(10);
      digitalWrite(8, 1);
      //Up for DYNPL

      digitalWrite(8, 0);
      SPI.transfer(0x01 + 0x20);
      delay(10);
      SPI.transfer(0x3f);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x02 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x03 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x04 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x05 + 0x20);
      delay(10);
      SPI.transfer(0x4c);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x06 + 0x20);
      delay(10);
      SPI.transfer(0x06);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x0a + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x10 + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

    }

    void NRF_startListening() {

      attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);

      digitalWrite(7, 1);   //CE High
      Serial.println("Listening started");

    }

    void NRF_monitorRegisters() {

      for (int i = 0; i < 30; i++) {
        digitalWrite(8, 0);
        SPI.transfer(i);
        delay(10);
        Serial.print(i , HEX);
        Serial.print(" -> ");
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);
      }
      Serial.println("");

    }

    void setup() {

      Serial.begin(115200);

      NRF_receiverBegin();
      NRF_startListening();
      NRF_monitorRegisters();

    }

    void loop() {

      /*if (millis() - lastTime > 20000) {
        NRF_monitorRegisters();
        lastTime = millis();
      }*/

    }


message:
Default sketch working but arduino is not recognizing

I have an arduino UNO and when I connected the device through the USB to the PC (with windows 7 64 bit),

The default blinking sketch, which comes shipped with it, is working,

but the device recognition sound is not playing.

and the device driver installation dialog never appeared and no arduino entry in the device manager.

And when I tried to upload a successfully compiled sketch from the ide 1.8.4 ,

It just says, 'problem uploading to board'
More verbosely, **' avrdude: can't open device""\\.\COM1": the system cannot find the file specified'**

The device is getting power and running the sketch,
But device is not recognized, maybe it is connected charge only, can I install the drivers manually?

Thanks in advance for any help.

body:
Hahaha! I figured it out! The USB connector on the board's side was loose connected! It didn't felt like more pressable & when I pressed it enough, it firmly fitted.

When it loose connected, the board connects power only.

The drivers were installed automatically & it showed under COM6. I've got sketches running in no time.
I' ve tried a lot of knight rider patterns with a bunch of RGB LEDs then ;-)

Thank you @Majenko and the arduino stack exchage for your kind replies.


message:
Issue with If statement and boolean logic

I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:

    if ((analogRead(rain) < 650 || (Wind > 4)){
      motor_closed();
    }

    else if (analogRead(rain) < 650 && (Wind > 4)){
      motor_closed();
    }

    else if (analogRead(rain) < 650 && (Wind < 2)){
      motor_closed();
    }

    else if (analogRead(rain) > 900 && Wind > 4){
      motor_closed();
    }

    else if (analogRead(rain) > 900 && Wind < 2){
      motor_open();
    }

Did I make mistake when using `&&` boolean operator? Or its something else?

body:
I ran a test with your original code, with rain and wind varying over all the range:

    (rain, wind) -> action
    ------------------------
    (600, 1) -> motor_closed
    (600, 2) -> motor_closed
    (600, 3) -> motor_closed
    (600, 4) -> motor_closed
    (600, 5) -> motor_closed
    (650, 1) ->
    (650, 2) ->
    (650, 3) ->
    (650, 4) ->
    (650, 5) -> motor_closed
    (700, 1) ->
    (700, 2) ->
    (700, 3) ->
    (700, 4) ->
    (700, 5) -> motor_closed
    (750, 1) ->
    (750, 2) ->
    (750, 3) ->
    (750, 4) ->
    (750, 5) -> motor_closed
    (800, 1) ->
    (800, 2) ->
    (800, 3) ->
    (800, 4) ->
    (800, 5) -> motor_closed
    (850, 1) ->
    (850, 2) ->
    (850, 3) ->
    (850, 4) ->
    (850, 5) -> motor_closed
    (900, 1) ->
    (900, 2) ->
    (900, 3) ->
    (900, 4) ->
    (900, 5) -> motor_closed
    (950, 1) -> motor_open
    (950, 2) ->
    (950, 3) ->
    (950, 4) ->
    (950, 5) -> motor_closed

So your logical expression reduces to this:

    if (analogRead(rain) < 650 || Wind > 4) {motor_close();}
    else if (analogRead(rain) > 900 and Wind == 1) {motor_open();}

It's that what you want?

What's that "limiting switch"? May be it's a physical problem (like installing sensor **under** de roof)


body:
Personally I like to force precedence in my `if` statements to ensure that things always work precisely as I intend.  Group your logical predicates with brackets:

    if ((analogRead(rain) < 650) || (Wind > 4)) {
        motor_close();
    } else if ((analogRead(rain) > 900) and (Wind < 2)) {
        motor_open();
    }

Using intermediate variables would make it more readable:

    bool tooWindy = (Wind > 4);
    bool notWindy = (Wind < 2);
    bool tooRainy = (analogRead(rain) < 650);
    bool notRainy = (analogRead(rain) > 900);

    if (tooWindy || tooRainy) {
        motor_close();
    } else if (notWindy && notRainy) {
        motor_open();
    }

Giving names to the logical conditions makes it far more obvious what is going on:

* If it is too window **or** it is too rainy then close the roof.
* Otherwise, if it's not too windy **and** it's not too rainy then you can open the roof.

And of course you have the time when it's between too rainy and not too rainy, or between too windy and not too windy, in which case nothing should happen. This is called *hysteresis* and is good to have since it stops the roof from opening and then immediately wanting to close.

You could also improve the logic of the system even more and implement a small Finite State Machine:

    enum {
        CLOSED, OPENING, OPEN, CLOSING
    };

    int state = CLOSED;

    switch (state) {
        case CLOSED:
            if ((analogRead(rain) > 900) && (Wind < 2)) {
                motor_open();
                state = OPENING;
            }
            break;

        case OPENING:
            if (digitalRead(limit_open) == HIGH) {
                motor_stop();
                state = OPEN;
            }
            break;

        case OPEN:
            if ((analogRead(rain) < 650) || (Wind > 4)) {
                motor_closed();
                state = CLOSING;
            }
            break;

        case CLOSING:
            if (digitalRead(limit_close) == HIGH) {
                motor_stop();
                state = CLOSED;
            }
            break;
    }

In that you only attempt to open the roof (and even check to see if you should open the roof) if the roof is actually closed. Similarly for checking for and closing the roof - it only happens when the roof is actually open.  Nothing happens in the way of checks while the roof is in the process of opening or closing, so it has to complete its open or close operation first before any more decisions are made as to whether the roof should be open or closed.


body:
> Did I make mistake when using && boolean operator? Or its something else?

use brackets liberally.

rather than

    if (x > 65 && y < 10)

instead,

    if ((x > 65) && (y < 10))


message:
I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write

I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.

I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.

I tried calling `Wire.setClock(400000);`, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).

I also tried calling `Wire.begin(); TWBR = 10;`, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple

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

    /* Example code for the Adafruit I2C FRAM breakout */

    /* Connect SCL    to analog 5
    Connect SDA    to analog 4
    Connect VDD    to 5.0V DC
    Connect GROUND to common ground */

    Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
    uint16_t          framAddr = 0;

    byte p = 55;   //any old value- just write the same thing into all locations

    void setup(void) {
     Serial.begin(153600);
     //Wire.begin();
     //TWBR = 10;
     //Wire.setClock(400000);

     if (fram.begin()) {
      Serial.println("Found I2C FRAM");
     }
     else {
      Serial.println("I2C FRAM not identified ... check your connections?\r\n");
     }

    }

    void loop(void) {

     int i = 0;

     long a = micros();

     for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
      fram.write8(i, p);

     }

     for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
      fram.read8(i);

     }

     long b = micros();

     Serial.println(b - a);
     Serial.println("");
    }

body:
* You are running at 400000 bits per second, or 200000 per half second you say it takes.
* You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
* 200000/1000 = 200 bits per transaction.
* Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.

That makes 50 bits per transaction.

So yes, half a second to write then read it all is perfectly possible.

The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

----

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.

A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.

So for a read and write it's 38+48 = 86 bits.

Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.

At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.

If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

So not a bad guestimate of 25% transmission in my original surmising.


message:
Establishing an MQTT connection using Arduino Mega and ESP8266

As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (`PubSubClient client(?????)`), I have to set a client. What should I put in there? Is there another library I must use?

body:
You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).

Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.


body:
you have the AT firmware in the esp8266?
use [WiFiEsp library][1]

or if you can change the esp8266 firmware, you could try [JeeLabs esp-link][2]

  [1]: https://github.com/bportaluri/WiFiEsp
  [2]: https://github.com/jeelabs/esp-link


message:
Connect arduino with C# Desktop application wireless using esp8266

I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

body:
Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.

How you would do either of those in C# is outside the scope of this website.

The ESP8266 has AT commands that perform the task for you - chiefly `AT+CIPSTART`.

The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.

A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.

Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.


message:
Waking Arduino from sleep by holding button for more than 3 seconds

I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).

My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.

I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.

Below is my code:

    #include <avr/sleep.h>
    const int led1 = 44;
    const int led2 = 45;
    const int led3 = 46;
    const int usbState = 12;
    float pressLength = 0;
    const int button = 2;
    int optionOne = 100;
    int optionTwo = 3000;

    void setup() {
      pinMode(button, INPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(usbState, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      while (digitalRead(button) == LOW) {
        delay(100);
        pressLength = pressLength + 100;
        Serial.print("ms-");
        Serial.println(pressLength);
      }
      if (pressLength >= optionTwo) {
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        digitalWrite(led3, LOW);
        sleepNow();     // sleep function called here
      } else if (pressLength >= optionOne) {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        digitalWrite(led3, HIGH);
        while (1) {} //Keeps LEDS HIGH
      }
    }

    void sleepNow() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable(); // enables the sleep bit in the mcucr register
      attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
      sleep_mode(); // here the device is actually put to sleep!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
      while (digitalRead(button) == LOW) {
        delay(100);
        pressLength = pressLength + 100;
        Serial.print("ms-");
        Serial.println(pressLength);
      }
      if (pressLength >= optionTwo) {
        SleepNow(); //Back to sleep fucntion
      } else if (pressLength >= optionOne) {
        sleep_disable();
        // first thing after waking from sleep: disable sleep...
        resetFunc();//Resetting
      }
    }

    void wakeUpNow() {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
    }
    void(* resetFunc)(void) = 0;

Please help. Thanks.

body:
You won't manage it without external circuitry.

The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.

For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/JVt4J.png)

<!-- End schematic -->

In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.

Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.

To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.

If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.

R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.

This method is basically a very extreme form of debouncing.


message:
RFID-RC522 not working, red led is on

I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

body:
Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

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

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

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.

The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.

Here's how I connected it:

    Component markings and connections

    |-------------------------------------------|
    |   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
    |----------|-------|-----------|------------|
    | SDA (SS) |  10   |     7     |            |
    | SDA (SS) |       |     6     |    SDA     |
    | SCK      |  13   |     5     |            |
    | SCK      |       |     4     |    SCK     |
    | MOSI     |  11   |     3     |            |
    | MOSI     |       |     2     |    MOSI    |
    | MISO     |  12   |           |    MISO    |
    | IRQ      |  N/C  |    N/C    |    N/C     |
    | GND      |  GND  | 8,9,11,14 |    GND     |
    | RST      |   5   |           |    RST     |
    | 3.3V     |       |     1     |    3.3V    |
    |-------------------------------------------|


message:
POST to server using ESP8266 module- Arduino Uno- AT+ commands

I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken

The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.

I do not understand why my server does not receive data

Thank you a lot in advance for your help.

I have used the following code:

--------

    #include "Arduino.h"
    #include "ESP8266.h"
    #include "SoftwareSerial.h"
    #include "ArduinoJson.h"

    #define ssid "mySSID"
    #define pw "myPW"
    #define IP "xxx.xxx.xxx.xxx"
    #define URL "http://myurl.com/myaccesstoken"

    int incomingByte;

    void setup() {//I connect to wifi
      Serial.begin(115200);
      Serial.println("AT");
      delay(5000);
      analogReference(INTERNAL);
      if(Serial.find("OK")){
        Serial.println("AT+CWMODE=3");
        delay(1000);
        String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
        Serial.println(WF);
        delay(5000);}
    }

    void loop() {
      //JSON data creation
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["flow"] = 2.54;
    root["measured"] = "2017-08-14T06:16:03.418Z";
    root.printTo(Serial);
    delay(5000);
     // I start communication with server
     Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
     delay(5000);
     Serial.println("AT+CPSTATUS");
     // I use HTTP protocol to POST the data
        Serial.println("AT+HTTPINIT");
        delay(2000);
        Serial.println("AT+HTTPPARA=\"CID\",\"1");
        delay(2000);
        Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
        delay(2000);
        Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
        delay(2000);
        Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
        delay(2000);
        Serial.println("AT+HTTPACTION=1");
        delay(2000);
        Serial.println("AT+HTTPREAD");
        delay(2000);
        if(Serial.available() > 0)
            {
                    // read the incoming byte:
                    incomingByte = Serial.read();
                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByte);
        }
        Serial.println();
        Serial.println("AT+HTTPTERM");

        delay(5000);
      }

body:
Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"

I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.


body:
I suggest you use computer based tools to start communication with ESP8266 module and test out sending and receiving data before you connect the module with Arduino.
If you are looking for tutorials for the same then I suggest you visit [this link][1] maybe it will solve your problem or give you a direction to work on

  [1]: http://absaransari.com/category/esp8266/


message:
Power consumption in Arithmetic Operation in Arduino UNO

I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.

Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

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

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

body: Why not just measure the current drawn by the board and an empty loop vs. a loop that does some multiplication? (other than 1,2,4,8..)


body:
The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.

The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.

Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

---

## Addition

### Test sketch

    volatile int foo = 100;
    int main (void)
      {
      DDRB = 0b00111111;  // all ports to output
      DDRC = 0b00111111;
      DDRD = 0b11111111;
      PORTB = 0;          // write LOW
      PORTC = 0;
      PORTD = 0;

      while (true)
        foo += 42;
      }

### Generated code

      a6: 80 91 00 01  lds r24, 0x0100
      aa: 90 91 01 01  lds r25, 0x0101
      ae: 8a 96        adiw r24, 0x2a ; 42
      b0: 90 93 01 01  sts 0x0101, r25
      b4: 80 93 00 01  sts 0x0100, r24
      b8: f6 cf        rjmp .-20      ; 0xa6 <main+0x10>

### Measured consumption

I measured an average of 7.00 mA.

---

## Multiplication

### Test sketch

    volatile int foo = 100;
    int main (void)
      {
      DDRB = 0b00111111;  // all ports to output
      DDRC = 0b00111111;
      DDRD = 0b11111111;
      PORTB = 0;          // write LOW
      PORTC = 0;
      PORTD = 0;

      while (true)
        foo *= 42;
      }

### Generated code

      a6: 4a e2        ldi r20, 0x2A ; 42
      a8: 20 91 00 01  lds r18, 0x0100
      ac: 30 91 01 01  lds r19, 0x0101
      b0: 42 9f        mul r20, r18
      b2: c0 01        movw r24, r0
      b4: 43 9f        mul r20, r19
      b6: 90 0d        add r25, r0
      b8: 11 24        eor r1, r1
      ba: 90 93 01 01  sts 0x0101, r25
      be: 80 93 00 01  sts 0x0100, r24
      c2: f2 cf        rjmp .-28      ; 0xa8 <main+0x12>

### Measured consumption

I measured an average of 6.32 mA.

---

## Conclusion

I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.

Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).

I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?

## Update

As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.


message:
Grounding for arduino, measuring phase controllled 240V

I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

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

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

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

  [1]: https://i.stack.imgur.com/UVC1i.jpg
  [2]: https://i.stack.imgur.com/9FywE.jpg

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?

Thanks!

body:
You shouldn't really connect the mains direct to the Arduino like that - even with a zener. The potential for disaster is somewhat large.

Instead you should galvanically isolate the mains from the Arduino. I would use something as simple as an opto-isolator:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/0wN00.png)

<!-- End schematic -->

Make sure that R1 is rated for at least 339V and can dissipate enough power (1W). The resistance of R1 needs to be small enough that the opto-isolator triggers properly, yet large enough that you don't need a great honking heater of a resistor to cope with the power. 150K seems a reasonable compromise.

D2 is needed to prevent the LED In the opto-isolator from being reverse biased with 339V in the reverse-swing portion of the waveform.

You can incorporate your zener as well if you want to "push down" the waveform to get a lower cross section of it (clip off the upper portion) instead of just reducing its amplitude:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/VCnrr.png)

<!-- End schematic -->

In this R1 is the same as the resistor you were planning to use before. The added R3 resistor is to limit the current through the LED (drop the 5V to the LED forward voltage at a suitable current for the LED).


body:
your circuit will work, and can be simplified a little bit further. But it will work.

it is safer to use isolation, however. there are multiple ways to go about doing it.

the key here is to detect zero crossing, and start counting from there.


message:
How can I swap a servo with a stepper motor?

I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

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

This is the code I'm currently using to drive the servo:

    void loop() {
      topServo.write(115);
      delay(500);

      for(int i = 115; i > 65; i--) {
        topServo.write(i);
        delay(2);
    }

This is a schematic of my project:

![schematic](https://i.stack.imgur.com/T9MCD.png)

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

Can anyone help me to configure this? or point me into the right direction.

Any help would be greatly appreciated!

body:
Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like [this][1] along with your 28-BYJ48 stepper motor.

Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

<hr>

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.

(I've often found this simple piece of code really handy for troubleshooting!)

    #include <Stepper.h>

    const int stepsPerRev = 2048

    // initialise the stepper library on pins 8, 9, 10 & 11
    Stepper myStepper(stepsPerRev, 8,10,9,11);

    void setup() {
      // set the speed
      myStepper.setSpeed(4);

    }

    void loop() {
      // step one revolution in one direction:
      myStepper.step(stepsPerRev);
      delay(1000);

      // step one revolution in the other direction:
      myStepper.step(-stepsPerRev);
      delay(1000);

    }

  [1]: http://42bots.com/wp-content/uploads/2014/02/stepper01.jpg


message:
Can not receive data from UART with stepper motor

I am using an Arduino Mega2560
While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.

How can I make my motor move without stopping the reception of data from UART?

body:
If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:

    void AccelStepper::runToNewPosition(long position)
    {
        moveTo(position);
        runToPosition();
    }

which, in turns calls:

    // Blocks until the target position is reached
    void AccelStepper::runToPosition()
    {
        while (run())
     ;
    }

In turn, run() returns false only when the position is reached, as shown here:

    boolean AccelStepper::run()
    {
        if (_targetPos == _currentPos)
     return false;

        if (runSpeed())
     computeNewSpeed();
        return true;
    }

As you can see, your program is blocked until the position is not reached.

Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.

To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.

In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in `rotate_motor()` call only:

    stepper1.moveTo(1100);

Then in the loop, write somewhere:

    stepper1.run();

EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "`m`"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling `stepper1.run()`, check if you actually must move (`if (m != 0)`). When you call the `stepper1.run()` method, check if it returns `false`. In this case it means it reached the position, then you must change the value of m accordingly.


message:
How do I connect an Adafruit headphone jack to an Arduino 101?

I just purchased Adafruit headphone jack and I want to know how to connect it to an Arduino 101. I'm trying to use a breadboard to play a sample tone melody from the Arduino libraries, which I want to hear with my iPhone headphones.

I have been looking online for instructions on how to do this, but found nothing. Please advise.

Thank you!

body:
First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.

Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/7Zoml.png)

<!-- End schematic -->

Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.


message:
Troubleshooting an Arduino Computer Program

I am trying to make a serial monitor print something based on when a button is pushed.

When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.

Thanks

    int led = 2;
    const int buzzer = 3;

    int upButton = 5;
    int downButton = 7;
    int enterButton = 6;

    int up = 1;
    int down = 1;
    int enter = 1;

    bool homeActivated = true;
    bool appsActivated = false;

    int homeLocation = 1;
    int appsLocation = 1;

    bool homePrinted = false;
    bool appsPrinted = false;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode (upButton, INPUT);
      pinMode (enterButton, INPUT);
      pinMode (downButton, INPUT);
      Serial.println("Initializing");
      delay(2000);
    }

    void loop() {
      up = digitalRead (upButton);
      enter = digitalRead (enterButton);
      down = digitalRead (downButton);

      //move up and down
      if (up = 0)
      {
        if (homeActivated = true)
        {
          homeLocation + 1;
          Serial.println("Scrolled Down 1");
          delay(1500);
          homePrinted = false;
        }
        else if (appsActivated = true)
        {
          appsLocation + 1;
          Serial.println("Scrolled Down 1");
          delay(1500);
          appsPrinted = false;
        }
      }

body:
You need to learn basic C syntax.

`=` is assignment, not comparison.

For comparison you use `==`

* https://www.tutorialspoint.com/cprogramming/c_operators.htm


message:
Arduino Editor: Monitor menu show "Serial port unavailable"

Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".

    $ dmesg | grep tty
    [    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    `dmesg | grep FTDI`, but no any output returned.

    $ ls -l /dev/ttyUSB*
    ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

body:
type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.

Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.

With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....


body: Do a `ls -l /dev/tty*` in a console screen and then search for the tty* port that your arduino is connected to (mine is `ttyACM0`), you will see which group (my group is `dialout` for Ubuntu 17.10) you need to add yourself to in order to be able to access your arduino via the Serial Monitor.


message:
Angular velocity of a dc motor controlled by a potentiometer

I created a setup in which a potentiometer controls a dc motor, with current flow through the dc motor controlled by an H-bridge.
The principle is as follows:
With the potentiometer dial set to the mid-point, the motor is off. Rotating the potentiometer clockwise would cause the motor to rotate in one direction, with speed dictated by the displacement of the potentiometer from the mid-point: the greater the displacement from mid-point, the greater the speed of rotation of the motor. If the potentiometer is rotated anti-clockwise, away from mid-point, the motor would rotate in the opposite direction from before; again, with speed dictated by the extent of displacement of the potentiometer from mid-point.

The loop has three functions, where HB_12EN is to enable the drivers, HB_1A is the first driver input, and HB_2A is the second driver input (H-Bridge pins 1, 2 and 7, respectively) as per this datasheet:
http://www.ti.com/lit/ds/symlink/sn754410.pdf

To summarise their functions: HB_12EN allows voltage to be applied to the the device controlled by the H-Bridge (in this case a motor), and is pulse-wave-modulated. HB_1A and HB_2A control the flow of current through the motor, setting its angular velocity. HB_1A set HIGH and HB_2A set LOW directs current one way through the motor, and HB1A set LOW and HB_2A set HIGH directs current the other way through the motor.

The loop is:

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

    //OUTPUTS
    int const HB_12EN = 9; //pwm pin
    int const HB_1A = 2;
    int const HB_2A = 3;

    //INPUTS
    int const POT_MOT = 0; //A0, analog 0

    //GLOBAL VARIABLES
    unsigned int pot_val = 0; //ADC value from potentiometer
    unsigned int grp_num = 1;

    pot_val = analogRead(POT_MOT);
    grp_num = setMotSwitch(HB_12EN, HB_1A, HB_2A, pot_val, grp_num);
    setMotSpeed(HB_12EN, pot_val, grp_num);

The two (non-library) functions are:

    unsigned int setMotSwitch(int const motor_reg, int const first_motor, int const sec_motor, unsigned int pot_value, unsigned int group_num) //grp 0: 0-383; grp 1: 384-639; grp 2: 640-1023
    {
      if (pot_value >= 0 && pot_value < 384)
      {
        if (group_num != 0)
        {
           digitalWrite(motor_reg, LOW);
           digitalWrite(first_motor, HIGH);
           digitalWrite(sec_motor, LOW);
           group_num = 0;
        }
      }
      else if (pot_value > 383 && pot_value < 640)
      {
        if (group_num != 1)
        {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, LOW);
          group_num = 1;
        }
      }
      else if (pot_value > 639 && pot_value <= 1023)
      {
        if (group_num != 2)
        {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, HIGH);
          group_num = 2;
        }
      }
      else
      {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, LOW);
          group_num = 0;
      }
      return group_num;
    }

    void setMotSpeed(int const motor_reg, unsigned int pot_value, unsigned int group_num)
    {
      unsigned int mot_speed = 0;
      if (group_num == 0)
      {
        mot_speed = map(pot_value, 0, 383, 255, 0);
        mot_speed = constrain(mot_speed, 0, 255);
        analogWrite(motor_reg, mot_speed);
      }
      else if (group_num == 1)
      {
        if (pot_value > 500 && pot_value < 523)
        {
          digitalWrite(motor_reg, HIGH); //braking
        }
        else
        {
          digitalWrite(motor_reg, LOW);
        }
      }
      else if (group_num == 2)
      {
        mot_speed = map(pot_value, 640, 1023, 0, 255);
        mot_speed = constrain(mot_speed, 0, 255);
        analogWrite(motor_reg, mot_speed);
      }
    }

I tried to proceed as follows:
As the potentiometer would produce an ADC input with 1024 states, I divided those 1024 states in to 8 groups, the first three groups, covering the first 384 states (0-383) correspond to a dc motor direction (let's say anticlockwise), representing different speeds of rotation (ignoring issues of many-to-one mapping). The middle 2 groups, 256 states (384-639), correspond to a stationary motor. The last three groups, 384 states (640-1023), correspond to motor rotation in the other direction (in this example, clockwise). The ADC inputs have to be translated in to analog outputs with 256 possible states (0-255), so I map each range as appropriate; for 0-383, the mapping has to be reversed, so an input of 383 corresponds to an input of 0. The middle range (384-639) is stationary, but I tried to make a small "sub"-range in the middle a "braking range", I believed this is achieved by setting both H-bridge inputs to LOW. The 640-1023 range mapping is 640 to 0 and 1023 to 255.

Hopefully that makes sense. It seems to work, the issue I am having is that the motor seems to achieve a greater speed in one direction compared to the other: the maximum rotation speed produced in the motor is greater when the potentiometer is at its maximum in one direction compared to the other. I am pretty sure the code above gives an "even" mapping from the potentiometer to the motor for both directions. Is this, then, something to do with hardware?, and is it something to be anticipated in these kinds of setups?

Any help would be appreciated. If anyone has any advice on the best way to combine a potentiometer -or similar- input with a motor output let me know. The "braking" functionality is also a little confusing.

body:
Personally I wouldn't bother with "groups". Just do simple maths:

    int velocity = analogRead(POT_MOT) - 512;

`velocity` now gives you a value from -512 to +511.

    bool dir = (velocity >= 0);

`dir` is now `true` for a positive value (0 is considered positive) or `false` for negative.

    velocity = abs(velocity);

`velocity` is now made positive if it is negative.

So you now have two variables: `dir` which sets the direction, and `velocity` which sets the speed.

Now you can "offset" it:

    velocity = map(velocity, 0, 512, -128, 255);

`velocity` is now changed to fit into the range -128 to 255. Anything above 0 is a valid speed, anything below is the "dead zone" and stops the motor.

    if (velocity <= 0) {
        // If it's negative or zero stop
        digitalWrite(motor_reg, LOW);
        digitalWrite(first_motor, LOW);
        digitalWrite(sec_motor, LOW);
    } else {
        if (dir) { // Pot was positive
            analogWrite(motor_reg, velocity);
            digitalWrite(first_motor, LOW);
            digitalWrite(sec_motor, HIGH);
        } else { // Pot was negative
            analogWrite(motor_reg, velocity);
            digitalWrite(first_motor, HIGH);
            digitalWrite(sec_motor, LOW);
        }
    }

Adjust the negative value in the map to change the size of the "dead zone".


body:
i would break out this into three or at least two parts:

1) a call to change the speed of the motor;
2) a call to read the potential meter setting;
3) a call to convert the potential meter setting into motor speed, optional.

the code would look like this:

      pot_setting = potsetting_read(); //read pot setting
      speed_setting = pot2spd(pot_setting); //convert pot setting to motor speed
      motor_setspeed(speed_setting); //set motor speed

it is not difficult to figure out each of the three functions.

the  more challenging of the three, to a newbie, is the one that sets the motor speed. there are many ways to do it, and I personally prefer to use timer interrupts.

the basic construct is to sequentially go through a set of pin states, where the duration of each state transition is controlled by a timer interrupt. by changing how fast that timer interrupt takes place, you change the speed in which the pins transition their states, thus motor speed.


message:
Problem receiving full serial event+SMS

I wrote code in Arduino to read SMS. I have a problem with receiving it from serial.

    String str;

    void setup() {
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      delay(1000);
    }

    void loop() {
      Serial.println("AT+CMGF=1");
      delay(2000);
      Serial.println("AT+CMGR=1");
      delay(5000);
      while (Serial.available()>0) {
        str = char(Serial.read());
        Serial.print(str);
      }
      Serial.println();
    }

I have an A6 GSM modem. When I read the serial I just get:

    +CMGR: "REC READ

Nothing more!

I should get something like this:

    +CMGL: 1,"REC READ","+989207201219",,"2017/08/26,21:54:56+05"
    test 20

I changed my code to:

    int readline(int readch, char *buffer, int len) {
      static int pos = 0;
      int rpos;
      if (readch > 0) {
        switch (readch) {
          case '\n': // Ignore new-lines
            break;
          case '\r': // Return on CR
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
          default:
            if (pos < len-1) {
              buffer[pos++] = readch;
              buffer[pos] = 0;
            }
        }
      }
      // No end of line has been found, so return -1.
      return -1;
    }

    void setup() {
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
    }

    void loop() {
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CMGR=1");
      static char buffer[80];
      if (readline(Serial.read(), buffer, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buffer);
        Serial.println("<");
      }
      delay(3000);
    }

But I get nothing.

body:
The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.


body:
I changed the code. so It works fine

    String inputString = "";         // a String to hold incoming data
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
    }

    void loop() {

      Serial.println("AT+CMGR=1");

    }

    void serialEvent() {
        inputString = Serial.readString();
        Serial.println(inputString);
        delay(5000);
      }


message:
Super-fast USB communication; how is it possible?

On Arduino forums, [there's a post][1] where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.

## My test code

I made a simple program on Python for testing; here it's:

    import serial
    import sys
    import datetime

    ser = serial.Serial(
       port = 'COM9',
       baudrate = 26*115200, #biggest number acceptable by python
       parity = serial.PARITY_NONE,
       stopbits = serial.STOPBITS_ONE,
       bytesize = serial.EIGHTBITS
    )

    if ser.isOpen() == False :
       ser.open()
       if ser.isOpen() == False :
          print("Can't open serial port")
          sys.exit(1)

    start = datetime.datetime.now()
    s = b'abc'*10000
    ser.write(s)
    total_len = len(s)
    end = datetime.datetime.now()
    speed = total_len/(end - start).total_seconds()/1e6
    print("Speed: " + str(speed) + " MB/s")

And I made a simple Arduino program to read:

    char buf[500];

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

    void loop() {
      if (Serial.available() > 0) {
         Serial.readBytes(buf, 500);
      }
    }

With this, my best result was `0.2 MB/s` with my Arduino mega. However, on [that post][1], they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!

## Atemmpting to achieve their result:

Apparently Arduino libraries are different than before, so just taking their code and putting it in my `arduino\avr\cores\arduino` directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...

## The problem I faced

So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:

    #define USBCON

but this lead to the error:

    error: #error "Targets with both UART0 and CDC serial not supported"

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

1. Is it possible to get these speeds? How?
2. If it's, why is it not in the default Arduino library?
3. In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

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

body:
> Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

> If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

> In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.


message:
Simplest/best way to control a set of 8-10 PWM signals from a smartphone

As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more.  I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project.  I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).

It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth.  I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs).  Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.

If people here concur with this approach, I shall move this question to the Arduino forum.

`

body:
HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the [Node MCU][1]) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.

I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used [app inventor][2] which is extremely easily to use for bluetooth.

  [1]: https://en.wikipedia.org/wiki/NodeMCU
  [2]: http://appinventor.mit.edu/explore/


message:
Problems Writing and Clearing 24FC512 EEPROM using Arduino Uno

#Solution:#

Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.

    void writeEEPROMPage(long eeAddress) {
   int writes = incr;
   bool overflow = false;

      //check for page overrun, adjust writes to fill page and set flag if overrun
   if((eeAddress % 128 + incr) > 127) {
     writes = 128 - eeAddress % 128;
     overflow = true;
   }
   Wire.beginTransmission(EEPROM_ADR);

   Wire.write((int)(eeAddress >> 8)); // MSB
   Wire.write((int)(eeAddress & 0xFF)); // LSB
   //Write bytes to EEPROM
   Wire.write(rwBuffer, writes); //Write the data
   Wire.endTransmission(); //Send stop condition
   eeAddress += writes;

   if(overflow) {
     delay(5);
     Wire.beginTransmission(EEPROM_ADR);

     Wire.write((int)(eeAddress >> 8)); // MSB
     Wire.write((int)(eeAddress & 0xFF)); // LSB

     //Write remaining data to new page
     Wire.write(rwBuffer + writes, incr - writes);

     Wire.endTransmission();
     eeAddress += incr - writes;
   }
 }

#Problem:#

I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.

In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.

For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:

    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
    +12 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
    +12 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
    +5 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.

This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.

Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.

    #include <Wire.h>

    #define EEPROM_ADR 0x54

    const int incr = 30;
    byte rwBuffer[] = {
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
    };

    void setup() {
      pinMode(13, OUTPUT);
      pinMode(12, INPUT);
      Wire.begin();
      Wire.setClock(400000);
      long currentSpot = 0;
      if (digitalRead(12)) {
        dumpEEPROM();
      } else {
        while (currentSpot < 64000) {
          writeEEPROMPage(currentSpot);
          currentSpot += incr;
          delay(7);
        }
      }
    }

    void loop() {
      digitalWrite(13, !digitalRead(13));
      delay(500);
    }

    void writeEEPROMPage(long eeAddress) {
      Wire.beginTransmission(EEPROM_ADR);
      Wire.write((int)(eeAddress >> 8)); // MSB
      Wire.write((int)(eeAddress & 0xFF)); // LSB
      //Write bytes to EEPROM
      Wire.write(rwBuffer, incr); //Write the data
      Wire.endTransmission(); //Send stop condition
    }

    void dumpEEPROM() {
      long i;
      int j, readnum, timer = 0;
      Serial.begin(115200);
      timer = millis();
      for (i = 0 ; i < 64000 ; i += incr) {
        //Read all bytes from EERPOM
        readnum = readToBuffer(i);
        for (j = 0; j < incr; j++) {
          if (rwBuffer[j] < 0x10)
            Serial.print("0");
          Serial.print(rwBuffer[j], HEX);
          Serial.print("  ");
        }
        Serial.println();
      }
      timer = millis() - timer;
      Serial.print("Full data dump took ");
      Serial.print((float)timer / 1000, 3);
      Serial.println(" seconds.");
      Serial.end();
    }

    int readToBuffer(long address) {
      int i = 0;
      Wire.beginTransmission(EEPROM_ADR);
      Wire.write((int)(address >> 8)); // MSB
      Wire.write((int)(address & 0xFF)); // LSB
      Wire.endTransmission();
      Wire.requestFrom(EEPROM_ADR, incr);
      for (i = 0; i < incr && Wire.available(); i++) {
        rwBuffer[i] = Wire.read();
      }
      return i;
    }

body: Right after each `Wire.endTransmission();` you need to insert a `delay(5);`. The errors you see could be write-related, and/or read related too. You have to let the EEPROM chip process the address request before you start dumping/reading.


body:
You are trying to do a page write across a page boundary.

> The write control byte, word address and the first data
byte are transmitted to the 24XX512 in the same way
as in a byte write. But instead of generating a Stop
condition, the master transmits up to 127 additional
bytes, which are temporarily stored in the on-chip page
buffer and will be written into memory after the master
has transmitted a Stop condition. After receipt of each
word, the seven lower Address Pointer bits are internally
incremented by one. If the master should transmit
more than 128 bytes prior to generating the Stop condition,
the address counter will roll over and the previously
received data will be overwritten. As with the byte
write operation, once the Stop condition is received, an
internal write cycle will begin

You are sending blocks of 30 bytes (`incr = 30`). You have 128 byte pages.

* 128 / 30 = 4.267 writes per page. The 5th write spans pages. But, in a big bold NOTE in the datasheet:

> Page write operations are limited to writing
bytes within a single physical page,
**regardless** of the number of bytes
actually being written. Physical page
boundaries start at addresses that are
integer multiples of the page buffer size (or
‘page size’) and end at addresses that are
integer multiples of [page size – 1]. If a
Page Write command attempts to write
across a physical page boundary, the
result is that the data wraps around to the
beginning of the current page (overwriting
data previously stored there), instead of
being written to the next page as might be
expected. It is therefore necessary for the
application software to prevent page write
operations that would attempt to cross a
page boundary.

So you write 4 blocks to the first page, then the 5th block fills in the end of the first page *then goes back to the start of that page and overwrites what has already been written earlier*. Your next page then starts part way through the next block skipping a chunk that you cannot now get to.

You must either do your writes in blocks of an integer division of 128 (so 16 bytes is the largest you can do) or manually detect a page boundary and split your block write into two separate writes - one to finish filling the first page and the next to start filling the next page.


message:
How to "break" a function we made?

This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "*".

I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: `char key = keypad.getKey();`.

The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "*".

    void loop() {
      char key = keypad.getKey();
      if (key=='*'||key=='#') {
        position = 0;
        setLocked(true);
      }
      if (key==secretCode[position]) {
        position ++;
      }
      if (position ==3) {
        setLocked(false);
      }
      delay(100);
    }

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
      }
    }

body:
I may be missing something, but couldn't you just modify your `setLocked` function?

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      }
      return;
    }


body:
I was looking at your `loop()` and it have some problems, like not counting how many digits did the user input and locking upon receiving a single "#" a

Here is some better way:

    char secretCode[] = "1234";
    char inputCode[] = "xxxx";
    int position = 0;

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

    void loop() {
      char key = keypad.getKey();

      if (key == '*' || key=='#') {
        int i = 0;
        //  With 4 input digits, now we compare against secret code.
        while (i < sizeof(inputCode) && inputCode[i] == secretCode[i]) {
          i++;
          }
        //  Set locked only if 4 digits are the same.
        setLocked(i == sizeof(inputCode));
        //  Reset input code array.
        position = 0;
      } else {
        //  Key adding digits to the input code.
        inputCode[position++] = key;
        if (position == sizeof(inputCode)) {
          position = 0;
        }
      }
      delay(100);
    }

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      }
      return;
    }


body:
The problem is that when the device is unlocked with the correct code, you turn the green LED on wait for 0.5 seconds and then you don't turn it off again. So the simple answer would be [sempaiscuba's answer][1].

Personally, I like the fact that the red LED indicates that the device is locked and the green LED indicates that it is unlocked.

The problem that I see with your code is that if the user enters an incorrect number, it doesn't reset, allowing any amount of wrong numbers until it sees the right number. This means that I could come along and press the keypay randomly and after a while I would have pressed every digit in the secret code and it would unlock.

Think of the problem as a state machine. You start with 0 digits correct (ie `position==0`). If at any time the user presses an incorrect digit (or the * or #), the state machine will reset back to 0 digits correct state. If the user enters the first digit correctly then it progresses to the 1 digit correct state (ie `position==1`). And so on until all of the digits are correct and the device is unlocked. Due to the simplicity of this state diagram it can be accomplished using a few if statements.

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

    int position = 0;
    char secretCode[] = "7890";
    char inputCode[] = "????";      // This can be any character and just acts as a placeholder
    boolean newKey = false;

    void setup()
    {
        setLocked(true);
    }

    void loop()
    {
        char key = keypad.getKey();

        // Only process when a new key has been pressed
        if ((key != NO_KEY) && newKey)
        {
          newKey = false;  // Don't enter this if statement again if the key is being held down (used for debounce)

          if ((key == secretCode[position]) && (position < 3))
          {
              // The correct key has been pressed
              position ++;
              if (position == 3)
              {
                // Correct code has been entered (all 4 digits)
                setLocked(false);
              }
          }
          else
          {
            // It must be a wrong key (including * & #)
            // Or the device is unlocked and the user is locking it again.
            setLocked(true);
          }
        }
        else
        {
            // Key has been released (used for debounce)
            newKey = true;
        }
    }

    void setLocked(boolean locked)
    {
        if (locked)
        {
            position = 0;
            digitalWrite(redpin, HIGH);
            digitalWrite(greenpin, LOW);
        }
        else
        {
            digitalWrite(redpin, LOW);
            digitalWrite(greenpin, HIGH);
        }
    }

Once unlocked, all you have to do is press any key to lock it again.

Resources:
http://playground.arduino.cc/Code/Keypad

  [1]: https://arduino.stackexchange.com/a/44146/19409


message:
Arduino - Getting error - 'TCCR2' was not declared in this scope

This code below:

    void setup() {
      #if defined(__AVR_ATmega168__)
        // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

        // set prescaler to 1
        // (sbi means "set bit register", cbi means "clear bit register")
        cbi(TCCR1B, CS12);
        cbi(TCCR1B, CS11);
        sbi(TCCR1B, CS10);

        // set fast PWM
        cbi(TCCR1B, WGM13);
        sbi(TCCR1B, WGM12);
        // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
        // with slow PWM, it is half that speed (31KHz)
      #else
        // 22KHz for the ATMega8 (this is a low frequency)
        TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
        TCCR1B = ((TCCR1B & ~0x07) | 0x01);
      #endif
    }

when verify, generates an error:

    In function 'void setup()':
    pwm-control-1:185: error: 'TCCR2' was not declared in this scope
    TCCR2 = ((TCCR2 & ~0x07) | 0x01);
    ^
    exit status 1
    'TCCR2' was not declared in this scope

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.

Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code

I'm not an expert in pwm and timer/controls in micros... just started to learn..

Note: I've only shown the necessary part of the code

body:
The problem is because TCCR2 is not declared, as there is no register with that name. Maybe you wanted to configure the timer 2, i.e. you meant TCCR2A or TCCR2B instead of TCCR2.

EDIT: analyzing your code, you should definitely write TCCR2B.


body:
Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.

The easiest fix will be to remove the non-'168 branch (between `#else` and `#endif`), and make the '168 branch default (remove the `#if` line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.


body: Check the datasheet to see if there is a tccrb. Maybe for your device, it is tccra, tccrb, or teerc, ....


message:
GPS and Arduino

I am working on a project with an Arduino Uno. I want to know if the latitudes and longitudes can be input to the Arduino for the Arduino to move to that particular location. If it's possible then which sensors or actuators are to be used? Please also mention some references for me to read and collect the required information.

body:
See this site, for a practical example:

http://www.instructables.com/id/Arduino-Powered-Autonomous-Vehicle/


body:
OK, notwithstanding Majenko's excellent suggestion in the comments above, I played around with Arduino and GPS, so I can probably offer a few pointers.

**First, GPS**:

All the GPS modules that I have played with give out a series of standard strings of information or "sentences". These sentences are defined by the [National Marine Electronics Association (NMEA) protocol][1]. You are going to want to spend some time learning how to use this information.

The most commonly used string in an NMEA sentence is **$GPRMC**. From this you can extract date, time and position. But there is a lot more useful information in an NMEA sentence, so do your research.

When you have decided which GPS module you want to use, just use Google to search for sample Arduino code specific to that module. That should be enough to get you started.

**On the subject of GPS Modules:**

There are many available. Just Google search for "Arduino GPS module".

They vary in price from a few GB pounds to well over a hundred GB pounds. It all depends on what you need from it, and what you can afford. Personally, I got very good results from cheap (~ £5 GB) Neo-6M modules (like the one shown here) with some mobile robots I was experimenting with.

![neo-6m][2]

Now, I've just typed "*Neo-6m GPS Arduino*" into Google, and one of the first sites was this [Instructable][3], which has more than enough information to get you going with this combination.

**Path planning**

Yes, you could give a robot a GPS and a target location and have it plan a route and move to the new location.

Sounds easy doesn't it?

It isn't.

It really, *really* isn't!

Path planning is a complicated discipline. There is an introductory course on [Computational Motion Planning][4] available (free to audit last time I looked) on Coursera if you are interested. It's part of a Robotics "Speciality", so depending on your existing skills, you might want to work through the modules in sequence.

[If you do decide to do all the modules in the Speciality, I shared [my notes][5] for some of the modules via my Scribd account. Some of these also contain elements on motion planning. (***Be warned***, some of them also contain a lot of maths!)]

The best practical advice I can give is to start small.

I tested my robots in a local park, over distances measured in tens, rather than hundreds of metres. I then introduced obstacles (trees) in a different part of the park, and things got a whole lot more interesting! (Not least, of course, because GPS really doesn't like trees! So you have to use other sensors when the robot isn't receiving data from the GPS ...).

And if you think that's complicated, just wait until you introduce "moving obstacles", like people, dogs, cars, bicycles, ...!

Hopefully that will give you some pointers to get you started. When you hit problems with your code (and you're almost certainly going to hit problems with your code!), sites like this will be a godsend.

I really wish Arduino: SE had been around back when I was banging my head against the proverbial wall trying to work out why my code wasn't doing what I expected it to!

  [1]: http://www.gpsinformation.org/dale/nmea.htm
  [2]: https://i.stack.imgur.com/GrgHw.jpg
  [3]: http://www.instructables.com/id/How-to-Communicate-Neo-6M-GPS-to-Arduino/
  [4]: https://www.coursera.org/learn/robotics-motion-planning
  [5]: https://www.scribd.com/lists/15471316/Aerial-Robotics-notes


message:
Transfer byte-buffer with ENC28J60

How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of `uint8_t` from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.

This is how the array is filled:

    uint8_t temp = 0, temp_last = 0;
    byte buf[256];
    length = myCAM.read_fifo_length();
    while (length--) {
      temp_last = temp;
      temp =  SPI.transfer(0x00);
      if ((temp == 0xD9) && (temp_last == 0xFF)) {
        buf[i++] = temp;
        is_header = false;
        i = 0;
      }
      if (is_header == true) {
        //Write image data to buffer if not full
        if (i < 256)
          buf[i++] = temp;
        else {
          i = 0;
          buf[i++] = temp;
        }
      }
    }

body:
Assuming you are using the EtherCard library you can send a UDP packet with:

    ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in `hisip` and `dstPort`.

The prototype for the function is:

    void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example `udpClientSendOnly.ino` with the library shows you UDP sending in action.


message:
Linux SSH command for Arduino Console

I have a Leonardo with a Yun shield, and I would like to be able to control the arduino with a windows form app, but thats besides the point for now at least. Currently, I am using putty and the commands Telnet Localhost 6571. However, I would like to avoid doing that and I was wondering if anybody new how to communicate with the arduino from port 22 at the yun's IP, rather than connecting to the yun and then to the remote local machine. That or I am missing something entirely!

This is the code I am using to try and access the console port of the Leonardo:

<!-- language: lang-java -->

    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                //connect to arduino
                ConnectionInfo ConnNfo = new ConnectionInfo("10.1.1.211", 22, "root", new AuthenticationMethod[] { new PasswordAuthenticationMethod("root", "123456789") });
                using (var sshclient = new SshClient(ConnNfo))
                {
                    sshclient.Connect();
                    //connect to console port of arduino
                    TcpClient tcp = new TcpClient("localhost", 5671);
                    sshclient.Disconnect();
                }
                Console.ReadKey();
            }
        }
    }

Thank you

body:
The console port is only listening on 127.0.0.1 (for security), so only the Yun itself can connect to the console.

You can weaken security and open the port up to the entire local network by editing the file `/usr/lib/python2.7/bridge/console.py` and change the value `127.0.0.1` to `0.0.0.0`.

Any machine on your local network will then be able to connect directly to port 6571.


message:
Coding for a stop button

I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.

How should I code for that stop button? Do I put it in a separate while loop under the void loop?

body:
There are lots of possible approaches. One possibility would be to set up your code something like this:

    enum { STOPPED, PLAYING } flag;

    void setup() {
      // setup stuff ...
      flag = STOPPED;
    }

    void loop() {
      while (flag == STOPPED)
      {
        // wait for start button
        if (start button pressed)
        {
          // initialise the game ...
          flag = PLAYING;
        }
      }

      while (flag == PLAYING)
      {
        // play the game
        if (stop button pressed)
        {
          flag = STOPPED;
        }
      }
    }


body:
One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.

The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.

Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.


body:
If you code your loop without delay() or busy loops then it is pretty easy:

    void loop(){

        if(DigitalRead(RESET_BUTTON)){
           // Reinitialize game state

        }

        //rest of game logic.

    }


message:
Problem reading in Arduino serial port with 5K potentiometer

I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.

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

    void loop() {
      int sensorValue = analogRead(A1);
      Serial.println(sensorValue);
      delay(500);
    }

body:
It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:

![single potentiometer circuit][1]

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


body: Disconnect the pot and take some readings. You should get some random values near zero. That would mean you're not connecting the leads right or the swinger is stuck at one end.


message:
Arduino Nano + RFID RC522 + Ethernet shield W5100

I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.

For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.

Does anybody have some ideas, what I'm doing wrong right here?

body:
I had almost exactly this situation with one of my projects.

The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a [74HC125][1] (4-channel tri-state buffer).

This is the page on [Better SPI Bus Design in 3 steps][2] that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

  [1]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT125.pdf
  [2]: https://www.dorkbotpdx.org/blog/paul/better_spi_bus_design_in_3_steps