message:
Different sensor readings on analog input when connected via USB to self-contained/externally powered

I am building up an electricity monitor using the ACS712 hall effect sensor.  I have tested and built the circuit having the Arduino (Nano) connected via USB to my laptop, and have tested/debugged etc., getting expected results.

I've migrated the circuit to be powered from an external 5v power supply via the VIN pin ([details](http://www.electrodragon.com/product/ac-85-265v-dc-5v-power-module/)—this is not a "wallmart"-style supply).  It is supplying a solid 5.01v across the circuit according to multimeter readings—I've tested at multiple points in the circuit.  The 5v supply is rated at 700mA, so plenty of head room.  The ACS712 is deriving it's power directly from the supply, not the Arduino 5v pin.

I'm running a "calibration" routine that takes readings from the ACS712 (which is measuring AC current) to find the "zero" point (where the AC signal crosses over), which should be the value of half VCC with this sensor—see https://arduino.stackexchange.com/questions/19301/acs712-sensor-reading-for-ac-current for more detail/background on this.  Usually this hovers around 512 (as expected—in the test unit I'm getting 547 when connected to an AC supply).

When I run/test this circuit with the USB connected, I get expected results.  When I remove the USB, the calibration routine returns a much higher value (about 650 in the test units) and resultant readings are therefore incorrect.  The laptop/test computer is not connected to a power supply during these tests.

When the USB is connected, there is no difference in reading across the VIN, 5V or sensor power pins, so the circuit seems to continue working from the external 5V source.  However, I have noted that the 5v output pin on the Arduino drops to about 3.95v when run off the power supply alone, vs 4.7v when powered by USB/both.

When I repeat this test by connecting an external USB power supply to the Arduino USB port (i.e. no serial connection, and removing the laptop from the equation) I get the same results (a higher calibration value and strange readings).

I've read that the analog pin is referenced to the 5V voltage.  This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case? (Given the whole circuit is powered from the same power supply, this seemed unnecessary to me, but I'm still pretty new to this whole thing.)  The ACS is very sensitive to input voltage fluctuations, so I assumed that I'd be better powering it directly and not relying on the Arduino.

Given that I'm supplying a 5v input, should I be switching from the VIN to the 5v pin? (something I've read you can do, and that the VIN should be for 7v+ supply input only).

Is there anything else that could be causing this discrepancy?

For reference, the calibration and read routines are reproduced below.

    #define SENSOR_PIN A0
    #define ACS_MVPA (100)

    double _numSamples = 0;
    double _ampsRMSSum = 0;

    int16_t acs712Calibrate() {
      uint8_t numReadings = 100;
      int16_t vals[numReadings];

      // collect a sample of readings
      for (uint8_t i=0; i<numReadings; i++) {
        vals[i] = constrain(analogRead(SENSOR_PIN), 0, 1023);
      }

      // Freq doesn't need to be 1024 wide, as the max val
      // from the ACS712 will be limited subset.
      // 20A = 100mV/A = 20*100mV/1000 = ~2v max voltage range
      // 2v / 1024 = 0.0048828125v per increment = ~410 potential increment values
      uint8_t freq[512]{0};
      uint8_t offset = 250;
      // count the frequency of specific readings
      for (uint8_t i=0; i<numReadings; i++) {
        freq[vals[i]-offset]++;
      }

      // work out the most frequent value
      // note that if there is a tie, the lowest value will be used
      uint8_t maxFreq = 0;
      int16_t modeVal = -1;
      for (int i=0; i<512; i++) {
        if (freq[i] > maxFreq) {
          maxFreq = freq[i];
          modeVal = i;
        }
      }

      modeVal = modeVal + offset;

      return modeVal;
    }

    void avgRead() {
      //debugSerial.println("_sample()");
      // see https://arduino.stackexchange.com/questions/19301/acs712-sensor-reading-for-ac-current for description

      int rVal = 0;
      unsigned long rSquaredSum = 0;

      // 50hz = 20 milliseconds per wavelength
      // if we measure for 100ms we will get 5 cycles
      // 60hz = 16.66667 milliseconds per wavelength, or just over ~6 cycles
      // from what I can tell, either should be sufficient for our purposes
      int sampleDuration = 100;       // 100ms

      // each logical "sample" is actually made up of a 100ms sample
      // for our internal arithmatic, we need to track the number of internal samples
      // not to be confused with _numSamples which tracks the number of times _sample()
      // is called between _log()
      int sampleCount = 0;

      // take samples for 100ms
      uint32_t startTime = millis();
      while((millis()-startTime) < sampleDuration)
      {
        rVal = analogRead(SENSOR_PIN) - _config.acs712Zero;
        rSquaredSum += rVal * rVal;
        sampleCount++;
      }

      double voltRMS = 5.0 * sqrt(rSquaredSum/sampleCount)/1024.0;

      // x 1000 to convert volts to millivolts
      // divide by the number of millivolts per amp to determine amps measured
      // in the case of the 20A component is 100 mv/A
      double ampsRMS = voltRMS * (1000/ACS_MVPA);

      _numSamples++; // update the overall sample count
      // add this reading to the summed total(which is averaged before logging)
      _ampsRMSSum += ampsRMS;
    }

body:
In preparing this question, I realised that the answer may lay in the statement "I've read that the analog pin is referenced to the 5V voltage. This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case?"

That made sense to me, so I modified the circuit so that the ACS712 runs off the 5v pin, and I'm now getting around 510 (which is as expected) as a calibration value.

Have tested with both USB connected and unconnected and getting a consistent result.


sender: user

message:
How to change baudrate of ESP8266 (12e) permanently?

IMPORTANT: DO NOT USE `AT+IPR=9600`! (see update)

I have an ESP8266 12E module that communicates at 115,200 bauds. Since I use it with an Arduino Nano with SoftwareSerial things get messy. So I found that I should reduce the baud rate of the ESP module.

I found [this link][1] on how to do it.

**I am wondering**

- Is this a permanent change or do you need to do this every time after the module is powered?

- Can I achieve the same by sending the command from the Arduino over SoftSerial? Well, I guess not since I tried and I always get an error on `AT+CIOBAUD=9600` or `AT+IPR=9600`.

- I read somewhere that in newer firmware versions of the ESP8266, the baud rate defaults to 9,600. Can anyone confirm this and if so, is it better to flash this newer firmware?

The module's vendor:

    Ai-Thinker Technology Co.,Ltd.

I think the current version of the firmware is 0.3.0. If I send  `AT+GMR` I get:

    sending AT+GMR

    response: ?AT¥TJÕ¨H(Q�²•ÉÍ¥½¹é‚r¢‚r‚r‚BÕ��Â’‚ŠªŠ¢Ò¢ªÒªÂJm
     SDK versioo:0.3.0
     Ai�½½
     ‚Šj

Again some garbage because of the baud rate which is too high.

Other info on the module:

    sending AT+RST
    response: ?AT+RST
    OK
    WRT
    "%M
    <99CT
     ets Jan  8 2013,rst catse:2, boot lode:(3,7)
    load 0x40100000ntail 4
    chksum 0x89
    ld tail 4
    chm3 tail 8 r 0 aM
     ón't use rtc mem dat`
    sl��oÌÿ
    Ai-Thinker Technology Co.,Ltd.

**UPDATE**

(*) I used an FTDI232 module to send `AT+IPR=9600` to my ESP8266-12E module **and I bricked it**!

**DO NOT USE `AT+IPR=9600` ON AN ESP8266(-12E).**

I did not manage to recover it so far! I tried re-flashing it but I get Invalid head exceptions.

On a new module I sent the `AT+CIOBAUD=9600` command and it worked. Permanently!

My module specs:

    AT+GMR
    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0
    Ai-Thinker Technology Co.,Ltd.
    Build:1.3.0.2 Sep 11 2015 11:48:04
    OK

  [1]: https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

sender: assistant

body:
Looks like you are you are having power supply issue. What is your power supply rating ? and try adding a small capacitor between vcc and ground.
Also its good idea to update the firmware to 0.9 which has baudrate issue fixed.

You can find new firmware at
https://github.com/espressif/esp8266_at


body:
Depending on how recent a version of the AT Instruction Set interpreter your chip has, the two instructions you tried may not be valid ones; they are not listed in Espressif's [ESP8266 AT Instruction Set][1] document. Searches for either "CIOBAUD" or "IPR" in the current document (version 1.5.3) return no results.

The baud rate commands are now "AT+UART_CUR" and "AT+UART_DEF" which configure the entire UART for the current session or the current and future sessions, respectively. The manual's prototype for the command is:

    AT+UART_DEF=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>
    Example:
    AT+UART_DEF=115200, 8, 1, 0, 3

  [1]: https://www.espressif.com/en/file/721/download?token=5D4jCASk

I have used these and can confirm that they work.

What I've found using software serial is that it can push 115200 baud well enough to send commands to the device (though I wouldn't build an application that depends on it) but it can only read reliably up to 9600 baud. I've been able to change my devices' baud rates from 115200 baud to 9600 over software serial; you just have to expect garbage coming back and ignore it:

    // Set ESP8266 baud rate to 9600. You only need to do this once per device
    set software serial baud to 115200;
    send "AT+UART_DEF=9600,8,1,0,0";
    set software serial baud to 9600;
    // From now on, communicate with your device at 9600 baud.


body:
I Connected an FTDI232 module at 115200 baud and could read the specs of the ESP8266 module now:

    AT+GMR
    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0
    Ai-Thinker Technology Co.,Ltd.
    Build:1.3.0.2 Sep 11 2015 11:48:04
    OK

After that I sent the `AT+IPR=9600` command, which first seemed to do the trick.
But after reboot of the module, all I got was garbage response, at any baudrate.

