text:
Arduino Mousecontroller library doesn't work
I am working on a project with the Mousecontrol library. This causes me a lot of problems with loading the library. I imported the library but it gives me errors everytime. I think it is a mistake in the library folders but I can't seem to figure it out.
#include <MouseController.h>

// Initialize USB Controller
USBHost usb;

// Attach mouse controller to USB
MouseController mouse(usb);

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

void loop(){
  usb.Task();
}

void mouseMoved() {
  Serial.print("Move: ");
  Serial.print(mouse.getXChange());
  Serial.print(", ");
  Serial.println(mouse.getYChange());
}

I get this error:
Arduino: 1.6.0 (Mac OS X), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

In file included from /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/MouseController.h:22:0,
                 from Muis_Bevrijding.ino:1:
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*)':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:62: error: 'UOTGHS_HSTPIPCFG_PTYPE_INTRPT' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                              ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:93: error: 'UOTGHS_HSTPIPCFG_PTOKEN_IN' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:151: error: 'UOTGHS_HSTPIPCFG_PBK_1_BANK' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: there are no arguments to 'UHD_Pipe_Alloc' that depend on a template parameter, so a declaration of 'UHD_Pipe_Alloc' must be available [-fpermissive]
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual uint32_t HIDBoot<BOOT_PROTOCOL>::Release()':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: there are no arguments to 'UHD_Pipe_Free' that depend on a template parameter, so a declaration of 'UHD_Pipe_Free' must be available [-fpermissive]
  UHD_Pipe_Free(epInfo[epInterruptInIndex].hostPipeNum);
                                                      ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'uint32_t HIDBoot<BOOT_PROTOCOL>::Release() [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: 'UHD_Pipe_Free' was not declared in this scope
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*) [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: 'UHD_Pipe_Alloc' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^

Thanks a lot for your time!

Thanks for your reply. How can I install this? I work with an Arduino Leonardo.

USBHost
Compatible with Arduino Due only

source


text:
Arduino Yun restarts or stalls during operation
I have an Arduino Yun that I need to connect to a machine to detect whether the machine is working or is stopped.
The signal used as a flag for such behaviour is basically the presence or absence of current in one of the motors that work when the machine operates. The voltage going through the motor is 220VAC. So I figured I could use a standard AC to DC converter like the one used to charge the phones (since those converters usually take 100~240V at 50/60Hz and output 5V with 1A) and connect that to one of the digital ports in input mode. Then I would know if the machine is working or not if such pin is in HIGH state or LOW state respectively.
Well, this works up to certain point. For some reason, the YUN stalls or resets itself while the machine is operating. I've checked the voltage and even used a voltage regulator to make sure it doesn't exceed the 5V. I even connected the signal to an Analog pin and measured the input and it never read more than 4.9V. So I guess my question is, what might be causing this behaviour and how could I avoid it. I suspected it was a voltage/current spike but with the voltage regulator and the resistors I added before passing the signal to the Arduino I though the issue should be solved but the issue persists.
Attached is an image of the power adapters I'm using to both feed the arduino with current and convert the signal that goes to the pins to DC.
Basically, I know that the arduino stalls because it closes the telnet session I am using to monitor the values read by the pins and because the USB let goes off. Normally the arduino will have the USB and the ON leds on but once the issue happens it turns the USB led off and in some boards it turns on the WAN led on.
Interestingly enough, it seems that the issue happens when the machine is stopped (LOW voltage) and is preparing to start working.
Just as a note. I've tried different Arduino Yun boards and all have the same behaviour so I don't think it's a matter of the board being broken. Resetting the board allows it to continue reading the signal but eventually it stalls again

You use a wall-wart just to send to the arduino the information "the motor is powered" ? It reminds me of that game... "incredible machine", it was called.

Yes, that's what I'm using it for. Not sure it that's the best way to do it though.

It's a little convoluted, honestly. Here is a hint to make it more efficient.

That makes sense. I'll try that out. Thank you.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Simple memory chip for Arduino?
My basic question is: What is a good alternative to EEPROM chips for external memory on the Arduino Unor R3?
I know that there are EEPROM chips when one would like an external memory chip. It, in fact, seems like this is the standard choice. I am wondering if there are any other good ways to work with external memory. Are there, for example, memory chips that work a bis simpler? Like, a chip that doesn't require any specific libraries in the Arduino?
(I do not have extensive experience working with the Arduino.)

What is the problem with using a library? If you have some external memory, you have to communicate with this memory somehow. This already makes it "not simple". Note that you are not required to use a library. You could just write your own code that does the communication. But that would make it even less simple

@Gerben: No problem at all. I was just wondering.

There is no DRAM, SRAM nor flash interface in ATmega, so you can't extend your chip memory. You can only connect serial (SPI, I2C) or parallel memory (usind GPIO).
Neither SPI nor I2C require any specific libraries.
SPI is much simpler to program than I2C and much faster, but require more wires.
Instead of using rather slow EEPROM, you can try FRAM (non-volatile) or SRAM (volatile, but may be battery-sustained). They are usually available with the same interface as EEPROM, but don't suffer from limited number of erase cycles. FRAM can withstand ridiculous number of erasures, SRAM is virtually indestructible.

In what way is SPI easier to program than I2C?

No. There is no external memory interface on the ATmega328P, so all external memory requires some sort of library to use.

Personally I like the Amtel 24C256 chip/module. It is I2C enabled and the standard Wire library is all you need to talk to it. It is 256 bits or 32K 8 bit bytes in size. Data is sent and read in byte chunks. Addressing is at the bit level. It can run on 3.3V and 5V. Ebay has a bunch of suppliers for it. There's a number of good How-To's on line.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error
I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:
C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
        -i -d --port=COM4 -U false -e
        -w true
        -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
        -R bossac.exe: extra arguments found
    Try 'bossac.exe -h' or 'bossac.exe --help' for more information

I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).
This error occurred because of the true after the -w switch. To fix it I modified the package to tell the IDE not to use that switch.

Go to: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8 (where %USER_PROFILE% is your windows user directory, for me it was C:\Users\user) in Windows Explorer.
Make a copy of the platform.txt file (I called it platform_backup.txt).
Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:
tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R
This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:
tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R
Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.

On my Windows 10 system, the path to platform.txt contained AppData\Local instead of AppData\Roaming.
Full path: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8
Uploads fine to my Due now!

Tim's solution is also applicable to Version 1.6.9 of the SAM tools. I just installed it in my Arduino IDE V1.6.8 and had the same parameter problem as originally reported. Following Tim's solution fixed the problem right away. As this is clearly a configuration issue on the Arduino IDE side, it should happen on any supported Windows platform, mine was Windows 7.
The only difference I encountered was the path to the SAM tools directory. On my Enterprise version of Win7, the path was not in AppData\Roaming but in AppData\Local , so
%USER_PROFILE%\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\ for the full pathname.

There's a better option:
(For Windows)
1/ Download the latest IDE release.
2/ Uninstall the IDE completely.
3/ Reboot PC
4/ Go to %USER_PROFILE%\AppData\Local\Arduino15 and delete it (the entire folder). If the path doesn't match then find it in AppData folder, it's in there somewhere.
5/ Reinstall the IDE, problem fixed.

I tried this solution in linux Fedora, it worked fine, but the location of the file "platform.txt" was
/home/{user}/.arduinoxx/packages/arduino/hardware/sam
It is a hidden folder, so make it visible so you can handle it. No sudo access was necessary.

From the question, it is obvious the OP uses Windows, not Linux. Providing a linux-based answer may not really help.


text:
How to store a function in a constant?
I'm trying to do something to this affect:
const string first_color = strip.Color(0, 60, 0, 0);
With the intended outcome being that I could use first_color wherever I'd have used strip.Color(0, 60, 0, 0) before.

Are you asking how to save the return value of the function so that you can reuse it, or are you asking how to create a reference to the function so that you can call it by invoking first_color? There doesn't seem to be much point to calling it repeatedly with the same parameters, unless it has some side-effects that you're interested in.

It sounds like you might want a preprocessor macro.

You pretty much need a helper function to do that; a small local function that calls strip.Color() with the intended arguments and returns strip.Color()'s return value if there is any.
int first_color(void)
{
   return(strip.Color(0, 60, 0, 0));
}

(assuming strip.Color() returns an int) which you would call with:
value = first_color();

If strip.Color() is a void function, then delete the 'return(' and one ')', fix the definition of first color to be void instead of int, and of course, don't try to use any return value from first_color().

It sounds like you might want a preprocessor macro:
#define FIRST_COLOR strip.Color(0, 60, 0, 0)

And then later
FIRST_COLOR;

This is basically just text substitution at the initial stage of the compilation process.  It is somewhat conventional to make macros all caps, but not required.  You can also define function-like macros which take arguments.

authors: Иван Маркович


text:
AVR-STL Library
I have a project that I need to use a vector, I have tried to get several libraries to compile with out luck. The one that has gotten the closest is  Andy Brown's AVR-STL. I keep getting the error:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'

I am sure that this is a simple fix, I just have no idea how. If this library is no longer viable then can someone else recommend another one?
Here is the code I am trying to compile
#include "Arduino.h"
#include "iterator"
#include "vector"
#include "pnew.cpp"

std::vector<int> test;