**DO NOT SEND AT+IPR=9600 TO YOUR ESP8266(12e) MODULE**

Maybe the `AT+UART_DEF` command - as mentioned by JRobert - works, but I used the  `AT+CIOBAUD=9600` command and it worked. Permanently!

I hope this can help others.


body: I bricked my Esp with the same command, too. After hours of searching I found a way to reset the bricked esp. https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware I had to set the baudrate to 115200 instead of 9600, and between the uploading files I had to disconnect the esp from power. I hope that helps you and everybody who did the same and found your post over Google.


body:
Using this firmware:
 https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware

and this flasher:
http://yaab-arduino.blogspot.com.br/2015/12/flashing-esp8266-firmware-arduino.html
i was able to recover my esp 8266 12f


message:
Digital Pin State - Some 1, Some 0

I'm running a sketch that looks for inputs to digital pins 3, 4, 5, 6, and 7.  The gist of the sketch is that it's a digitalRead() from 3-7 with a Serial.println() to the monitor. The odd thing is that without any pins connected I'm seeing "0" on some and "1" on others.  I there a reason some will be "0" while other are "1" without anything connected?  I imagine that all pins should read "0" until voltage is detected.

Based on my limited experience I draw the conclusion that a [pull-up resistor][1] will likely resolve my problem.  Thoughts?

  [1]: https://arduino.stackexchange.com/questions/186/button-state-changing-randomly

body:
Yep, in fact I would configure them as INPUT_PULLUP (which uses a built-in resistor), unless you are actually wiring pull up resistors of your own to them.

Also the [Digital pins Tutorial][1] has a bit more info on the modes possible.

  [1]: https://www.arduino.cc/en/Tutorial/DigitalPins


body:
The effect you are seeing is the result of floating pins.

Because the inputs are not at any defined voltage level and will 'follow' the voltage applied. So leaving them unconnected with no defined state will make it look as if its picking up stray signals.

Adding a pull-up resistor, or a pull-down resistor will give you a known  state, the value can be anything from 4.7kohms to 100kohms. So your conclusion to use a resistor is correct.


message:
My Arduino is heating up

I am working on a simple Arduino project where I am controlling 5 TowerPro servos. I read that each takes up 2.2 V each so that means the Arduino can only handle about 2 , if using 5V. So far Ive connected 4 with no issues but when I added the 5th the whole thing stopped and the 5V regulator was really hot. That means I don't have enough power and the Arduino is just having a hard time giving not enought volts for all five servos. I just don't know what to do now. Ive tried adding 3  3V battery packs instead of the Arduino but it was smoking. Is there another way to provide the right amount of power for 5 servos without breaking or burning anything!

body:
The voltage regulator on the Arduino is designed to power the logic circuits, and perhaps a few LEDs and other digital devices. It is not designed to power 5 motors.

You haven't specified what *current* they draw - that is the important question, not the voltage.

As the comments under your question have said, you need to power the motors separately from the Arduino, not *through* it. However, connect the *ground wires*, and use the Arduino to control the signal wire to the servos.

The graphic below shows the general idea. For 5 servos even those batteries are probably not enough.

Notice that the power for the motor does not go through the Arduino.

[![Powering a servo][1]][1]

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


message:
Arduino Memory Best Practice

So I have been diving deep into AVR programming and have seen several different ways of defining constants. I know that some of these methods are from "C" and others are from more modern "C++" methods. So my question here is what is the preferred method?

Method 1:

    #define MAX_ARRAY_LEN 3

    int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

Method 2:

    const int MAX_ARRAY_LEN = 3;

    int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

In my searches online I have ran across several pages that mention using PROGMEM in the declarations to load the variable into Flash memory instead of SRAM. The thing I am unclear about using PROGMEM is what should be loaded into Flash and what should be loaded into SRAM? Should I be loading all const into Flash? Are there any performance hits using Flash?

**Edit**
----------

I guess I was not clear on what I was asking. I understand that #define and PROGMEM are not related. My question is there are a couple of methods that can be used to define constants. One is #define (Method 1) and the other is const (Method 2), with the const type comes the PROGMEM, when using Method 2 there are now 2 areas where you can store variables, Flash and SRAM so when do you want to use PROGMEM and when do you want to just leave it, when using method 2? Is there any performance hits when reading from Flash vs SRAM?

I understand that when using method 2 it is now scoped and typed, but are there any other advantages? Are the programs smaller using one vs the other? Are there times that you would want to use one over the other?

body:
(Duplicate of [this](https://stackoverflow.com/questions/1637332/static-const-vs-define).)

In your example, neither definition of `MAX_ARRAY_LEN` will use program space nor RAM.  If you were to *use* the definition somewhere, it will certainly use program space in the instruction that uses that constant:

    for (int i=0 i<MAX_ARRAY_LEN, i++)
      Serial.print( my_array[i] );

In this case, a CPU instruction will load the constant 3 into a register.  So you can say that the 3 "used" a byte in the CPU instruction, and is part of the program size.  Most people ignore that, because a loading a *variable* into `i` uses both RAM and program space.

The primary advantage of using `const` instead of `#define` is that the former allows additional compiler type-checking.

C++ has introduced another keyword, `constexpr`, which tells the compiler that an entire expression can be evaluated at compile time and reduced to a single constant value.  Read all about it [here](https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const).

To answer your comment, #define's are not stored anywhere.  They are a simple string substituion that happens before the compiler processes the C++ code.

When you build your sketch, the source files are processed in several phases.  First, there's a preprocessor phase that consumes all the lines that start with '#'.  The results of the preprocessing are sent to the C++ compiler.  The compiler will see *all* the included files *inline*, and all #define's will be substituted.

## UPDATE

For example, `#define XXX 3` will cause the preprocessor to replace all occurrences of `XXX` in the C++ file with `3`.  The C++ compiler will never see `XXX`, it only sees `3`.  You could do a search and replace with your editor, and the C++ compiler would not know the difference.  (Well, there are a few more tricks the preprocessor can do for you, but you only asked about defining a numeric constant.)  The generated code would be identical.

There is no "global space" for `#define` symbols.  There is a "dictionary" in the preprocessor that is used to perform the substitution, but that is ephemeral.

PROGMEM is not related to `#define` or `const` at all.  It is an attribute of a variable that indicates it is to be stored in FLASH, not RAM.  I think the key is that `#define` is just string substitution, but `const` is a C++ attribute of a C++ variable.  All of these are equivalent:

    #define MAX_ARRAY_SIZE 3
    const uint8_t maxArraySize = MAX_ARRAY_SIZE;
    int array[ maxArraySize ] = { 1,2,3 };

    #define FOO 1,2,3
    int array[] = { FOO };
    const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

    #define MAX_ARRAY_SIZE goofyNameThatMeansNothing
    const uint8_t MAX_ARRAY_SIZE = 3;
    int array[ MAX_ARRAY_SIZE ] = { 1,2,3 };

    #define BAR = { 1,2,
    int array[] BAR,3};
    #define MAX_ARRAY_SIZE sizeof(array)/sizeof(array[0])

I hope that last 2 goofy examples help illustrate what a `#define` is... string substitution.

The PROGMEM attribute is a separate *thing*.  It can only be added to C++ variables, and it now requires the variable to also be `const`.  Extending the above, you could do this:

    #define MAX_ARRAY_SIZE 3
    const uint8_t maxArraySize = MAX_ARRAY_SIZE;
    const int array[ maxArraySize ] PROGMEM = { 1,2,3 }; // a flash array, not RAM

    #define FOO 1,2,3
    const int array[] PROGMEM = { FOO };
    const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

    #define MAX_ARRAY_SIZE goofyNameThatMeansNothing
    const uint8_t MAX_ARRAY_SIZE = 3;
    int array[ MAX_ARRAY_SIZE ] PROGMEM = { 1,2,3 };

    #define BAR PROGMEM = { 1,2,
    const int array[] BAR,3};
    #define MAX_ARRAY_SIZE 14

Again, in that last goofy example I used PROGMEM in the `#define BAR`, but it's just some characters as far as the `#define` is concerned.  And the last define is just plain wrong, but it will compile.

Because there is no validation of a string substitution, it is usually better to use a `const type var = value;` that can be validated by the compiler, both when it is defined and again when `var` is used in some context.

## UPDATE 2
You say,

>with the const type comes the PROGMEM

Not really.  `const` is the "read-only" attribute, and the compiler enforces that.

PROGMEM tells the AVR compiler that, **if storage is required for this variable**, put it in FLASH memory (a special address range) instead of RAM (a different address range).  Because of the AVR architecture, you must access FLASH differently, with special instructions.  The `avr.pgmspace.h` include file has some routines (macros and inline assembler) for reading from those address spaces.

I emphasized the "storage space required", because the compiler can optimize away the storage.  The literal 3 constant `MAX_ARRAY_LEN` does not need any storage space.  For this example program:

    const int MAX_ARRAY_LEN PROGMEM = 3;

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

      Serial.println( MAX_ARRAY_LEN );
    }

    void loop() {}

This is the generated code:

      Serial.println( MAX_ARRAY_LEN );
    156:    50 e0           ldi r21, 0x00   ; 0
    158:    63 e0           ldi r22, 0x03   ; 3
    15a:    70 e0           ldi r23, 0x00   ; 0
    15c:    82 e2           ldi r24, 0x22   ; 34
    15e:    92 e0           ldi r25, 0x02   ; 2
    160:    f7 c2           rjmp    .+1518  ; 0x750 <_ZN5Print7printlnEii>

The compiler knows that storage is not required.  The value "3" is pushed directly onto the stack at program location 0x158.  It did not go to RAM nor FLASH (PROGMEM) to load a 3 into a register, and then push that register's value onto the stack.