void setup(void) {

    Serial.begin(57600);
}

void loop(void) {

    test.push_back(1);
    Serial.println("Pushed");
}

And the full output:
14:57:27 **** Incremental Build of configuration Release for project MegaTesting ****
"C:\\Eclipse\\eclipse\\arduinoPlugin\\tools\\make\\make" all
'Building file: ../.ino.cpp'
'Starting C++ compile'
"C:\Eclipse\eclipse\arduinoPlugin\tools\arduino\avr-gcc\4.8.1-arduino5/bin/avr-g++" -c -g -Os -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR     -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\cores\arduino" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\variants\mega" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility" -MMD -MP -MF".ino.cpp.d" -MT".ino.cpp.o" -D__IN_ECLIPSE__=1 -x c++ "../.ino.cpp"  -o  ".ino.cpp.o"   -Wall
cc1plus.exe: warning: C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility: not a directory [enabled by default]
In file included from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/stl_iterator_base.h:38:0,
                 from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/iterator:40,
                 from ../.ino.cpp:8:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _TrivialIterator_concept_specification<_TrivialIterator>::_TrivialIterator_requirement_violation(_TrivialIterator)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:572:16: warning: typedef '__T' locally defined but not used [-Wunused-local-typedefs]
     value_type __T;
                ^
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _Allocator_concept_specification<_Alloc>::_Allocator_requirement_violation(_Alloc)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:799:39: warning: typedef '_Tp' locally defined but not used [-Wunused-local-typedefs]
   typedef typename _Alloc::value_type _Tp;
                                       ^
In file included from ../MegaTesting.ino:3:0,
                 from ../.ino.cpp:14:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp: In function 'void* operator new(size_t, void*)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'
 void* operator new(size_t size_,void *ptr_){
       ^
In file included from ../.ino.cpp:10:0:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: 'void* operator new(size_t, void*)' previously defined here
 void* operator new(size_t size_,void *ptr_){
       ^
subdir.mk:24: recipe for target '.ino.cpp.o' failed
make: *** [.ino.cpp.o] Error 1

14:57:28 Build Finished (took 600ms)

I've got the "Andy Browns method" of standard library working. But I believe I didn't have the same error as you.
A redefinition would mean that something has already been defined, I think you can choose to not include it at some point, since it's already defined.

It looks like new is redefined. I see that you include cpp file, that contains implementation - this is rather unfortunate design, but that's how it is done.
Anyway, it seems that this file is already being compiled elsewhere. Have you tried to remove this include? What happens if you remove it?
Apart from that problem, you must be aware that dynamic memory management in such small system yelds risk of memory fragmentation that eventually leads to failed allocations.

That's the thing, I have tried excluding the pnew.cpp and believe it or not I get a Undefined message, even if I include Arduino.h before any of this library.

Are you able to allocate anything using new? It should be available since 1.0.5 or something. Try int *i = new int[5];.

Thats the weird thing about this, I do have the 'new' functionality at runtime thats why I am thinking that it has to do with either an include or header because new is available without using this lib


text:
How did I burn out this ESP8266 unit?
ESP8266 -> FTDI -> USB Mac
I followed the wiring on this page: http://williamdurand.fr/2015/03/17/playing-with-a-esp8266-wifi-module/

I was communicating with it via Serial at 115200.  I issued a AT+UART_DEF=9600,8,1,0,0 and a few seconds later I looked over and it was smoking.

I bought 2 of these.  The previous one I had wired to an Arduino Nano running through a logic level converter.  That one only returns Exception (28) over and over again after issuing that same command.
On both units AT+GMR returned:
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0

Are these units too hard to use? What did I do to burn it out?
[UPDATE]
Answer given was that I fed it 5v instead of 3.3v. Obvious. I didn't think I did but I checked the output of the FTDI and sure enough it was 5.1v.  So why does the output on it say 3V3 ?  I thought that meant that it was 3.3v...

Should have checked it first.

You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.

I'm checkmarking you cause obviously you are correct.  But I hope to also get an answer to why 3V3 doesn't mean 3.3V?  Why not label it as VCC or +5V instead of 3V3 if it's not 3 volts?

The easy answer is that you have a defective FTDI device. It should be 3.3V, but clearly it is not.

Also, the FTDI device likely does not supply enough current on the 3.3V rail to run the ESP8266 module to its full potential regardless; you should get a separate 3.3V regulator and connect it to that.

I bought these but they say 150ma on the back.. http://www.amazon.com/XCSOURCE-Converter-Bi-Directional-Module-TE291/dp/B0148BLZGE?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o02_s00

Those are level shifters, not voltage regulators.

It sort of defeats the purpose of having a small wifi unit if you need a separate power supply or regulator for each of them.  In my project I already ahve 12v going to my nano and rfid reader, a 5v regulator going to a relay and some PIR sensors. And now I need another 3.3v regulator going to this. These power requirements are annoying.

I was only using the FTDI to test and set up the wifi module. In my project it will be wired to the nano. Is there a small regulator that can take 12v and give me 5v and 3.3v out at the same time.

A few, but they won't really save you any money over a separate 3.3V LDO linear regulator. Also, consider running the Nano on 3.3V as well (although there are a few caveats about that, which you can find by searching the site).

What about this: http://www.amazon.com/Qunqi-MP1584EN-Step-Down-Adjustable-Converter/dp/B014Y3OT6Y?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_sfl_title_1&smid=A12MRQC2NA7LMA

Those will work, but keep in mind that a AMS1117-3.3 or equivalent (for dropping the 5V to 3.3V) costs a very small fraction of one of those modules.

Also I found the answer and posted it here as well.  Thanks!

I checkmarked Ignacio's answer because it was correct.  But I wanted to leave an answer also as to HOW I supplied 5v when I thought I was supplying 3.3v.  Maybe it will help someone else.

The backside of this FTDI module has a jumper to select 3.3 or 5v and the default is set to 5v.  I needed to cut the default trace line connecting to 5v and solder my own jumper to switch it to 3.3v.  I should have double checked the voltage before powering it up.  New ESP01's on order.


text:
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—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 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;
}

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.


text:
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 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

You could try the hardware serial?
Or pull the reset pin low and then talk to the ESP directly through USB.
Might check if those work.

@Paul: the nano has only one set of hardware serial ports. So if I use those I cannot send data to the Arduino Serial Monitor anymore, making it hard to understand what is happening... Guess I'll need to go for firmware upgrade.

well you could make use of the software serialport for debugging? You'll need a "usb-serial/ttl" cable though.

http://stackoverflow.com/questions/34248581/set-baud-rate-to-esp8266-at-9600 This will answer your question.

Seems that setting the baud rate with AT+IPR=9600 also bricks an ESP01. I tried several suggestions in this thread to recover it. The solution in the link Marco Andre Silva supplied worked for me.

So you could "unbrick" your module?

This video, 1. How to flash ESP01 with latest AT command firmware, helped me re-flash the firmware to my ESP01.

Has anyone worked out why that command appears to brick the ESP?  That seems really weird

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.

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 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

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.

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.

Power cycling the ESP between each file was the key thing to me too - other sites combine all the files into a single esptool.py command, but that did not work for me. Only after breaking it into individual commands, one per file, and cycling between each one, was I finally able to restore the AT firmware. Thanks for the hint!

Also, I tried using the esptool.py that comes with the ESP32 IDF (v2.1-beta1) and that one works successfully with a single command to flash all files on my ESP8266 (which it also supports) - so only one power cycle + GPIO0-GND required.

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

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

I don't think this is a power supply issue. I have an external power supply which is more than capable. I tried without before and then the Arduino kept restarting... I found on a forum that that was due to power supply issues. So now I'm fine there. I really think the issue is that the SoftSerial cannot cope with the 115k baudrate.

esp is really picky, add a small capacitor between vcc and ground. I also power mine from external power source and was experiencing restarts.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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 will likely resolve my problem.  Thoughts?

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 has a bit more info on the modes possible.

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.


text:
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!

You need to determine how much current is required too, it's not just the voltage that matters. Can you show a schematic of how things are currently connected?

I suggest going back to read the basics about voltage and current, especially the part about parallel circuits. You seem to be confused about quite a few things. That said, without any sort of data about the servos or the circuit connections I doubt anybody will give an answer that you're happy with

Don't power the servos from the Arduino.  Power them separately, and only connect the ground and control signal lines to the Arduino.

I read that each takes up 2.2 V each so that means the Arduino can only handle about 2 , if using 5V - that doesn't mean you can power two 2.2V servos from 5V. It doesn't work that way. Can you edit your question and include a link to the servos and preferably the datasheet?

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.


text:
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?

Well, as far as I know every compiler is smart enough to understand that the const int field should not be allocated into memory, so I THINK both are the same... You can try to compile both versions and see if the size and the memory is the same or not..

(Duplicate of this.)
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.
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.

Thanks, I saw the link that you posted but what that did not touch on was the usage of PROGMEM and what should be stored where to utilize memory as efficiently as possible. #define's are stored in global space but there is no way I know of to tell where to put that memory when "used"

@AndyBraham, the link did not touch on PROGMEM because it is not related to #define.  UPDATE section added above to explain the difference between preprocessing (string substitution) and compiling (variables, storage and PROGMEM).

Thanks a bunch for trying to help, I guess I was just not clear on what I was trying to get at. I updated my question hopefully you can shed a little light....

@AndyBraham, UPDATE 2 added.  Basically, constants rarely use storage space.  PROGMEM only applies to things that actually use storage.

Awesome, now you hit on what I was trying to get at. Now one more thing. While researching this topic there was some mention about LCD projects and storing the Strings that are displayed in a structure or array like you mentioned in your "Update 2". Do they suggest this because the String Arrays are large and when used they take up much more memory than other types? Or is this one of those things that "Work" but there are better ways? I am trying to find out what the best approach is. As you know the internet is full of obsolete information.

@AndyBraham, Be careful, when you use the capitalized String, it usually refers to the Arduino class, which you should never use. I will assume you are referring to "C strings", aka char arrays.  Here is a good example of strings in PROGMEM. As explained above, const vars, including char[], will be both in RAM and FLASH if storage is required.  Since most string ops use the starting address of the string, they require storage. PROGMEM saves RAM, but the same speed penalty applies. No Big Deal


text:
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

Use a precision oscillator (possibly temperature compensated), then measure its time. You can find even 5ppm oscillators, which means that you can have an accuracy of one millisecond for times less than 200 seconds..

Some RTC can also output a frequency. E.g. the DS3231 can output a 1Hz, 1.024kHz, 4.096kHz, 8.192kHz square wave. This frequency is quite precise, as it's temperature compensated. You could use it, and count the number of pulses between the two touches. Might I ask what you are using to detect a touch? I hope you are not using CapSense for this.

Theres a touchpad, that when someone touch theres a contact similar to a button, i just read LOW or HIGH on arduino to know if someone touchs it. I'll read about count the pulses. thanks

For a ms in 8 hours, I get ~ 1 part in 30 million: (8hrs * 3600 sec/hr * 1000 ms/sec = 28,800,00 ms).

Yes! 28,800,800! But i have to multiply over the 20/1.000.000.000 in this case from the crystal right? to know the precision? because i dont found any 1/30ppm crystal, neither 0.33ppm. I'm probably messing up everything, first time working with this math.

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.

Do you know or have any material for implemente the crystal on arduino?  i'll also look more for it. thanks

Here's a starting point: http://www.google.com?q=Temperature+Compensated+Crystal+Oscillator+16+mhz

From what I read, Eduardo isn't using the internal oscillator. He says he's using an Arduino Uno, that already has an external crystal.

You are right, my bad. I have corrected my answer. The 16 MHz external oscillator of the Uno is probably miles ahead of the internal 8Mhz oscillator in the Atmega. Still, it's a relatively cheap resonator. I reckon that replacing it with a high quality oscillator can increase the precision by many orders of magnitude without breaking the bank. See this thread for a comparison: http://forum.arduino.cc/index.php?topic=60662.0

I'm even considering get an expensive (until 30$ maybe) crystal to get a better precision. There a good "brand" or any that you or anybody vouch for?


text:
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?

You run multiple checks. For example:
if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
    // do something
}