The compiler knows the value, so it uses the "immediate" form of the instruction to push the 3.

However, for this program:

    const int MAX_ARRAY_LEN PROGMEM = 3;

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

      Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
    }

    void loop() {}

The following code is generated:

      e4:   03 00           .word   0x0003  ; ????
         .
         .
         .
      Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
     158:   50 e0           ldi r21, 0x00   ; 0
     15a:   64 ee           ldi r22, 0xE4   ; 228
     15c:   70 e0           ldi r23, 0x00   ; 0
     15e:   82 e2           ldi r24, 0x22   ; 34
     160:   92 e0           ldi r25, 0x02   ; 2
     162:   b5 c2           rjmp    .+1386      ; 0x6ce <_ZN5Print7printlnEji>

Because I took the address of MAX_ARRAY_LEN, the compiler knew that it had to have storage... in order for it to have an address.  The compiler dutifully locates it in the program space, at 0xE4.  You can see that address being pushed onto the stack at 0x15A.

Without the PROGMEM attribute, the following code is generated:

      Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
     156:   50 e0           ldi r21, 0x00   ; 0
     158:   60 e0           ldi r22, 0x00   ; 0
     15a:   72 e0           ldi r23, 0x02   ; 2
     15c:   84 e2           ldi r24, 0x24   ; 36
     15e:   92 e0           ldi r25, 0x02   ; 2
     160:   b5 c2           rjmp    .+1386      ; 0x6cc <_ZN5Print7printlnEji>

This is a RAM address, 0x200.  Long before setup, a 3 is copied from the program space into RAM.  It is using both program space *and* RAM.

But this is only because I took the address of MAX_ARRAY_LEN.  In almost all cases, you will be using these as scalar values.  The compiler will not allocate any storage space for them, and the PROGMEM attribute is irrelevant.

You have another question:

>Is there any performance hits when reading from Flash vs SRAM?

Yes.  Reading from flash takes twice as many CPU cycles.  It's always a juggling act.  If you need to squeeze every cycle out, make sure your constants do not even need storage space (i.e., don't take their address).  And if it's a PROGMEM array or structure, consider using a cached value (i.e., loaded into a RAM array or structure).  Sometimes you don't have a choice.  If you are out of RAM, you will have to load them from PROGMEM every time you need them, with a small penalty.  RAM, SPEED, SIZE... pick two.


message:
millis() in a millisecond stopwatch

I'm making a stopwatch that will measure time between two points.

I want that stopwatch to have a millisecond accuracy.

After the start when someone touch the pad it will show like the time of the touch (15.359) 15 seconds and 359 millis.

I have an arduino uno board.
Everywhere I read it says that millis its not reliable, and in a feel tests it seems not very accurate. Also a lot of places say to use a RTC, but every RTC I found and read about it seem to use only second and not milliseconds. Others say to use a 32 KHz crystal, but I'm not sure if it will fix this. Could anyone give some ideas?

The Arduino will only record time, only that, start and get time and subtract and write on the serial and end.

Thanks!
**update 1:** thanks Mattia for the edit.

**update2 :** I was making some  math, and if the device is on for 8 hours, and i want millisecond precision i need something like 30ppb right?
Would this do the job?
http://www.digikey.com/product-detail/en/abracon-llc/AOCJYR-12.800MHZ-M5649LF/535-12624-1-ND/4989030

body: The resonator on the Arduino Uno is better than the internal oscillator of the Atmega328p, but still not very precise. Therefore, for accurate measurements, you need to use a better quality crystal. For instance @ 16 MHz. Once you set the correct prescaler in the Arduino, this should give you accurate millis() - as long as the crystal that you're using is accurate.


message:
Detect if multiple variables are the same?

I'm setting a series of variables with: `uint32_t currentLedColor[9]`

What I'd like to check is if certain ones of those are the same.

Basically want to say `if currentLedColor[0] and currentLedColor[1] and currentLedColor[2] are equal`

How would I write that?

body:
You run multiple checks. For example:

    if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
        // do something
    }


message:
Best Actuator to Behavioural Positive/Negative Feedback on Cat

Rhetorical, yet silly question: Given an Arduino to manage, what would be the easiest way, in terms of available actuators (price/availability counts) to:

a) Apply a positive feedback to a cat, in exchange for a good action?

b) Apply a *NEGATIVE* feedback to a cat, like trying to reach forbidden places?

body:
For the negative feedback, you could use a loud, screetching noise. I would suspect, however, that the cat would eventually get used to it and ignore it.

Depending on your cat's tastes, you could use the same hardware for positive feedback - playing, for example, a Mozart tune if that's what your cat is into.

I know, a silly answer, but what can you do with a silly question? ;-)


message:
Can the Arduino interface with USB devices without the USB host shield?

I'm looking to connect various USB-devices to an Arduino Uno (specifically, a gamepad and a webcam, but I'm interested in the general case). Is this possible without using the USB host shield, since the Uno has a USB port and USB-to-serial converter? I could use the shield, but I'm curious if/why it's neccessary.

The Sparkfun website states that:

> The SparkFun USB Host Shield contains all of the digital logic and analog circuitry necessary to implement a full-speed USB peripheral/host controller with your Arduino.