text:
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?

Err, don't we have an actuators tag?

This constitutes animal abuse. You should not have a cat if this is how you are thinking of treating him.

To anyone downvoting: Next time you laugh at Blender Defender, please remind of your hypocrisy. I'm not aiming at torture, just negative feedback.

That's what the CIA said; it wasn't torture, it was advanced interrogation techniques. I don't know what blender defender is. If what you are doing induces discomfort in the cat, it's animal abuse. You should also try to improve your English.

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? ;-)


text:
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
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?

I don't think it is impossible, USB is some kind serial bus with specific protocols, i.e. device tagging splitting devices to specific time ranges (some similar protocols like one wire). I think the only limitation is speed, therefore syncing all the USB specific commands and data is the thing that causes trouble,

@GeneralChaos You're right, it's not "impossble" - but it is highly impractical. There is a software implementation of a USB device (VUSB) which doesn't need any special hardware. It's iffy at best and barely works at the best of times. There is no reason why you couldn't write a host equivalent - however, it could never work at anything more than the 1.5MHz of USB 1.0 "Low Speed", so could never talk to anything other than a simple keyboard or mouse.  Things like ethernet or webcams are completely impossible without Host or OTG hardware, which the Due has built in to the main chip.

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.

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.


text:
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?

In theory a 3.3v ATmega could run at 12 MHz in which case it would be 3/4 as fast.  In practice people sometimes run at 16 MHz, which is out of spec for that voltage but sometimes works.  But yes, 8 MHz or half speed is the simple, safe choice.

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.


text:
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

And your question is?   The Stack Exchange sites require stating a clear, answerable problem

Please read How do I ask a good question? - you have stated what you want. Now you need to describe what is happening, compared to what you want to have happen.

I think you are mixing up your rightVal and rightIn, and your leftVal and leftIn.
rightVal = digitalRead(rightIn);
....
if (rightIn == HIGH) {

I'm just testing it with an led. In theory, would the code work?

Thanks, now that that's fixed could it work?

Probably, yes - as long as your circuit is up to it

Your HIGH/LOW signals will have to switch a motor's pole between power and ground - so you need more than "a transistor". You will need at least two each side in a H-bridge arrangement.

my motor only needs 3.3  volts, is 2 transistors per side really necessary?

Well, yes. How else are you going to switch 4 possible connections?


text:
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);
}

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


text:
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?

You need to escape your quotes:
Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");

Man that was fast! Thanks Majenko it worked perfectly!


text:
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?

You can send a pre-compiled binary yes.
But are you sure you don't mean assembly or HEX?
It would be a shame to only use the 0 & 1 of your keyboard for programming.
And why would you like to achieve this?

Voting to close as it is entirely unclear what the goal here is.  Binary communication is of course possible, but what does it mean to "programme" ?   To author something?  To load the flash??  To communicate with a bootloader, and if so which one???

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.

You should rephrase your answer. specifically everything after the 1st sentence. Bytes sent via the serial port are implicitly binary; the interpretation on the receiver's end is a different thing entirely and has nothing to do with bandwidth. The serial monitor displays the ASCII character equivalent to each byte received if it can, else you see gibberish for bytes that don't fall within the printable range, barring a few. Also, I dont think the OP is talking about serial communication but rather how code is burned into the ATmega chip over USB.

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).


text:
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);

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);
}


text:
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

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".

oh, look at that. Didn't even realize that library returned a long. Looking at examples for library shows it definitely does. Will try this fix.


text:
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?

You could use a timer interrupt and build your own scheduler, like any preemptive multitasking OS on a single core machine (though resources will be tight).  But it is probably better to do your long tasks in pieces, perhaps as state machines that advance one state each time they are called.  If the thing that needs to happen in the meantime is simple, perhaps you could just do that in an interrupt on the timer or some relevant occurence (pin change, serial rx, etc)

This article gives a great example of multitasking by using FreeRTOS.
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
  }
}

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.

I am a little confused in the readme it states "On the one hand, this means that the only way a task can “yield” the CPU is by returning to the caller, and it is thus inadvisable to delay() or do long waits inside a task." does this library have a function to give control to another process? Or would you have to put a return and let the program flow back to that point again?

I am by no means an expert on threads, but I think the writer might have confused threads and processes. As for your second question, I think you'd switch between threads by using SetInterval.


text:
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?

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.


text:
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)

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.

What do these pins do?

I bought this one

I'v had the same question and searched for a manual... And where is the manual?

For the Arduino clone? Should be the same as standard Arduinos.

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 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.

Does IOREF sets the voltage on I/O pins?

IOREF tells a shield what voltage the main board runs at.

It's all in the manual. I seriously suggest you read it. At the moment you're just making a fool of yourself asking such basic questions.

Would that make you happy?

If you were happy?


text:
3 square wave pulse by 120° phase shift and 3 inverted of each by Arduino
I want to make a three phase inverter (DC to AC) bridge type using Arduino. For that I want to generate three square wave each is 120° phase shifted and other three waves of main three wave forms inverted for opposite switch.
Can anyone please help me out? I am new to programing in Arduino.
Code:

void setup() {
  pinMode( 9 , OUTPUT );
  pinMode( 10 , OUTPUT );

  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
  TCCR1B = _BV( WGM13) | _BV( WGM12);
  OCR1A = 0;
}
#define PRESCALER 1
#define PRESCALER_BITS 0x01
#define CLK 16000000UL

int setWaveforms( unsigned long freq , int shift ) {
  unsigned long clocks_per_toggle = (CLK / freq) / 2;
  ICR1 = clocks_per_toggle;
  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL;
  OCR1B= offset_clocks;
  TCCR1B |= _BV( CS10 );
}

void loop() {
  setWaveforms( 50000 , 120 );
  delay(1000);
  setWaveforms( 50000 , 120 );
  delay(1000);
  setWaveforms( 50000 , 120 );
  delay(1000);
}

I had get 2 waves only but I want to get 6. I am new to Stack Exchange.

This question doesn't cut it here, and I doubt it will on Arduino.SE. You need to put in your own research effort and show what you've tried, before we can (and will) help you. Otherwise we're just a free developer for hire.

ATTiny861. As you've shown no effort, that's all the effort I'll show.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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?

And the wiring/circuit?

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.


text:
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 ?

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.