Does the Arduino not already contain this, just needing the proper software (although obviously it's easier to use the already written library for the Host Shield). Or are there hardware limitations?

According to
https://arduino.stackexchange.com/questions/16043/can-a-ethernet-usb-dongle-be-instead-of-ethernet-shield-for-arduino
(Majenko's answer), it can, in theory, be done with the Due, but not with the Uno. In that case, is this because the Uno uses the ATmega16U2 instead of the FTDI FT232RL for USB communication?

body:
First things first you need to learn the basics of how USB works.

In USB there are two main "things": Hosts and Devices.

You have one Host (usually your computer) and many Devices (such as Arduinos, Printers, Scanners, Webcams, WiFi dongles, etc).

Being a host involves knowing about what devices you are going to have attached to you and how to communicate with them. Being a device means just communicating with the host in your own way.

As you can see it is a far more complex job being a host than being a device.

Arduinos are devices. The small USB interface chips they use are very low powered and can only be a device, never a host.

If you want to plug a device into something it has to be a host (note: I am purposely ignoring hubs here).

The Arduino Due uses a far more powerful chip, and that is capable of being a host (using what is known as On-The-Go mode).

To do it with anything less powerful than a Due you require additional hardware that is specifically designed to be a USB host - and that is where the USB host shield comes in. It has a chip that is designed specially to be a USB host so you can plug a device in to it.

None of the chips on the Uno are designed to be a host. They just don't have the power.


body:
No.  USB strictly distinguishes between host and device roles.  A few chips have functional blocks capable of performing either role, but the 8u2/16u2 are not examples of this.

Typical USB serial converters like the FT232, CP210x, CH340, PL2303, etc are also strictly devices and incapable of being hosts

There are inexpensive host-capable MCUs like the Kinetis KL25Z, but to use them in their cheapest form you would need a different software approach (for example mbed rather than Arduino) and a lot more personal effort.  The Teensy-LC is related, but you pay more for the Arduino code loading helper on it than for the MCU that runs your program itself.


message:
Will Arduino Pro Mini 3.3V run at half the speed of 5V version?

Provided a very simple sketch like this:

    void loop() {
      digitalWrite(1, !digitalRead(1));
    }

... should I expect 5V Arduino to run twice as fast as 3.3V, or are there some internal adjustments in place?

Specifically, I'm wondering about Pro Mini and/or Nano boards. The "speed" here is simply the frequency measured on pin `1`.

**edit:**

-----

To clarify, I'm wondering if there might be some behind-the-scenes frequency divider that makes sure Arduino code always run at the same physical speed, even if the actual MCUs run on different clocks.

-----

Possibly the simplest way of forming this same question: Can the sketch above be used to identify 3.3V Pro Mini boards from 5V versions, with the help of a frequency meter?

body: If the board is running at half the speed (8MHz instead of 16MHz) then everything that isn't based on real time (i.e., millis(), delay() etc) will run at half the speed. It will all take twice as long to do everything.


message:
2 Direction Motor

Using an  Arduino-Nano, I'm trying to make a circuit that will change the direction of a motor based on two inputs. The input from the Arduino will be amplified by a transistor. Here's the code:

    int rightIn = 2;
    int rightOut = 3;
    int leftIn = 4;
    int leftOut = 5;
    int rightVal = 0;
    int leftVal = 0;

    void setup() {
      pinMode(rightIn, INPUT);
      pinMode(leftIn, INPUT);
      pinMode(rightOut, OUTPUT);
      pinMode(leftOut, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      rightVal = digitalRead(rightIn);
      Serial.println(rightVal);
      leftVal = digitalRead(leftIn);
      if ((rightVal == HIGH) || (leftVal == HIGH)) {
        if (rightVal == HIGH) {
          digitalWrite(rightOut, HIGH);
          digitalWrite(leftOut, LOW);
        }
        if (leftVal == HIGH) {
          digitalWrite(rightOut, LOW);
          digitalWrite(leftOut, HIGH);
        }
      }
      else {
        digitalWrite(rightOut, LOW);
        digitalWrite(leftOut, LOW);
      }
    }
And the arduino wiring:

 - Pins 3 and 5 are attached to the motors power and ground
 - Pins 2 ad 4 go to an seprate inputs

body:
I think you are mixing up your `rightVal` and `rightIn`, and your `leftVal` and `leftIn`.

    rightVal = digitalRead(rightIn);
    ....
    if (rightIn == HIGH) {


message:
Led blinking in the loop in condition

so I will explain what I want to get.
I am reading temperature from DS18B20 and showing it on the LCD.
I have one LED o pin 3 which is blinking when there is a temp reading and screen update. I have another LED on pin 4 which should lit when temp is more than 25 and less than 30, and I want it to blink when temp is more than 30. What I am getting is a blinking but not like one blink every 10ms but it waits for whole loop to start again to blink.
Can I do it separately that this LED will blink indepentantly when condition is true? With set interval for example 10ms which wont be waiting for whole loop.

here is my example code:

        #include <OneWire.h>

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    //LiquidCrystal_I2C lcd(0x27, POSITIVE);  // Set the LCD I2C address
    OneWire  ds(2);

    unsigned long previousMillis = 0;
    const long interval = 1000;
    int ledState = LOW;
    void setup()
    {
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);

      lcd.begin(16,2);               // initialize the lcd

    }

    void loop()

    {
      unsigned long currentMillis = millis();

      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius;

      if ( !ds.search(addr)) {
        ds.reset_search();
        delay(250);
        return;
      }

      Serial.println();

      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          Serial.println("  Chip = DS18S20");  // or old DS1820
          type_s = 1;
          break;
        case 0x28:
          Serial.println("  Chip = DS18B20");
          type_s = 0;
          break;
        case 0x22:
          Serial.println("  Chip = DS1822");
          type_s = 0;
          break;
        default:
          Serial.println("Device is not a DS18x20 family device.");
          return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

      delay(850);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      Serial.print("  Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;

      digitalWrite(3, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(10);              // wait for a second
      digitalWrite(3, LOW);    // turn the LED off by making the voltage LOW

       lcd.home ();
       lcd.print("Reading 1");
       lcd.setCursor( 0, 1);
       lcd.print("temp:");
       lcd.print(celsius);
       lcd.print("*C");

       if (celsius >= 25 && celsius < 30) {
        digitalWrite(4,HIGH);
       } else if (celsius >= 30) {
    blink1();
       } else {
        digitalWrite(4,LOW);
       }

    }

    void blink1() {
    digitalWrite(4,HIGH);
    delay(50);
    digitalWrite(4,LOW);
    }

body:
Here try this:

    #include <OneWire.h>

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    //LiquidCrystal_I2C lcd(0x27, POSITIVE);  // Set the LCD I2C address
    OneWire  ds(2);

    const long interval = 1000; //İnterval at which to blink(milliseconds)
    unsigned long previousMillis = 0;
    int ledState = LOW;
    void setup()
    {
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);

      lcd.begin(16,2);               // initialize the lcd

    }

    void loop()
    {

      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius;

      if ( !ds.search(addr)) {
        ds.reset_search();
        delay(250);
        return;
      }

      Serial.println();

      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          Serial.println("  Chip = DS18S20");  // or old DS1820
          type_s = 1;
          break;
        case 0x28:
          Serial.println("  Chip = DS18B20");
          type_s = 0;
          break;
        case 0x22:
          Serial.println("  Chip = DS1822");
          type_s = 0;
          break;
        default:
          Serial.println("Device is not a DS18x20 family device.");
          return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

      delay(850);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      Serial.print("  Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;

       lcd.home ();
       lcd.print("Reading 1");
       lcd.setCursor( 0, 1);
       lcd.print("temp:");
       lcd.print(celsius);
       lcd.print("*C");

       if (celsius >= 25 && celsius < 30) {
        digitalWrite(4,HIGH);
       } else if (celsius >= 30) {
    blink1();
       } else {
        digitalWrite(4,LOW);
       }

       unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= interval) {

         previousMillis = currentMillis;

         if (ledState == LOW) {
           ledState = HIGH;
         } else {
           ledState = LOW;
         }

         digitalWrite(3, ledState);
       }
    }

    void blink1() {
    digitalWrite(4,HIGH);
    delay(50);
    digitalWrite(4,LOW);
    }

and also note that i choosed 1000 milliseconds for interval (equal to 1 second) so if you want 10ms as in your first post then change `const long interval` to 10


message:
Manual TCP connection using WiFi ESP8266 module mistyped command

The command is working fine if I type it directly to the serial interface

    AT+CIPSTART="TCP","192.168.1.5",1647

But if I want to make it automatic and send it whenever I want from inside the code is not working at all.

Used this but it's not working (Serial1 is from the hardware sp)

    Serial1.println("AT+CIPSTART="TCP","192.168.1.5",1647")

Any way to arrange the data?

body:
You need to escape your quotes:

    Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");


message:
Can you send binary data to arduino AtMega328p?

I was wondering if its possible to send binary data to an Atmega328p. I don't want to send Arduino code or C code just binary. Is it possible to programme the ATmega328p using binary and how?

body:
The serial port is binary data.
Because we humans can read text data easier than binary data we mostly send text. This way we only use a very small amount of the possible band with.
The serial monitor translates your input to binary and the binary input of the arduino to text. If you write a program that uses the serialport directly you can communicate in binary without a prolem.


body:
When you upload your sketch using the IDE, it has been converted from C++ into "binary". So yes, it is possible. In fact that is the only way it is done.

> I don't want to send Arduino code or C code just binary.

The job of the compiler is to convert your C code into binary, and that happens automatically.

You an also use `avrdude` to upload a xxx.hex file (a file containing pure machine code).


message:
Wifi rssi converting char[] to uint8_t

I am trying to get RSSI of a network without connecting to it directly but I get an error " error: cast from 'const char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]"

       char ssid[]="GreenNET";
        long rssi = 0;

        void updateRSSI(){
          rssi = WiFi.RSSI(ssid);
        }

I am following this: https://www.arduino.cc/en/Reference/WiFiRSSI except I am not passing password since it is not required `WiFi.RSSI(wifiAccessPoint);`

body:
The argument passed to `RSSI()` must be an integer indicating the array index of the SSID of the WiFi network whose RSSI you want to get. To get that integer, you must first scan for networks.

    char ssid[] = "greenNet";
    byte num_ssids = 0;
    long rssi = 0;

    num_ssids = WiFi.scanNetworks();
    for (byte net = 0; net < num_ssids; net++){
        rssi = WiFi.RSSI(net);
        Serial.print(WiFi.SSID(net)); Serial.print(": ");
        Serial.println(rssi);
    }


message:
Capacitive sensor switch

I am trying to get relays to switch on or off based on if I touch a capacitive sensor, basically a light switch. For some reason, I get two readings that are high capacitive readings when I do a printout. I am not really sure why this is happening. I tried delays in case it was reading my touch too fast but with no luck.

The hardware is basically a 1M resistor between send and receive.

    // capactitive sensing
    #include <CapacitiveSensor.h>
    CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);
    // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
    const int numReadings = 5;
    int index = 0;                  // the index of the current reading
    int readings[numReadings];      // the readings from the analog input
    int total = 0;                  // the running total
    int average = 0;
    int relay = A2;
    int relay2 = A3;
    int relay3 = A4;
    int relay4 = A5;
    boolean lightState = false;
    // sound sample
    const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
    unsigned int sample;
    //other
    boolean isRelaysOn = false;

    // capacitive sensor
    void setup() {
      cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
      // turn off autocalibrate on channel 1 - just as an example
      Serial.begin(9600);
      for (int thisReading = 0; thisReading < numReadings; thisReading++)
        readings[thisReading] = 0;
      // other
      pinMode(relay, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);
      turnRelayOff();
      Serial.begin(9600);
    }

    boolean state = false;
    boolean lastState = true;
    boolean lightTurnedItOff = false;

    void loop() {
      Serial.println(capReading());
      if(capReading() >= 3000) {
        Serial.println("threadhold reached");
        lightState = !lightState;
        controlRelay();
      }
    }

    boolean isOn = false;

    void controlRelay() {
      if(lightState == true && isOn == false) {
        turnRelayOn();
        //delay(1000);
      }
      if(lightState == false) {
        turnRelayOff();
        // delay(1000);
      }
    }

    void turnRelayOn() {
      int delayAmount = 100;
      digitalWrite(relay, LOW);
      delay(delayAmount);
      digitalWrite(relay2, LOW);
      delay(delayAmount);
      digitalWrite(relay3, LOW);
      delay(delayAmount);
      digitalWrite(relay4, LOW);
      delay(delayAmount);
      digitalWrite(relay4, HIGH);
      delay(delayAmount);
      digitalWrite(relay4, LOW);
      isOn =true;
    }

    void turnRelayOff() {
      digitalWrite(relay, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      isOn = false;
    }

    int capReading () {
      // get average.
      total= total - readings[index];
      readings[index] =  cs_7_6.capacitiveSensor(30);
      total= total + readings[index];
      index++;
      if (index >= numReadings)
        index = 0;
      average = total / numReadings;
      delay(100);
      return average;
    }

The output doesn't make much sense sometimes either, here are a few samples:

> 11 16 21 22 32 61 74 threadhold reached 6191 threadhold reached 6167
> threadhold reached 30 15 11 12
>
>
> 6 10 17 44 2144 3745 threadhold reached
> -475 threadhold reached
> -3129 22 10 12 13
>
> 15 13 7 20 23 725 2726 2735
> -6373
> -3197 threadhold reached 4127 2714 54 40 43 34 24 27 31

body:
In this line:

    readings[index] =  cs_7_6.capacitiveSensor(30);

...you are assigning an "int" the value from a method of type "long".

Likely you will want to change all your types used to track the capacitance value, including the type of your "capReading" method, to "long".


message:
Is there a way to pause Program execution?

I understand that Arduino programming is procedural and not so much Object Orientated and also that the Arduino or AVR are only single core processors and any kind of "Multitasking" or "Threading" is emulated at best but I was wondering if there is a way to pause program execution in one area temporarily and give another area control? For example say we have the following class:

    Class A{
       void Test();
       void ProgramLoop();
    }

    void A::Test(){
       for (int i = 0; i < 10; i++){
          //Lots of cool stuff going on here but need to give
          //Control to someone else say ProgramLoop()
          Sleep(10);
       }
    }

    void A::ProgramLoop(){
       Serial.println("In Program Loop");
    }

Then in the main file:

    A testClass;

    void Setup(){
       Serial.begin(57600);
    }

    void Loop(){
       testClass.Test();
       testClass.ProgramLoop();
    }

I know I could do something like:

    void Loop(){
       if (!testClass.isBusy){
          testClass.ProgramLoop();
       }
    }

But I am trying to find out if there is a way to control how the program execution gives control? I understand that this is more of a threading topic, thats not what I am trying to get at, I just want to know if this is possible maybe using some sort of built in function or something? Or do my programs have to "Fall Through" being ONLY Procedural?

body:
[This][1] article gives a great example of multitasking by using [FreeRTOS][2].

I am pasting the sample code snippet which is pretty much self explanatory.

    #include <Arduino_FreeRTOS.h>

    // define two tasks for Blink & AnalogRead
    void TaskBlink( void *pvParameters );
    void TaskAnalogRead( void *pvParameters );

    // the setup function runs once when you press reset or power the board
    void setup() {

      // Now set up two tasks to run independently.
      xTaskCreate(
        TaskBlink
        ,  (const portCHAR *)"Blink"   // A name just for humans
        ,  128  // Stack size
        ,  NULL
        ,  2  // priority
        ,  NULL );

      xTaskCreate(
        TaskAnalogRead
        ,  (const portCHAR *) "AnalogRead"
        ,  128 // This stack size can be checked & adjusted by reading Highwater
        ,  NULL
        ,  1  // priority
        ,  NULL );

      // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
    }

    void loop()
    {
      // Empty. Things are done in Tasks.
    }

    /*--------------------------------------------------*/
    /*---------------------- Tasks ---------------------*/
    /*--------------------------------------------------*/

    void TaskBlink(void *pvParameters)  // This is a task.
    {
      (void) pvParameters;

      // initialize digital pin 13 as an output.
      pinMode(13, OUTPUT);

      for (;;) // A Task shall never return or exit.
      {
        digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
        vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
        digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
      }
    }

    void TaskAnalogRead(void *pvParameters)  // This is a task.
    {
      (void) pvParameters;

      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);

      for (;;)
      {
        // read the input on analog pin 0:
        int sensorValue = analogRead(A0);
        // print out the value you read:
        Serial.println(sensorValue);
        vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
      }
    }

  [1]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc
  [2]: http://www.freertos.org/


body:
If you have used threading before, this library-

https://github.com/ivanseidel/ArduinoThread

makes it very easy to schedule tasks in a controlled manner.

I would put this in a comment, but I don't have enough reputation yet.


message:
what units do Mouse.move() use?

When I use Mouse.move() method (https://www.arduino.cc/en/Reference/MouseMove), what are units of xVal and yPos parameters?

body: They're raw HID counts and as such don't have a unit. It is up to the OS to translate them from logical amounts to physical values.


message:
Purpose of extra holes for pins or Arduino clone

I bought this Arduino clone recently and it has lot of extra holes for pins, but some of them I don't know what they do. There was no instruction manual that came with it. Here's a picture of it, I added a red rectangle around the ones I don't know. (4 pins with X1, SCL/SDA, AREF and blank pin in the bottom)
[![Arduino uno clone unknown pins][2]][2]

I thought I could use the pins SCL SDA 5V GND with my I2C LCD Display because the names of the pins are the same on it. Could it work? Usually I use analog pins to connect the display, does that mean that by using it some analog pins will be used indirectly? I didn't try connecting it because I don't want it to break.

[![enter image description here][3]][3]

What do these pins do?

  [2]: https://i.stack.imgur.com/KVnWI.jpg
  [3]: https://i.stack.imgur.com/Jbrll.jpg

body:
It's what they say they are.

SDA/SCL are I2C - what used to be A4/A5 on the old footprint. On the '328 based boards those are directly linked to the A4/A5 pins.

The blank pin isn't used. The 5V next to it is actually mislabelled and should be labelled "IOREF".

AREF has been there since the very first Arduino boards.

It's the standard "R3" Uno footprint, plus some extra breakouts for the I2C in different forms (probably to go with specific I2C devices they also sell).

All of that is on the [Uno's product page](https://www.arduino.cc/en/main/arduinoBoardUno) if you'd care to read it some time...

The ones by the cheap Chinese USB interface chip will be something to do with that. Maybe RTS/CTS broken out on a header. You can ignore those - they are of no interest at all. In fact, just looking in their direction has a good chance of breaking the USB interface chip. Stay well away.


message:
Delay function not working as intended

int j;
    void setup()
    {
       for(j=2 ; j<=9 ; j++)
          pinMode( j , OUTPUT );
       digitalWrite( 2, HIGH );
    }
    void one()
    {
       digitalWrite( 3, HIGH );
       digitalWrite( 4, HIGH );
    }
    void all_off()
    {
       for(j=3 ; j<9 ; j++)
          digitalWrite( j,LOW);
    }
    void loop()
    {
       one();
       delay(1000);
       all_off();
       delay(3000);
    }

Trying to do a blinking "1" (stopped at 1 before continuing other numbers because of this problem ) with a single-digit 7 segment display. Where pin 2 is comnected to the com pins of the display.

Expected: display 1 for a second , then turn off for 3 seconds.

Reality: display1 for 3 seconds then turn off for a second.

Tried putting the delay functions in the one and all_off functions but no use.

Tried changing the delay(1000) to delay(7000) , the off time increased.

Tried changing the delay(3000) to delay(1000) , the turn on time changed to 1 second.

The code should work in order, should it not?  What is happening? How to fix it?

body: Without circuit information and part numbers, one can't say for sure what the problem is.  However, the symptoms suggest that your LEDs turn on when you pull some pin low, rather than when it goes high.  This can happen if, for example, the LED anodes are wired (through a resistor) to V+ and the cathodes are connected to a drive pin.  If, however, the cathodes are connected to  ground through a transistor, positive-logic should apply, rather than negative logic.


message:
Mass Storage with Arduino Uno and LUFA

guys ! I want to implement the mass storage example from the LUFA Library to my Arduino Uno, but I do not know where to start. Has anybody done this successfully and could give me a few pieces of advice ?

body: You start by taking the Uno and putting it aside, and picking up an AVR-based Arduino that has native USB device support such as a Leonardo or Esplora. You can then use the build scripts that come with LUFA to build the code for your device.


message:
Arduino with wifi shield and 5AA batteries current draw

Arduino uno with official Wifi Shield take 5 Volts.
Arduino lights up as it should when powered but the WiFi shield is dead the l9 doesn't light up but works fine when arduino is connected to usb cable.

I use 5 battery holder 5x1.5V = 7.5 V ; 2000 mAH

    50 mA - Arduino
    300 mA - WiFi shield

    350 mA * 5h = 1750 mAh

    5xAA = 7.5V ; 2000 mAh

Am I missing here something? It should last in the worst case scenario 5 hours with new batteries at 2000 mAH (which I think they have more but I do not have them on me right now).

body:
As a general answer, yes. AA alkaline should be more around 2500~3000 mAh depending on quality. 5x AA in series would result in 7.5 Volts and 2500 mAh.

But that's only for almost fully charged batteries. AA batteries can range from 1.6V to 0.8V "dead for most purposes". As they drain, the voltage drops.

What may be happening is that you are powering the Arduino through its power jack, which goes through a diode, causing a 0.7V drop. Then it goes to the linear regulator which has a very high drop out voltage. Or even via the VIN pin, bypassing the diode. But as the battery drains, the voltage drops below the regulator ' s limit.

The Arduino microcontroller can easily work below 5V. The shield might not.


body:
4xAA = 6.0V connected to a standard diode like 1n4001 = ~5.4V (within the specs for an AVR), connect directly to Vdd (+5V on arduino's). Unless there's a reason you need to use a 7.5V pack. Bypass the protection diode & Vreg = less wasted energy on heat/diode drops. IIRC, the WIFI/Ethernet shields can spike to 500mA or so, so that may also be causing extra drain. If your code constantly uses the WIFI radio, it will cause more current spikes as opposed to using the WIFI less in your code. Your avg current will decrease and battery life will go up. You'll save batteries by using 4 instead of 5 and not cause the 5V regulator to drop out and cause power issues by bypassing its input at Vin and connecting the 6V pack with a series diode to drop it to ~5.4V and connecting to +5V on an Arduino. It will also help with Vdrop when the WIFI has a current spike.

Also note that as any battery discharges, it's more of a slope than straight line and then dead, even for lithium packs. look at this link, good info for you to understand.
[**http://www.powerstream.com/AA-tests.htm**][1]

  [1]: http://www.powerstream.com/AA-tests.htm


message:
EEPROM - Storing Static Data

I'm trying to store four items to EEPROM.  I can do one item no problem, I just don't know how to make the jump to multiple items.

My code:

    #include <EEPROM.h>
    char sgrpID[31] = "acpilot's arduino";
    char addrID[51] = "123 any street rd";
    char zpcdID[11] = "12345";
    char gwayID[31] = "what a cool toy!";

    void setup()
    {
      Serial.begin(9600);
      for (int i = 0; i < 6; i++) {
        EEPROM.write(i, sgrpID[i]);
        EEPROM.write(i, addrID[i]);
        EEPROM.write(i, zpcdID[i]);
        EEPROM.write(i, gwayID[i]);
      }
    }

    void loop() {
      Serial.println(sgrpID);
      Serial.println(addrID);
      Serial.println(zpcdID);
      Serial.println(gwayID);
      delay(99999);
    }

I want to be able to call on these in a sketch and post them to a db along with dynamic data of some flavor (TBD).

Am  on the right path?  Any help, corrections, or general guidance is appreciated.  I've moved beyond the "novice" stage of basic Arduino programming but an completely new to EEPROM.  If in doubt, SLOWER AND LOUDER is by far the best way to communicate key EEPROM concepts to me.

I have reviewed the Arduino EEPROM library but I was reading Greek.  I keep reading it and I'm sure at somepoint I'll recognize a pattrn and start to "get it."

body:
Some things I noticed in your code:

 - You are writing everything to the same address (is that intentional?)
 - You are only writing the first 6 six bytes of your arrays (I am pretty sure that is intentional)
 - You are declaring these arrays to be bigger than what you are putting in them (this is again probably intentional, but I am just guessing)

So here is an example of how I would handle the eeprom:

    #include <EEPROM.h>

    char sgrpID[31] = "acpilot's arduino";
    char addrID[51] = "123 any street rd";
    char zpcdID[11] = "12345";
    char gwayID[31] = "what a cool toy!";

    //These are the definitions of what goes where in memory
    //You do not want everything to have the same number
    const size_t SGRP_ID_EE_START = (0);  //Zero is good address to start
    //To get the next address we merely add the size of the first item
    //With the address of the first item
    const size_t ADDR_ID_EE_START = (sizeof(sgrpID) + SGRP_ID_EE_START);
    //And so on and so forth
    const size_t ZPCD_ID_EE_START = (sizeof(addrID) + ADDR_ID_EE_START);
    const size_t GWAY_ID_EE_START = (sizeof(zpcdID) + ZPCD_ID_EE_START);

    //Use this function to write a char array to the EEPROM at
    //The address "address" (and the size of "len")
    void WriteEepromArray(size_t address,char* arr,size_t len){
      for (size_t x = 0; x < len; x++){
        EEPROM.write(address+x,arr[x]);
      }
    }
    //Use this function to load your char array with values from
    //The EEPROM
    void LoadFromEeprom(size_t address,char* arr,size_t len){  //Be aware that this function modifys the data pointed to by "arr"
      for (size_t x = 0; x < len; x++){
        arr[x] = EEPROM.read(address+x);
      }
    }

    void setup()
    {
      Serial.begin(9600);
      //Some sample writes
      //               starting address----array-----size of the array
      WriteEepromArray(SGRP_ID_EE_START   ,sgrpID   ,sizeof(sgrpID));
      WriteEepromArray(ADDR_ID_EE_START   ,addrID   ,sizeof(addrID));
      WriteEepromArray(ZPCD_ID_EE_START   ,zpcdID   ,sizeof(zpcdID));
      WriteEepromArray(GWAY_ID_EE_START   ,gwayID   ,sizeof(gwayID));
      //Use the following to load:
      LoadFromEeprom(SGRP_ID_EE_START,sgrpID,sizeof(sgrpID));
      Serial.println(sgrpID);   //Now it should be loaded

    }

The comments I hope help....otherwise comment below with what I left out.


message:
Possible Arduino Uno c++ compiler bug?

I recently gave the students in my Arduino-based programming class a project to write some simple unit tests and fix the bugs that they encountered as they did.  The class in question mostly stores a bunch of Arduino-style String objects, with various getters and setters and a couple of constructors.

The test code that they're supposed to write involved creating two instances of the class (on the stack) and verifying that the constructors set the values correctly.  When I went through the exercise myself, everything worked.

When the students repeated the exercise, the first object worked.  The second object returned empty strings.  If they commented out the first object, the second object began working.  I couldn't find any obvious mistakes that could explain these failures.

After staring at their code for about ten minutes to make sure I wasn't losing it, I compared Arduino IDE versions to make sure my machine was running the same version.  It was.

Next, I unplugged one of their Arduino Uno devices and plugged in my Mega 2560.  The exact same source code passed the unit tests as expected.  That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Before I file a bug against the Arduino Uno compiler (v1.6.7, though I don't see anything in the 1.6.8/1.6.9 release notes that imply any compiler changes since then), I wanted to make sure I wasn't missing something subtle.  Could somebody take a look at this and see if I missed anything?

I've included a condensed version of the class in question below (with irrelevant bits removed).  You can see the complete set of exercises at:

https://sites.google.com/a/cabrillo.edu/cs-11m/schedule/unit-testing-exercises

The tests failed unexpectedly after they added the second ``AddressBookEntry`` object.

**Class Declaration (partial)**

    class AddressBookEntry {

      public:
        AddressBookEntry(void);
        AddressBookEntry(String title, String firstName,
                         String middleName, String lastName,
                         String suffix);

        String title(void);
        String firstName(void);

    ...

      private:
        String _title;      // Mr.
        String _firstName;  // Barack
        String _middleName; // Hussein
        String _lastName;   // Obama
        String _suffix;     // Sr.

        String _addressLine1; // The White House
        String _addressLine2; // 1600 Pennsylvania Ave.
        String _city;         // Washington
        String _state;        // DC
        String _zip;          // 20500
        String _plusFour;     // 0001   (from 20500-0001)

        String _homePhone;    // Unknown
        String _mobilePhone;  // Unknown
        String _workPhone;    // 202-456-1414

**Implementation (partial)**

    #define assert(condition) { \
      if (!(condition)) { \
        Serial.print(__FILE__); \
        Serial.print(":"); \
        Serial.print(__LINE__); \
        Serial.println(": Assertion failed: " #condition); \
        while (1); \
      } \
    }

    bool AddressBookEntry::runTests(void)
    {
      Serial.println("Running tests.\n"); Serial.flush();

      AddressBookEntry testEntry("Mr.", "Jim", "Bob", "Murphy", "Sr.");

      Serial.println(testEntry.title());
      Serial.flush();

      assert(testEntry.title() == "Mr.");
      assert(testEntry.firstName() == "Jim");
      assert(testEntry.middleName() == "Bob");
      assert(testEntry.lastName() == "Murphy");
      assert(testEntry.suffix() == "Sr.");
      testEntry.setMiddleName("Phil");
      assert(testEntry.middleName() == "Phil");

      AddressBookEntry obamaEntry("Mr.", "Barack", "Hussein", "Obama", "");

      assert(obamaEntry.title() == "Mr."); // fails
      assert(obamaEntry.firstName() == "Barack"); // fails
      assert(obamaEntry.middleName() == "Hussein"); // stopped checking here.
      assert(obamaEntry.lastName() == "Obama");
      assert(obamaEntry.suffix() == "");

      Serial.println("All tests passed.\n"); Serial.flush();
    }

    AddressBookEntry::AddressBookEntry()
    {
      _title = "";
      _firstName = "";
      _middleName = "";
      _lastName = "";
      _suffix = "";

      _addressLine1 = "";
      _addressLine2 = "";
      _city = "";
      _state = "";
      _zip = -1; // Deliberate bug
      _plusFour = -1; // Deliberate bug

      _homePhone = "";
      _mobilePhone = "";
      _workPhone = "";
    }

    AddressBookEntry::AddressBookEntry(String title, String firstName,
                                       String middleName, String lastName,
                                       String suffix)
    {
      _title = title;
      _firstName = firstName;
      _middleName = middleName;
      _lastName = lastName;
      _suffix = suffix;

      _addressLine1 = "";
      _addressLine2 = "";
      _city = "";
      _state = "";
      _zip = -1; // Deliberate bug
      _plusFour = -1; // Deliberate bug

      _homePhone = "";
      _mobilePhone = "";
      _workPhone = "";

    String str = "";
      Serial.println(str + "title is \"" + title + "\"");
    }

    String AddressBookEntry::title()
    {
      return _title;
    }

    String AddressBookEntry::firstName()
    {
      return _firstName;
    }

    ... // remaining getters are similar

**Calling Code (from setup() function)**

      Serial.begin(9600);
      AddressBookEntry myEntry;
      myEntry.runTests();

body:
> That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Not a subtle difference - a big difference.  The Mega2560 has considerably more RAM than the UNO (8kB compared to 2kB).

All those strings are using RAM. Lots of RAM.  Your Mega2560 has enough RAM to cope (just), but the UNO just dumps its stack in a heap all over the floor1 at the mere thought of trying to handle that quantity of string data.

----
1: That's a technical way of describing the stack and the heap meeting and, if there were no protection, colliding into each other.


message:
Over voltage protection for Arduino

If an external voltage of 7 volts is applied to the external voltage input on the Arduino and the power from the USB port remains connected, is there a protective circuit that will protect the Arduino?  Thank you.

body: yes there is. power will be drained from external source(altough 7 volts is around the limit and arduino may switch to usb power) and arduino will still operate at 5v, same as usb. in any case your arduino and usb will be safe.


message:
Arduino SoftwareSerial - can't get data from NEO 6M-GPS module

I am using Mikael Hart's TinyGPS (v.13) library and example code to talk to my module. The LED on the GPS module is lit and flashing which I assume means it is receiving data from the GPS satellites. The module seller claims that the module has a default baud of 38400.

I'm pretty sure it's wired up correctly:

[![Arduino side][1]][1]
[![Neo 6M-0-001 side][2]][2]

And my sketch says:

    SoftwareSerial ss(4, 3);

So I read this as Orange (Rx) to pin 4 and Brown (Tx) to pin 3.

Any help appreciated

  [1]: https://i.stack.imgur.com/TOfy9.jpg
  [2]: https://i.stack.imgur.com/yILgM.jpg

body:
RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS.  Arduino pin 3 (ss TX) goes to the GPS RX.

And you should use pins 8 & 9 instead.  That would let you use [AltSoftSerial](https://github.com/PaulStoffregen/AltSoftSerial), the best choice when you can't use HardwareSerial (i.e., `Serial`).

If you can't use pins 8 & 9, then [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) is a better choice than SoftwareSerial.

And while I'm promoting NeoSWSerial, I'll mention a library I wrote, [NeoGPS](https://github.com/SlashDevin/NeoGPS)...  It's faster and smaller than all other GPS libraries, and very configurable.  It also has several [diagnostic programs](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Examples.md#diagnostics) and a [Troubleshooting](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md) section in the docs.


message:
Connecting Arduino to internet through HC-06 and then smartphone

Can I use HC-06 to connect the Arduino to a smartphone (which I am already doing) and thereafter take the data to the internet?

body:
Yes, but not in quite the way you think.

In this case the smartphone is acting exactly like the PC when you have the Arduino plugged in to it. You have a serial connection. Theoretically you can:

* Send a request to the smartphone over the serial bluetooth connection
* Write some software on the smartphone to interpret that request and perform some action depending on what the request is

That way the smartphone is then acting like an incredibly expensive and bulky ESP8266.


body:
old thread I know..

You can use MIT App Inventor to write/make an app for your Android phone.

This will do several things:

 * pair with your Arduino/BT device.
 * take data sent from the Arduino/BT device and parse it
 * do what you like with that data at that point, save to a database..etc. send info to a map (like google maps)..etc

You havent stated what you want to do with the data after it reaches the phone.

Alternately.. you may be able to get rid of the BT device.. and use an ESP8266 wi-fi module and connect directly to a 3rd party web script/service and dump the data directly to the 'internet'


message:
Current Arduino STL Libraries

I was going to update [this question][1] but I thought that this was different.

I have been trying to get std::vector to work with the latest Arduino. I have tried downloading several libraries found online but I can not get one of them to compile correctly. So here is my question, does anyone CURRENTLY know of a Arduino STL Library that is working?

[StandardCplusplus][2]: As stated above I tried to use this library but run into problems with the new/delete functions.

[Andy Brown's AVR-STL Library][3] doesn't even seem to come close to compiling.

If anyone has a working copy of these two I would love to have a copy or if you can tell me how to get them to compile. Otherwise I really need to find a way to get Vectors working, does anyone have any ideas?

**Edit**
----------

I didn't want to answer this question so it is still active as I am sure there will be additions to this. Anyways I FINALLY got a library to work (for now, so far). I downloaded the [StandardCplusplus][2] library and found that in order to get any of the stl functions to work you have to add an include to the "StandardCplusplus.h" file before EVERY use, not just in the first file as stated in the Wiki on the Project page.

So I was able to get vectors to work using the following:

    #include "StandardCplusplus.h"
    #include <iterator>
    #include <vector>

    vector<int> test;

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

       test.push_back(1);
       test.push_back(2);
       test.push_back(3);
       test.push_back(4);
    }

    void loop(){
       for (int i = 0; i < test.size(); i++){
          Serial.println(test[i]);
       }
    }

I would still like to know of other working STL Libraries as it seems that there are tons of outdated and old libraries out there.

  [1]: https://arduino.stackexchange.com/questions/24148/avr-stl-library
  [2]: https://github.com/maniacbug/StandardCplusplus/blob/master/README.md
  [3]: http://andybrown.me.uk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/

body:
I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called [ArduinoSTL][1].

  [1]: https://github.com/mike-matera/ArduinoSTL


message:
Arduino + WiFi 101 Gerber Files

Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101?  I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side.

Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP?  I am under the impression that it is open source but I'm not sure where the OS boundary ends.

body:
On the [Arduino UNO][1] and [Wifi shield][2] websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says

> The Uno is open-source hardware! You can build your own board using
> the follwing files

With the free version of [Eagle][3], you can open it and export to gerber file format.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: https://www.arduino.cc/en/Main/ArduinoWiFiShield101
  [3]: http://www.cadsoftusa.com/download-eagle/freeware/


message:
Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw

I am unable to properly connect those things together with batteries:

    Arduino Uno
    Parallax continuous servo
    Arduino wifi shield

5xAA batteries are connected through power jack to arduino which I assumed would power both arduino and the wifi shield and then I have 1 9 volt battery to power 2 servo motors.

With this setup it seems like I can only get to run 1 servo at a time.

Here is a picture how it looks like: https://i.stack.imgur.com/7mGKe.jpg

I'm really desperate for any advice/guidance when it comes to powering this thing.

body:
9V batteries can only supply  very little current. So two servo's is too much.

Just use another set of multiple AA batteries for the servo's.


message:
How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?

I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it.
Before burning my object of experience, I prefer to ask my silly question to the community.

Context :

- I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
- I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

- can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?

body:
It's quite hard to understand what you want from your question, it's quite "woolly".

However, I will note:

1. It's not possible to output a negative voltage from a normal microcontroller.
2. Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is *with respect to ground*. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, *with respect to that IO pin,* to be negative.  With the IO pin LOW it will appear, *with respect to that IO pin,* to be positive.

Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be *with respect to groud,* so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen *with respect to the IO pin*.


message:
Serial is freezing arduino

I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.

It always worked very well, then out of the blue, it stopped printing anything using Serial.print();

But if I ommit the "Serial.begin(9600);" line, the code runs **normally**, sending sensor data via MQTT, even if I can't see debug output.

This shows the problem is on the Serial handling.

Since I can't show the entire code here, here's two test cases:

1.

    void setup(){
      Serial.begin(9600);
      Serial1.begin(9600);
      while(!Serial); //Wait until Serial is ready before printing
    }

    void loop() {
      Serial1.println("This came from serial 1"); //does nothing
      Serial.println("This came from serial 0");  //works
      delay(1000);
    }

It shows me the following output:

> This came from serial 0
>
> This came from serial 0
>
> Thi

Looks like the module freezes before the third iteration.

But if I omit the lines that aren't printed, from Serial1:

2.

    void setup(){
      Serial.begin(9600);
      while(!Serial);  //Wait until Serial is ready before printing
    }

    void loop() {
      Serial.println("This came from serial 0");  //works
      delay(1000);
    }

No output is shown on Serial monitor.

What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?

Observations:

I tested the code in two LinkIt ONE modules of the same model.

I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.

Edit:

Just made another test using the code below. It blinked two times showing that

Serial.begin(9600); runs

while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)

But Serial.println(); freezes

    void setup(){
      pinMode(13, OUTPUT);
      blink();
      Serial.begin(9600);
      blink();
      while(!Serial); //Wait until Serial is ready before printing
    }

    void loop() {
      Serial.println("This came from serial 0");  //works
      blink();
      delay(1000);
    }

    void blink(){
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);
    }

body:
I have bit similar problem. I thing, this is arduino bug.
When start serial port, must be take out data from Rx. When read buffer overflow my arduino freeze. I can't run delay because when arduino wait, serial port can receive lot of data -> overflow -> freeze. Instead of delay I use own function wait(milis):

    void wait(unsigned long wait_time){
      unsigned long start_time;
      start_time=millis();
      while ( millis() < (start_time+wait_time) ){
        if (serial.available() > 0) serial.read();
      }
    }


body:
The problem was solved by:

 - making a clean install of Arduino IDE 1.6.9
 - uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.


message:
Use terminal command to verify software

I've seen that it is possible to use terminal command to verify software instead of using the IDE. Something like ```arduino --verify lab.ino```.
Is there a way to do so on Mac OS?

Thank you

body:
Use AVRDude, and set the `op` field to `v` for verify. E.g.:

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-A703114N -b57600 -D -Uflash:v:/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:i

change `/dev/cu.usbserial-A703114N` to your serial port.

change `/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex` to your hex file.

More info on avrdude at http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions

Sample output would be:

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Volumes/Lion-Data/home/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbserial-A703114N
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 2
             Firmware Version: 1.16
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: verifying flash memory against /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
    avrdude: load data flash data from input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex:
    avrdude: input file /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/build7a7055aab8d0564b6a7844b201562ffe.tmp/CV-turner.ino.hex contains 7902 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 3.34s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0002
             0x64 != 0x6a
    avrdude: verification error; content mismatch

    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: safemode: Fuses OK (H:00, E:00, L:00)

    avrdude done.  Thank you.

Notice the `verification error, first mismatch at byte 0x0002`

PS. you need an actual `hex` file, not an `ino` file. Different compilers and different versions of the Arduino IDE can produce slightly different hex files, for the exact same C-program.


body:
I managed to verify code from terminal by invoking ```/Applications/Arduino.app/Contents/MacOS/Arduino --verify lab.ino``` BUT this command automatically starts the IDE and exits it afterwards. Even with an IDE instance open it will start a new one. This is annoying since it will switch the active workspace away, but it kinda works. See [arduino manpage][1].

  [1]: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc


message:
Opening webpage using ESP8266 in Arduino

I am trying to open the webpage in ESP8266 via Arduino Mega.
I have successfully opened the webpage if I use the **AT command** in the Serial Monitor

The output is perfect

    +IPD,382:HTTP/1.1 200 OK
    Server: nginx
    Date: Sun, 08 May 2016 06:44:47 GMT
    Content-Type: text/html
    Connection: close
    Vary: Accept-Encoding
    X-Powered-By: PHP/5.5.26
    Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache

    S|R190|W5|O31.0|T0|A24|CLOSED

As you can see the output is fine.
Now If I issue commands using Arduino Serial1.print() and read the output using following code:

     while( Serial1.available() )
     {
         inChar = Serial1.read();
         Serial.write(inChar);
         //delay(1);         //could play around with this value if buffer overflows are occuring
     } // while

The output **skips character randomly**

    +IPD,386:HTTP/1.1 200 OK
    Server: nginx
    Date: Tue, 17 May wed-y: HP/.5.26
    SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
    Epirs: hu, 19Nov198 0852:0 GT
    ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
    raga: o-cche
    F~SR19|W5O310|T90|ENDLOSD

I have tried different values of **delay()** but of no help.
My baudrate is **9600** for both arduino Serial and ESP8266 Serial1

Can you please tell me what can be the reason.
Thanks

body:
First things first: *never* use a delay when reading from serial.

You are just blindly trying to read data and send it out to another port. That's not going to work unless you know *how much data* you need to read.

And that information is handed to you on a plate - you just need to interpret it.

You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data.  For instance, when you read the characters `+IPD` you know you have an IP Data response to be interpreted.  Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.


message:
Find remote ip address TCP

Found this "Remote IP of TCP Socket" at:
https://e2e.ti.com/support/wireless_connectivity/simplelink_wifi_cc3000/f/851/t/380635

I am trying to log the remote ip address of a client.  Using Ethernet, I have accomplished remote ip address logging.  Trying to do the same with the Adafruit CC3000 library.

**Answer provided; does not respond every time with the correct "client.IP".** When it is wrong; client.IP is always "client.IP: 0.0.0.0.0" which occurs more frequently than the correct "client.IP" of my computer.  Why is does this happen?  Is there a solution?   Answer is on the right track; need additional help, so client.IP is correct every time.

Edit:  File modified is Adafruit_CC3000_Server.cpp  Only change was to the clientIndex value.  Will this cause an impact on client connecting?  File is contained in "Arduino Stack Exchange.zip" linked in this post and is located in the Adafruit_CC3000 folder of the zip.  Changes are commented.

Modified files with client ip  returned.  https://drive.google.com/open?id=0Byo8QWKyqAT9TUt4d0FteENQS2s CC3000.zip

William

body:
This function is not built-in so you'll have to modify the library slightly. This is one way to do it, I think:

 - Navigate to the `class Adafruit_CC3000_ClientRef` in the file `Adafruit_CC3000_Server.h`. In the class definition, just before the `private` methods and attributes are defined, you will add a new public attribute as follows:

        uint8_t ip_addr[4];  // assuming a typical IPv4 address

    It will hold the IP address of each `ClientRef` instance as the connection is accepted.

 - Go to `Adafruit_CC3000_Server::acceptNewConnections()` near the end of `Adafruit_CC3000_Server.cpp`. A few lines will be added to get the IP address from the CC3000 and store it temporarily in the appropriate `struct`:

        static sockaddr tSocketClientAddr;  // file scope
        static socklen_t addr_len;

        // Accept new connections and update the connected clients.
        bool Adafruit_CC3000_Server::acceptNewConnections() {
          bool newClientCreated = false;
          // For any unconnected client, see if new connections are pending and accept
          // them as a new client.
          for (int i = 0; i < MAX_SERVER_CLIENTS; ++i) {
            if (!_clients[i].connected()) {
              // Note: Because the non-blocking option was set for the listening
              // socket this call will not block and instead return SOC_IN_PROGRESS (-2)
              // if there are no pending client connections. Also, the address of the
              // connected client is not needed, so those parameters are set to NULL.
              cc3k_int_poll();
              addr_len = sizeof(tSocketClientAddr);
              int soc = accept(_listenSocket, &tSocketClientAddr, &addr_len);
              if (soc > -1) {
                _clients[i] = Adafruit_CC3000_Client(soc);
                newClientCreated = true;
              }
              // else either there were no sockets to accept or an error occured.
            }
          }
          return newClientCreated;
        }

 - You'll also edit the `getClientRef()` method in `Adafruit_CC3000_Server.cpp`:

        Adafruit_CC3000_ClientRef Adafruit_CC3000_Server::getClientRef(int8_t clientIndex) {
          if (clientIndex != -1) {
            Adafruit_CC3000_ClientRef newClient =  Adafruit_CC3000_ClientRef(&_clients[clientIndex]);
            // at least 2 (family) + 2 (port) + 4 (ip_addr) bytes expected
            // also check if address is standard ipv4
            if ((addr_len >= 8) && (tSocketClientAddr.sa_family == AF_INET)){
               // copy address into array; in network byte order
               memcpy(newClient.ip_addr, &(tSocketClientAddr.sa_data[2]), 4);
            }
            return newClient;
          }

          // Couldn't find a client ready to read, so return a client that is not
          // connected to signal no clients are available for reading (convention
          // used by the Ethernet library).
          return Adafruit_CC3000_ClientRef(NULL);
        }

    Save all the files.

 - Now the address is stored in an array for each client and can be accessed from your sketch. For example, you can access the address in your sketch like this:

     In the `loop()` of the the `HttpServer` example:

         Adafruit_CC3000_ClientRef client = httpServer.available();
         if (client) {
           Serial.println(F("Client connected."));
           for (int i = 0; i < 3; i++){
             Serial.print(client.ip_addr[i]);
             Serial.print('.');
           }
           Serial.println(client.ip_addr[3]);
           // other code
         }

Completely untested. Good luck.


message:
Can this Motor shield support other arduino functions?

http://www.flipkart.com/grab-em-l293d-motor-driver-arduino-shield/p/itmehvzzpzj4wyby?pid=ETYEHVZZFFHRFMFG

I want to ask whether this shield will allow me to use the free pins of arduino for other functions?

body: Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.


message:
Arduino IDE unable to see serial connection on OS X El Capitan

For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

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

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

  [1]: https://i.stack.imgur.com/zKw7L.png
  [2]: https://i.stack.imgur.com/YQzfD.png

Thanks,
Shaun

body:
I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case `PD0` is Hardware Serial `RX` which is a receive pin.

Here's some relatively older code based around the same idea:
>Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239

Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.

    UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.

The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.

As I mentioned in my comment, if you have another pin available to you, use that instead.


message:
Program around this while loop not working as expected

int i=0;
    while(i == 0){
      if(digitalRead(saveSwitch) == HIGH){
        Serial.print("New coordinates saved \n");
        lat1 = gps.location.lat();
        Serial.print("Latitude");
        Serial.println(lat1);

        lng1 = gps.location.lng();
        Serial.print("Longitude");
        Serial.println(lng1);
        i = 1;
      }
    }
Why isn't leaving the while loop?

body: Instead of setting i=1, you could use a 'break' command to break out of the while loop.  That way you don't need 'i' at all, you can just do 'while(true)'


body:
> Why isn't leaving the while loop?

There's a good chance that the code *is*  leaving the `while` loop, repeatedly.  However, if the code that's shown is in (eg) the `loop()` function, `i` will be reset to 0 each time the function runs, which will cause the `while` loop to start again.

As noted in Dave X's comment, you can move `int i=0;` to a higher scope. Moving it to file scope, for example, will allow it to retain its value through repeated function calls.  For example, if the code shown is in `loop()`, you could put `int i=0;` just before `void loop() {`.

Note, having generically-named variables like `i` declared at a high level is a bad idea, a blunder, a programming faux pas.  An alternative is to leave its declaration within `loop()` but add the `static` keyword so that `i` is allocated only once, rather than being reallocated and reinitialized at each execution of `loop()`.  For example:  `static int i=0;`.


message:
Connector for I2C sensor

Im about to develop some home automation. It should be possible to connect new sensors to the main computer. Thats a Arduino.

What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Is it possible to send data wirelessly from a I2C sensor?

Regards

body:
> What can be used as a connector for the I2C sensors? It should be customer friendly. So something like RJ11 or USB. What can be used for that?

Almost anything you like. Whatever is easy to get hold of and use. You only need 4 wires, and they are all low voltage, so nothing too fancy is needed.

> Is it possible to send data wirelessly from a I2C sensor?

No. But you can connect the I2C sensor to an Arduino then use that with a wireless interface of some form to send the data wirelessly.

One thing for you to know though:

**I2C is not suitable for long distance communications. A few inches to a foot or so is about the limit. Anything longer and you will start running into communication problems. For longer distance communications you need to use a more reliable protocol.**


message:
Arduino Pro mini to CH340G Connection problem

I have worked with Arduino UNO but recently I bought a new Arduino Pro mini 5v 16M and a CH340G converter to work with. I have searched google to connect pins but I found examples that explains this way :
GND to GND
VCC to VCC
Converter RDX to Arduino Pro Mini TXO
Converter TDX to Arduino Pro Mini RXI
My problem is that my Arduino Pro Mini (328p) has pins TXD and RXD (not RXI , not TXO) or maybe I have no knowledge about TX,RX, IN and OUT.
Can someone please help me to connect these wires?

body:
try reversing the tx/rx lines, if the PRO Mini and serial adapter are chinese, you may want to try using your UNO as ISP programmer. See here for a hint/ex:
https://www.arduino.cc/en/Tutorial/ArduinoISP


body:
Generally, lines with names like TX, TXO, and TDX are for serial-data transmit, and  lines with names like RX, RXI, and RDX are for serial-data receive.

Connect transmit on the CH340G board to receive on the Pro Mini, and vice versa.

For typical serial-converter programmers (I don't know specifically about the CH340) you need to connect CTS (Clear to Send, if the programmer has it) to the pin next to BLK on the Pro Mini, and RTS to GRN (DTR).  The RTS-to-DTR (Request to Send, Data Terminal Ready) connection lets the programmer auto-reset the Pro Mini to start programming.

See [yourduino.com's ProMiniPinout.png](http://yourduino.com/docs/ProMiniPinout.png) diagram.