text:
How to 'label' module using electric techniques
I am in a project where it makes set of 'modules(set of separate circuits that will work as a sensor when connected to the board' that would be connected to Arduino Mega.
Currently, I'm planning to connect 'modules' with the Mega board using RJ-45(also known as LAN cable) cables.
At first, using voltage divider circuit, I tried to identify these 'modules' by attaching a resistor to it, so that if the board sends 5V to the 'module', it gets the resistance of the resistor inside the module.
But, as soon as I tested, this way seemed a bit unstable, because the measured resistance of the resistor kept changing.
Now, is there any other way to 'label' the module? I'm a beginner in this thing, so I'll appreciate any help that is provided.
Thanks in advance.
Ps. the voltage divider circuit that I used can be found in here:
Ps2. the resistor in the module does not mean the total resistance of the circuit in the module. It's separate.

What kind of sensors / communication protocol / electrical signalling are you using?

each modules have sensors like photo-interrupter in it, and through the RJ-45, are provided VCC,GND, 2 digital inputs, 2 analog inputs, a PWM, and 1 pin is left for the identification.

That starts getting kind of tricky then...  Let me put my thinking cap on for a while...

the voltage divider circuit that I used can be found in here:; no link present. Raspberry hats use I2C EEPROM to identify the 'HAT'/shield. I've seen people using a DS18S20 temperature sensor, as those also include a 64-bit unique identifier. Though both of these will a relatively expensive options. It could be the long lengths of cable that mess with the resistance. So maybe you could add a constant current source on the modules; then add a 'terminating' resistor at the Arduino, and measure the voltage across it.

Personally I would have made the modules purely digital. Add a small microcontroller to each one to interact directly with the sensor in the module, and then use a digital protocol (RS-485, RS-422, LVDS, etc) to communicate between the module and the main board. That way the protocol can include a "tell me what you are" request. Cable length then also doesn't affect analog readings.

It also means the sensor modules themselves then contain the code needed to interact with the sensor. The main board doesn't need to know how to do that - only how to request data from it, or send settings to it.

You still haven't provided the divider circuit!!!

@Gerben Gosh... my eyes are dim lately... here's the link: http://www.circuitbasics.com/arduino-ohm-meter/

What kind of values are you using? You might want to try adding a small capacitor near the analog pin on the arduino to stabilize the voltage. PS maybe your eyes need an op-amp (optical amplifier) q-;

@Gerben Pardon me, I didn't get the 'What kind of values are you using?'...

Resistor values in ohms

If you are unable / unwilling to change your interface into a purely digital system whereby a small microcontroller in the sensor module interfaces the sensor with a communication bus, the best method is probably to include a small 1-wire EEPROM with each module.
An ideal one would be the DS2431 which provides 1024 bits (128 bytes) of EEPROM storage using just 1 wire to both communicate and provide power.
Programming in a unique identifier for the module would be a simple enough task, and that unique ID can then be used to work out what the module is.
The DS2431 is pretty cheap too, available at prices around  $1.50 and below (much less for bulk and surface mount).
You can also get bigger versions for storing more data should you want to.

humm... if the digital storage is the only answer... then I shall follow. Thanks so much!


text:
AVR dude not working in javaFX
I am working on an Project in which i have to upload hex file from java to arduino uno i wrote the code in java its working but only when i call it in main method. But when i call it when button is pressed it doesn't upload the hex.
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
    Parent root = loader.load();
    MainController controller = (MainController) loader.getController();
    Scene scene = new Scene(root,485,355);
    primaryStage.setScene(scene);
    primaryStage.setTitle("Hello World!");
    primaryStage.show();

    controller.Init(primaryStage);
    controller.searchForPorts();
    controller.disableControls();
}

public static void main(String[] args) {
     Avr avr = new Avr();
    avr.start();
    launch(args);
}

}
Working fine like this but when called on button pressed event doesn't work.
public class Avr extends Thread {
String avrdude;
String avrconf;
String hex ;

MainController main;
void setup() throws IOException{
    Path avrpath = Paths.get("avrdude.exe");
    Path hexpath = Paths.get("sketch_may13b.ino.hex");
    Path avrconfpath = Paths.get("avrdude.conf");
    Path realavrpath = avrpath.toRealPath(LinkOption.NOFOLLOW_LINKS);
    Path realhexpath = hexpath.toAbsolutePath();
    Path realavrconfpath = avrconfpath.toAbsolutePath();

    avrdude = realavrpath.toString();
    avrconf = realavrconfpath.toString();
    hex  = realhexpath.toString();

    avrdude = avrdude.replace("\\","\\\\");
    avrconf = avrconf.replace("\\","\\\\");
    hex = hex.replace("\\","\\\\");
    main = new MainController();

    String port ="COM3";
        runCommand(new String[]{avrdude, "-C"+avrconf,"-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hex+":i"});

  }
  void runCommand(String[] cmd){

try {
Runtime.getRuntime().exec(cmd);
}
        catch (IOException e) {
      System.out.println("something went wrong: \n");
      e.printStackTrace();
  }

  }

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        setup();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}


text:
What happens if I draw too much current from ATMEGA IO pin?
I revisited an older device that I made and discovered, that I had an 8 Ohm speaker connected directly to ground and an IO pin of an Atmega328P. According to my calculation that means that the pin would have to source 625 mA, which is way above the 40 mA that any single port should be able to source and even above the 200 mA that the Vcc and GND support. Yet it somehow worked and the chip seems to be working just fine. The application uses a duty cycle of 50%, so in the best case it would use maybe 312.5 mA, which is a little better but still way above the ratings.
So my question is, what happens if the output pin is asked to source more than it's rating?
I've seen chips that just release their magic smoke while others just can't keep up with supplying that kind of voltage, so only the voltage drops without any other problems. How does the Atmega328P handle this?
The Atmega clearly didn't burn through, but what other kind of damage should I expect?

It is not good, but the effective internal impedance means that when facing such a load the voltage of the pin will not be at the supply rail and so the current will be less than you calculated.

Your math is off. You would only draw 150mA.

@IgnacioVazquez-Abrams: How so? According to Ohm's Law 5V / 8Ohm = 625 mA. Where is my calculation off?

@ChrisStratton: Sounds interesting. Do you have more details on that?

You forgot to account for the 25ohm output impedance of the chip.

@IgnacioVazquez-Abrams Thanks, that is a good point!

There's a few crude calculations you can do using some numbers from the datasheet.
This graph is in the datasheet:

It shows the voltage dropped by the high-side MOSFET driver in the IO pin for different amounts of current draw. From that we can get its resistance R(DSON).
For instance at 10mA, at 25C, the output voltage would be 4.75V. That's a 0.25V drop from the 5V supply voltage. So we can calculate the resistance as:

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

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

25Ω + 8Ω = 33Ω

Now we can calculate the current through that circuit:

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

That is, of course, way above what the IO pin can actually supply (or so the datasheet says).
So what happens? Well, two things, basically:

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

The actual voltage will be, of course, V=I×R = 0.152A × 25Ω = 3.8V droped, so 5 - 3.8 = 1.2V
What is more critical, though, is the heat.  152mA through a 25Ω resistance generates P=I²R = 0.152 × 0.152 × 25 = 0.5776W. That's quite a lot. Enough to melt the internal circuits in the chip and release the Magic Smoke™.
Running at 50% duty cycle, though, makes a difference. That's 50% of the power, which makes a big difference to the heat.
What would the actual allowable heat be? Well, at 40mA, with 25Ω, that is 0.04 × 0.04 × 25 = 0.04W.
So you're generating more than 14 times the amount of heat you are allowed to. Even at 50% duty cycle, that's over 7x the limit.
Will it kill the chip? Well, possibly, possibly not. It depends how rugged the chip is and how well it can withstand the heat. Short bursts may be OK since the heat doesn't build up enough to melt things. Extended use, though, will make it get too hot, and things will go pop.

Your duty cycle analysis is incorrect.  At moderate PWM rates, when it is on it is still running at full power, however it is running at full power only half the time.  Hence half the heat, not a quarter.

@ChrisStratton It's actually not as simple as either situation - you have to take thermal conductivity, dissipation, etc into account. Instantaneous power (which would be half) is not the same as dissipated heat power, since that is subject to time and the aforementioned parameters. Either way, though, it's still exceeding the limits by a considerable margin.

Wow! Thanks for that amazing answer! That was much more than I expected! So basically, I am just really lucky that this is still working. I will add some resistance before using it the next time.

It is indeed not simple, but your posting and also followup are both substantially wrong on the basic points.  It is time average power, not instantaneous power which would be half.  Instantaneous power is full once the coil inductance is overcome.

@Dakkaron - while far outside the specs, the reality is that shorting a pin to ground does not usually damage a device such as this, at least in the short term.  Of course when you go outside the specs, there are no guarantees, and even apparent functionality no longer implies complete reliability.

That is very true. I am getting my terminology mixed up somewhat. Feel free to edit the answer and improve it.

@ChrisStratton I have worked out where I was going wrong - for some reason I was confusing output power with mosfet dissipated power. Yes, 50% current = 50% power dissipation from the mosfet because the voltage drop across the mosfet is determined by the peak current not the average current, so the peak voltage drop and the average current give the same result as the average power.