text:
Connecting a motor to Arduino UNO Play breadboard
I am new to Arduino and have a small query. I am building a simple system that switches on a motor and switches it off after some time and repeats this in a loop.
The Arduino that I am using is a “DIY UNO Play Breadboard -ATMEGA328P with FT232 Breakout Board” (Rs. 825, or $12.38USD, from Mangalore).  The Arduino board is similar in size to a Nano but without USB.  The FT232 board has a USB B port on one end and serial pins on the other.

My query is whether I should connect the positive end of battery supply to the motor and then connect in series using a motor controller circuit to port 7 and connect the negative terminal to the gnd port.
Or do I need a separate voltage source for my Arduino, because this Arduino has no built in USB ports.
This is my code to switch on and switch off the motor:
int motorPin = 7;
   pinmode(motorPin,OUTPUT);
   digitalWrite(motorPin,HIGH); //turn motor on
   delay(500); //wait
   digitalWrite(motorPin,LOW); //turn motor off
   delay(500); //wait

Can you please specify operating voltage/current rating of your motor. and some info related to your motor controller circuit.

My motor is a 5V motor and this is the circuit that I want to build: http://www.instructables.com/files/orig/F5O/D77S/I0VOVRVX/F5OD77SI0VOVRVX.jpg

Using same Voltage supply to power Arduino Board and motor simultaneously is usually not a good practice.
So, what you can do is use separate batteries to power Arduino and motor as shown in image below

However you can also power arduino and motor from single power supply, but in this case you should first think of current ratting of your battery and current consumption of your Arduino (normally 500mA) and motor. As shown below,

Hope it help. Any question Comment below.

thanks for answering. Just another doubt, why can't I connect the positive terminal of the battery to the Vin Port.

oh, really sorry, did a mistake there. edited. you are right. you actually have to connect to vin which in voltage input port whereas 5V is a voltage output port.

Last doubt. Do I need to connect the negative terminal in the first diagram of the battery connected to motor to the gnd pin of the Arduino or will it work without the connection?

you have to. It wont work without that. What we are doing there is called common ground. All GNDs in your circuit must be connected.

You can use the same power supply for both if it can source enough current for both; USB ports usually can not. But what you must not do is try to supply motor current through the Arduino, from any power supply. You need the Arduino to control a transistor switch which manages the motor current.


text:
I2C Master-Slave Arduino system to control array of steppers
trying to make a system where one master Arduino makes moving 9 steppers 28BYJ-48 by 3 stepper on each slave arduino.
While all the parts on their way to me, wonder to check with professionals.
Maybe I've missed something?
Any suggestions and tips are welcome.
Thank you.

I think your schematic might be wrong there. Only one MEGA is connected to a positive side of a battery.
The MEGA can only run on 7V to 12V. BUT PLEASE DO NOT apply the voltage to the 3V3 or 5V pin.
Microcontroller ATmega1280
Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limits)  6-20V

And also, I would only put in another MEGA when you don't have enough I/O pins.
Digital I/O Pins    54 (of which 15 provide PWM output)

In theory you could use 13 steppers on one MEGA. Try slowly scaling up.
You don't need PWM for steppers, maybe you're confused with servo's?
And why not use one of the stepper-driving MEGA's as the master? (In the first picture, slave 1 isn't even connected to the SDA/SCL lines of the I2C bus.

I don't quite understand the problem. A
 arduino mega would have no problem controlling 9 of these steppers alone. If you are asking about i2c protocol please be more specific about what you need help with.

How much does she more can handle? Can you point me, how it possible, because as my newbie brain think when one stepper requires 4 PWM outputs and mega has only 15, I can drive only 3. Thank you for your help!

These steppers doesn't require any timers really, you can control them with 4 outputs each and control each stepper in code.

Well, 4 pwm outputs, 15 ppm on each arduino.

Why would you need PWM? It's not like doing micro-stepping on a 28BYJ-48 is useful?

If you were to tell us what this system of yours is going to do, we might be of more help.

It is for simultaneously moving steppers, like in kinetic statues. With accelerated moves and so on.

Well first off, if two or more steppers need to go simultaneously just connect them in parallell. These stepper doesent require any PWM or timers really, in normal program loop you need to delay stepping them or else it will stall them(run faster than they can handle), so maybe by using a non-blocking code you could easily run 13 of theese steppers of one mega. or basically any amount of theese steppers you want using shift registers.

@Hans Neve Sorry for my idiotic questions, but what is non-blocking code? loop+setup? What if I want to drive steppers simultaneously but with different speed and direction?

@lenyapugachev : 1) the "non-blocking" concept is something that most arduino developer will experience early in her developer career. If you already have NOT "hit" related problems, than How and Why to avoid delay() is the place where to start :-)   2) no ;  3) unfortunately I have NO experience with stepper-motors but.... my "feeling" is that you need a sort of multitasking and, as such, you definitely need to investigate point 1), that is mandatory in such a scenario :-)

ok, if I get it, yes I will avoid delay(), planning to use something like http://www.airspayce.com/mikem/arduino/AccelStepper/

source: Stack Exchange

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

sort: votes


text:
Using millis() and micros() inside an interrupt routine
The documentation for attachInterrupt() says:

... millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. ...

How does micros() differ from millis() (except of course for their precision)? Does the above warning mean that using micros() inside an interrupt routine is always a bad idea?
Context - I want to measure low pulse occupancy, so I need to trigger my routine when my input signal changes and record the current time.

The other answers are very good, but I want to elaborate on how micros() works. It always reads the current hardware timer (possibly TCNT0) which is constantly being updated by the hardware (in fact, every 4 µs because of the prescaler of 64). It then adds in the Timer 0 overflow count, which is updated by a timer overflow interrupt (multiplied by 256).
Thus, even inside an ISR, you can rely on micros() updating. However if you wait too long then you miss the overflow update, and then the result returned will go down (i.e you will get 253, 254, 255, 0, 1, 2, 3 etc.)
This is micros() - slightly simplified to remove defines for other processors:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
    t = TCNT0;
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

The code above allows for the overflow (it checks the TOV0 bit) so it can cope with the overflow while interrupts are off but only once - there is no provision for handling two overflows.

TLDR;

Don't do delays inside an ISR
If you must do them, you can time then with micros() but not millis(). Also delayMicroseconds() is a possibility.
Don't delay more than 500 µs or so, or you'll miss a timer overflow.
Even short delays may cause you to you miss incoming serial data (at 115200 baud you will get a new character every 87 µs).

Not able to understand the statement given below that is used in micros(). Could you please elaborate? Since ISR is written, TOV0 flag will be cleared as soon as ISR is entered and hence below condition may not become true!. if ((TIFR0 & _BV(TOV0)) && (t < 255)) m++;

micros() isn't an ISR. It is a normal function. The TOV0 flag lets you test the hardware to see if the timer overflow has happened (but not been processed yet).

Since the test is done with interrupts off you know the flag will not change during the test.

So you mean to say after cli() inside micros() function, if any overflow occurs, that needs to be checked? That make sense. Otherwise even though micros is not a function, TIMER0_OVF_vect ISR will clear TOV0 in TIFR0 is what my doubt was.

Also why TCNT0 is compared against 255 to see if it is less than 255? After cli() if TCNT0 reach 255 what will happen?

Even with interrupts off the hardware timers will continue to count. I think the test for < 255 is because of a possible situation where the overflow flag has been set but the timer is still at 255 (so it hasn't quite overflowed yet). The next one up from 255 would be 0.

TIMER0_OVF_vect ISR will clear TOV0 in TIFR0 is what my doubt was - the timer might have overflowed and the ISR has been scheduled but not yet run.

In particular after the line t = TCNT0; the timer might overflow just now so we need to test the overflow flag, and it t is less than 255, and the overflow flag is set, then it probably overflowed between those two instructions.

It is not wrong to use millis() or micros() within an interrupt routine.
It is wrong to use them incorrectly.
The main thing here is that while you are in an interrupt routine "the clock isn't ticking".  millis() and micros() won't change (well, micros() will initially, but once it goes past that magic millisecond point where a millisecond tick is required it all falls apart.)
So you can certainly call on millis() or micros() to find out the current time within your ISR, but don't expect that time to change.
It is that lack of change in the time that is being warned about in the quote you provide.  delay() relies on millis() changing to know how much time has passed. Since it doesn't change delay() can never finish.
So essentially millis() and micros() will tell you the time when your ISR was called no matter when in your ISR you use them.

No, micros() updates. It always reads the hardware timer register.

The quoted phrase is not a warning, it is merely a statement about how things work.
There's nothing intrinsically wrong with using millis() or micros() within a properly-written interrupt routine.
On the other hand, doing anything at all within an improperly-written interrupt routine is by definition wrong.
An interrupt routine that takes more than a few microseconds to do its job is, in all likelihood, improperly written.
In short:  A properly-written interrupt routine will not cause or encounter issues with millis() or micros().
Edit:  Regarding “why micros() "starts behaving erratically"”, as explained in an “examination of the Arduino micros function ” webpage,  micros() code on an ordinary Uno is functionally equivalent to
unsigned long micros() {
  return((timer0_overflow_count << 8) + TCNT0)*(64/16);
}

This returns a four-byte unsigned long comprised of the three lowest bytes from timer0_overflow_count and one byte from the timer-0 count register.
The timer0_overflow_count is incremented about once per millisecond by the TIMER0_OVF_vect interrupt handler, as explained in an examination of the arduino millis function  webpage.
Before an interrupt handler begins, AVR hardware disables interrupts.  If (for example) an interrupt handler were to run for five milliseconds with interrupts still disabled, at least four timer 0 overflows would be missed.  [Interrupts written in C code in the Arduino system are not reentrant (capable of correctly handling multiple overlapping executions within the same handler) but one could write a reentrant assembly language handler that reenables interrupts before it begins a time-consuming process.]
In other words, timer overflows don't “stack up”; whenever an overflow occurs before the interrupt from the previous overflow has been handled, the millis() counter loses a millisecond, and the discrepancy in timer0_overflow_count in turn makes micros() wrong by a millisecond too.
Regarding “shorter than 500 μs” as an upper time limit for interrupt processing,  “to prevent blocking the timer interrupt for too long”, you could go up to just under 1024 μs (eg 1020 μs) and millis() still would work, most of the time.  However, I regard an interrupt handler that takes more than 5 μs as a sluggard, more than 10 μs as slothful, more than 20 μs as snail-like.

Could you please elaborate on "how things work", in particular why micros() "start behaving erratically"? And what do you mean by "properly-written interrupt routine"? I assume it means "shorter than 500us" (to prevent blocking the timer interrupt for too long), "using volatile variables for communication" and "not calling library code" as much as possible, is there anything else?

@PetrPudlák, see edit

You should never do anything inside an ISR except set a flag saying you got the interrupt, and return.

While it is true that one should keep ISR code as short as possible, this statement is excessive. There are many situations where doing something else is relevant. In fact, just setting a flag is useless: the hardware, at least on AVR, does that for you, without having to enable the interrupt.

@EdgarBonet, I am not sure, but I think high rep users can vote to delete an answer with negative score

@Juraj: Indeed, you are right.

It is different than the advice you've gotten maybe, but it simplifies code and encourages good program structure.  Open your mind and see how the suggestion would make the problems in the sample code go away.  The only thing "excessive" is my 30 years of coding firmware for IBM :)

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

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


text:
Arduino IDE stopped uploading sketches to BLEduino board
I know similar questions to this have been asked before, but I have a "resp=0x10" which I haven't found elsewhere, so maybe it's different, the board is also not an Arduino Uno although it's should be fully compatible with it in adition to the Bluetooth part.
I'm a beginner to Arduino (and electronics in general) and I bought a Bleduino board. It was working without problems, I've tested a servo and a DC motor (with a motors shield) without problems. But, it suddenly stopped working! I basically can't upload any sketch no matter what I try, giving me this error (10 attempts):
         Using Port                    : COM11
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x10

avrdude done.  Thank you.

I did try the reset button before uploading (actually tried both black and white reset buttons on this board), double checked I'm using the correct board and ports.
I've used an old 12V power supply with 1000mA, so maybe that damaged the main chip? The L and LINK LEDs light up though when connected to usb or jack, and the bluetooth also connects to the IOS App.
I read [this][3] thorough answer for similar problems and my board passes the loopback test, but while uploading, only the L and RX LEDs flash!
Have I damaged the main chip? Do I have to buy a AVR programmer and burn a new Bootloader?
Edit:
A screenshot of wiring to test the Atmega16U2chip:

ATmega328Pchip Response:
Atmega chip detector.
Written by Nick Gammon.
Version 1.18
Compiled on Apr 10 2016 at 10:30:58 with Arduino IDE 10607.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
7E80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7E90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EA0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EB0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EC0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7ED0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

MD5 sum of bootloader = 0xEA 0x3C 0x5C 0xA9 0x35 0xD1 0x36 0xA6 0x71 0xD1 0xB2 0x3F 0x7E 0x62 0x79 0x6F
Bootloader MD5 sum not known.

First 256 bytes of program memory:

0: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
10: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x00 0x00 0x00 0x00 0x00 0x00 0x00
20: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
30: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
40: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
50: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
60: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
70: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
80: 0x10 0x20 0x40 0x80 0x01 0x02 0x04 0x08 0x10 0x20 0x01 0x02 0x04 0x08 0x10 0x20
90: 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x02 0x02 0x02 0x02 0x02 0x02 0x03 0x03
A0: 0x03 0x03 0x03 0x03 0x00 0x00 0x00 0x00 0x25 0x00 0x28 0x00 0x2B 0x00 0x00 0x00
B0: 0x00 0x00 0x24 0x00 0x27 0x00 0x2A 0x00 0x2A 0x01 0x7D 0x02 0x11 0x24 0x1F 0xBE
C0: 0xCF 0xEF 0xD8 0xE0 0xDE 0xBF 0xCD 0xBF 0x11 0xE0 0xA0 0xE0 0xB1 0xE0 0xE2 0xE0
D0: 0xF8 0xE0 0x02 0xC0 0x05 0x90 0x0D 0x92 0xA8 0x30 0xB1 0x07 0xD9 0xF7 0x21 0xE0
E0: 0xA8 0xE0 0xB1 0xE0 0x01 0xC0 0x1D 0x92 0xA7 0x31 0xB2 0x07 0xE1 0xF7 0x10 0xE0
F0: 0xCC 0xEB 0xD0 0xE0 0x04 0xC0 0x22 0x97 0xFE 0x01 0x0E 0x94 0xFB 0x03 0xC8 0x3B

Programming mode off.

Thank you Nick! I think I'll have to wait then till I buy an Arduino board and test with.

Looking at this post about the uploading process a response of 0x10 is STK_OK. Now while that looks fine, if the uploader is expecting STK_INSYNC then it's not OK.
I suggest you go through more of the steps in the link you posted.
You could use the "board detector" sketch mentioned on that page, to see if the main chip is completely gone, or if there is another issue. Other issues might be things plugged into D0 and D1, wrong baud rate, wrong clock rate, etc.

Hi again!,
I've an Arduino Uno and tested with and apparently I have a failed ATmega16U2 chip!

It seems odd to me that a failed chip makes any sort of response. You reported it responded STK_OK each time.

I followed your instructions about that chip testing and I got:
Atmega chip detector. Written by Nick Gammon. Version 1.18 Compiled on Apr  9 2016 at 23:55:08 with Arduino IDE 10607. Attempting to enter ICSP programming mode ...................................................... Failed to enter programming mode. Double-check wiring! Programming mode off.
And here's a screenshot of the wiring:
link

And here's what I got when testing the ATmega328P chip:
link

Google Drive: You need permission - how about editing your question and including relevant extra details in that, rather than an off-site link?

Yes sure I'll do that in few hours

I've edited the post. Please review.

A screenshot of wiring to test the Atmega16U2chip: Processor = ATmega328P - it's not a Atmega16U2chip is it?

I really don't know what's the difference, I'm new to this, but I wired to the pins beside the usb socket as you advised.

According to this page, it's the BLE firmware Burn http://www.elecfreaks.com/wiki/index.php?title=BLEDUINO

The schematic is a bit hard to read, but it doesn't look like it has a Atmega16U2 chip on it. it suddenly stopped working - sounds like you damaged something, but that chip looks OK, except that it has an unknown bootloader (not necessarily a bad thing).

So, what do you advise me to do? Would using an AVR programmer solve the problem?

Read the link about problems uploading. You may possibly be able to program the chip with an AVR programmer. I can't say for sure.

Nick, I'm sorry but I must say THANK YOU! I've been able to solve the problem using the "ATmega328P responds but has no bootloader" part of your fantastic post! I'm able to upload to BLEduino board once again :)


text:
Measuring the capacitance of 2 capacitors at a time
I need help with my project. In my project, I have two homemade capacitors made from 2 aluminum foil strips separated by a water bottle. I need to detect which bottle is going to become empty as people drink from it. So I plan to use the change in capacitance to detect the empty bottle. I know how to measure capacitance of 1 bottle and detect the change, but I don't know how to do it to 2 bottles at a time. Any ideas how to do this?
Here is the following code, I have been working on.
// Initialize Pins
int analogPin = 0;
int analogPin1=1;
int chargePin = 13;
int chargePin1=12;
int dischargePin = 11;
int dischargePin1 = 10;

// Initialize Resistor
int resistorValue = 10000;

// Initialize Timer
unsigned long startTime;
unsigned long elapsedTime;

// Initialize Capacitance Variables
float microFarads;
float microFaradr;
float nanoFarads;
float nanoFaradr;

void setup()
{
  pinMode(chargePin, OUTPUT);
  pinMode(chargePin1,OUTPUT);
  digitalWrite(chargePin1,LOW);
  digitalWrite(chargePin, LOW);
  Serial.begin(9600); // Necessary to print data to serial monitor over USB
}

void loop()
{
  digitalWrite(chargePin, HIGH); // Begins charging the capacitor
  digitalWrite(chargePin1,HIGH);
  startTime = millis(); // Begins the timer

  If(analogRead(analogPin)>648){
    elapsedTime= millis() - startTime;
    microFarads = ((float)elapsedTime / resistorValue) * 1000;

    if (microFarads == X) // X is an arbitrary capacitance when the bottle is empty and X is not a variable
    {
      Serial.println(" Bottle A is empty");
    }

    digitalWrite(chargePin, LOW); // Stops charging capacitor
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin, INPUT); // Prevents capacitor from discharging
  }

  If(analogRead(analogPin1)>648){
    elapsedTime= millis() - startTime;
    microFaradr = ((float)elapsedTime / resistorValue) * 1000;

    if (microFaradr == Y) // Y is an arbitrary capacitance when the bottle is empty and Y is not a variable
    {
      Serial.println(" Bottle B is empty");
    }

    digitalWrite(chargePin1, LOW); // Stops charging capacitor
    pinMode(dischargePin1, OUTPUT);
    digitalWrite(dischargePin1, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin1) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin1, INPUT); // Prevents capacitor from discharging
  }
}

Please edit your question and add a photo, a circuit diagram,  and  a Minimal, Complete, and Verifiable example of code.  This will indicate how you measure capacitance of a bottle.  That may dictate the approach to measuring two at once.

Do you need to do two at a time? How long does it take to do one? Can you do one after the other? Would that be easier for you to implement?

@Mark Smith I would like if the capacitor's capacitance can be measured at the same time

Your requirement of measuring “at the same time” makes no sense: you will never be able to synchronize the measurements to the picosecond. Please, tell us instead how much delay you can tolerate between the measurements. Do they have to be done in the millisecond? In the same microsecond?

If you know how to do one bottle you already know how to do two bottles. The second bottle is identical to the first (just change your pins / variables). Making a class is a good way of abstracting repeated complex code like this.

I have pasted the code. However unable to reformat it.

I just reformatted the code, now the edit is gone...

@Edgar Bonet, I realise that it is impossible to coordinate  the measurements.  Sorry for the request. It would be fine if there is a time difference of 30 seconds or so between each measurement.  I have tried to achieve it through my code. Thanks.

Taking a closer look at this... your approach is completely flawed. You expect a capacitance change in the tens of picofarads, maybe 100 pF at most. With a 10 kΩ resistor, the charging time constant will be no more than one microsecond. Forget analogRead(). You need a bigger resistor (1 MΩ should do) and a faster measurement method. Search this site (or the larger Web) for capacitive sensing methods suitable for small capacitances. Once you manage to measure one bottle (and not before), you may worry about having two bottles.

Ah, I assumed with my answer that the one-capacitor version was known to work...

Before we get started, there are a few problems with your code.
First, I wouldn't check for ==648 or ==0: what if you miss it by a moment and it jumps to 649, or it doesn't quite discharge to 0v?  I'd use >=648 and <=2 (or some other similarly low number - experimentation required).
How is your circuit connected?  I can't quite get my head around the charge and discharge pins, but I'll stick with what you have, assuming it works.
You say you want measurements every 30s, but don't say how long they take. (I have no idea of the capacitance of your bottle.)  My code assumes it takes much less than 30s to measure one bottle.  If it takes near to 30s to do one, this won't work.
I'll also assume your code works.  This is a bad assumption, since it won't even compile (capital I in if) but regardless, that's what I'll assume.
All that being said, here's the code:
// Pins connections
int analogPinA = 0;
int analogPinB = 1;
int chargePinA = 13;
int chargePinB = 12;
int dischargePinA = 11;
int dischargePinB = 10;

// Resistor being used
int resistorValue = 10000;

void setup()
{
  pinMode(chargePinA, OUTPUT);
  pinMode(chargePinB, OUTPUT);
  digitalWrite(chargePinA, LOW);
  digitalWrite(chargePinB, LOW);
  pinMode(dischargePinA, OUTPUT);
  pinMode(dischargePinB, OUTPUT);
  digitalWrite(dischargePinA, LOW);
  digitalWrite(dischargePinB, LOW);
  Serial.begin(9600);
}

// Measure the capacitance of specified capacitor
float measureCapacitance(int analogPin, int chargePin, int dischargePin)
{
    // Ensure the capacitor is discharged
    digitalWrite(dischargePin, LOW);
    while (analogRead(analogPin)>2) { /* Do nothing */ }
    pinMode(dischargePin, INPUT);

    // Start charging
    unsigned long startTime = millis();
    digitalWrite(chargePin, HIGH);

    // Wait for the capacitor to charge
    while (analogRead(analogPin)<=648) { /* Do nothing */ }
    unsigned long endTime = millis();

    // Start it discharging again, ready for next time
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW);

    // Calculate measured capacitance
    unsigned long elapsedTime = endTime - startTime;
    float microFarads = ((float)elapsedTime / resistorValue) * 1000;
    return microFarads;
}

void loop()
{
    // Measure capacitance of first bottle
    float microFarads = measureCapacitance(analogPinA, chargePinA, dischargePinA);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle A is empty");
    }

    // Measure capacitance of second bottle
    float microFarads = measureCapacitance(analogPinB, chargePinB, dischargePinB);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle B is empty");
    }
}


text:
Listen for USB "TX signal received" response on RX
Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.
To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified USBAPI.h and HID.cpp files. It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.

All but two of your tags do not belong, but apart from the obviously inapplicable "signal processing" only you know which.  Delete the ones that don't belong.

The atmega32u4 is the chip the arduino micro uses and I mistakenly thought that was also what the uno uses. Signal processing was included because I expect the solution involves measuring the raw signal from the computer but until that is confirmed I'm happy to leave it off.

That is not what "signal processing" means.

Is "signal processing" not taking analog signals or digital voltages, cleaning them up, and extracting meaning from them? A solution need not use the communication standard to achieve the goal in this case.

None of which you would be doing in this case, as you are not implementing a USB transceiver yourself, but merely using someone's working chip, USB stack, and apparently protocol driver.  And even if you were implementing it yourself (think V-USB), it is arguably too trivial a case to qualify.  Go try to find signals or patterns in noise you have to reject and we can start applying the term.

I don't understand the question, to be honest. Please read How do I ask a good question?.

If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond.  I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.
Going a step further, in the Arduino API an if (Serial) test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it.  Again, this only applies to those that implement USB within the chip on which the sketch is running.
Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in USBCore.cpp Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset.  In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you.  See for comparative example the implementation details behind the if (serial) and create something similar for your chosen USB mode.

if (Serial) is not what is needed here I think as that looks for a connection to the arduino serial terminal and the keyboard (which I am using) library does not depend on that. IE, (Serial) may be perpetually false but various Keyboard functions might or might not work.

I only included the Serial check as an optional more specific extension.  The SoF case should catch anything.  If you are implementing a keyboard in particular, that protocol may have more specific interaction too, indicating that the host operating system has decided to accept you as a keyboard, and not merely noted your presence on the bus.

Can you provide any further reading references on how to use this possible interrupt? I am not aware of any USB related interrupts in the standard arduino micro development environment.

You may well need to dig into the source code of what Arduino normally does behind the scenes below the sketch level.  You may find they have exposed something for the mode you are using compared to the "if (serial)" that is exposed for the usual USB-serial mode, if not you can fix your issues in the source.  Or even more simply, just make sure you don't wait forever for something that may not happen.

I actually have looked at the source code and modified it so the original keyboard library supports proper media keys and such. The problem is rewriting the USB interface is probably 20K LoC in an area I have no expertise in for a problem entirely unrelated to my actual work. My arduino sketch right now is only 175 LoC + ~20 added to the Keyboard/mouse library.

Also when I originally checked into the source code for the library the constructor/deconstructor functions called in the source appear very half baked or non existent. IE calling them or not made no difference to the functioning of the arduino as a USB device. What I'm getting from all this is that the solution to all this might be "go rewrite the keyboard library from scratch." If that's the case, well shit, I'll buy a Teensy, replace the Arduino, rewrite my code and still be done with less time, effort, and frustration.

No, the solution is probably adding 1-3 lines of code, maybe 10 tops, as it is simply checking a condition and returning early if there is no USB.

As I understand, you are trying to implement some peripheral device based on AtMega 8-bit micro-controller that uses USB1.1 interface (FS or LS) to connect to USB host. Your problem seems to be that your host computer (unspecified) puts the port into SUSPEND (sleep), and does not wake up when you try to activate your device (button or something).
First, the USB2.0/1.1 interface does not have any "Tx" or "Rx", it is a half-duplex bi-directional bus. It has D+ and D-, and VBUS. But it is true that a USB peripheral device can generate a bus event called RESUME.
You have two choices. (1) either you make your host computer to never sleep or put USB ports into SUSPEND, or (2) make your device to support RESUME (aka "remote wake-up") function in full compliance with USB specifications.
In case (2) the driver for your device (on host computer) must support remote wake-up function, and this function must be enabled. Then when the host computer is planning to go into one of various sleep modes and decides to SUSPEND your device, it must send special control command to your device which should arm it for wake-up, and the host will be expecting it. In this case the host will never remove VBUS ("passively from computer"), so the device will be able to wake the bus up.
Is this your question about?

No, the question is about a device which should behave differently when it is connected to an operating computer vs. a non-operating computer or simple power supply.

Yes what Chris said is true. The solution should be OS agnostic (IE no modifying of drivers on host computer). That said, if I can make the arduino listen for the SUSPEND and RESUME commands the computer might already be sending, I might be able to achieve the goal anyway.

Then I am confused. On operating computer, your device will connect and will be enumerated and maintain active status as long as host sends SOFs or keep-alives. On non-operating computer the device will not receive any responses from host, and should fall into SUSPEND state (without being armed for remote wake-up). When connected to a charger, this will be similar to non-operaing computer. This behavior is defined in USB2.0 specifications. So what is your question then?

@amoose136: it is not "if you can make the arduino listen to SUSPEND", you must make it so, so your device conforms to USB specification. The SUSPEND function is one of basic USB function. You might elect to do nothing if bus suspend happens, but your interface must wake-up and start responding to host packets if host decides to resume port's activity.

Yes this would probably solve the issue if the device is initially plugged into a computer that is turned on but what if the power goes out? Then no suspend signal is sent and the arduino will try and do the handshake before the OS has had time to boot up so nothing will work.

The goal isn't to have it suspend, the goal is to have it not get stuck waiting for a computer that isn't there or isn't awake.  Of course, the fact that it is apparently getting stuck is purely a problem in how the device side USB code is dealing with USB, not one with USB itself.

@amoose136: When a USB port has no power, it means that the host is not ready to connect and communicate. The "suspend signal" cannot be sent, the SUSPEND happens when NO SoF SIGNAL IS SENT. A USB device must not pull up any data wires (aka "connect signaling") or start any "handshake" until it receives a valid VBUS signal (even if the device is self-powered). This is a major USB requirement. Overlooking VBUS functionality as a logical signal to start communication is a very common mistake in USB design.

@AliChen - what you keep missing is that the problem occurs when there is no active USB host to talk to, but power is present.  Stop thinking about the USB spec, and think instead about what the poster's device will experience if connected to a phone charger instead of a computer.  Of course this has simple solutions, if one is willing to spend some time understanding and modifying the code which implements USB peripheral functionality.

@Chris: yes, I am missing the problem statement. A powered USB port on non-operating computer is no different from a wall charger, so the USB device should not behave any differently, unless OP means charging functionality. By a set of functional explanation of how a normal USB interface works, I am trying to obtain clarification to the OP question, but apparently I have little success. If you have a firm grasp on the essence of the question, please provide a proper edit and make a clear statement of the problem. So far I failed to see any problem, except of brutal misuse of USB terminology.

The problem is that the poster's software hangs when it is not serviced by an operating USB host.  The problem arises because they are using a USB peripheral code library written by someone else, with internal workings they haven't really studied.

@Chris: Thank you for the clarification. Ok, then the device driver on Arduino side is totally botched - the support for fundamental USB suspend-resume functionality is missing. This is what happens when someone resorts to half-baked software disregarding interface protocol specifications.

No, it has nothing to do with suspend-resume.  You are still assuming that there ever was a functioning USB host.  There might have been, or there might never have been.  The poster's device needs to deal with both.

Let us continue this discussion in chat.

Upon having a clarification on what the problem essentially is, the answer is as follows:
(1) There is no way of knowing if the port is a wall charger or inactive computer port, initially. Therefore the initial device behavior must be identical in both cases – asserting pull-up on D+ (assuming it is USB 1.1 FS interface);
(2) However, if the port belongs to a computer, the connect event will awake the host, and the host will issue USB_reset, and perform device enumeration. There is no need to “send any Tx signal” or else, the host will perform this activity by itself. The Arduino software must remember this.
(3)  If the host decides to suspend the port (fell asleep), the device must transition into SUSPEND state, and Arduino software must remember this.
(4) If the port was initially in a state with USB totally disabled and does not wake up upon cable attach, see scenario (1);
(5) When/if the host computer is awaken, it will see USB attach status (D+ is up), and will start scenario (2).
In summary, the device (upstream facing port) must implement port functionality in full accord with port state machine described in USB2.0 specifications, Section 9 (Figure 9-1) and Appendix C.2 , Figures C-2 and C-3. As one can see, contrary to the assumption of OP, the port can be in more than two states, and Adruino software must have several different behaviors. Any half-baked implementation of the port state diagram is unacceptable and will cause some functional problem sooner or later.

Wow! Downgrade! I guess some people prefer hacking over engineering here. Amazing.

I did not downvote your answer. While I think this is probably the right approach, I'm wondering about the specifics of implementation and why the provided mouse/keyboard library doesn't implement any of this; is there some hardware limitation I don't know about maybe? (https://www.arduino.cc/en/Reference/MouseKeyboard) Secondly, given my know how, I don't know if I have the time or experience to implement something so complex. That sounds like several hundred lines of code just for proper USB spec adherence while my actual sketch is probably only 175 LoC in the first place.

The provided library doesn't implement this because it is not actually necessary for most purposes.  What is proposed here is a far, far, far larger task than needed.  The is issue is nowhere near as complicated as Ali insists on makes it out to be, but if you want to get distracted into pursuing this, that is your choice.

@Chris: As an engineer with 20+ years in semiconductor industry, yes, I insist that the USB device protocol must be implemented in full accord with specifications, with all states and transitions. The suspend-resume state of USB device are not designated as "optional", their implementation is a "must". If not, the device loses an ability to distinguish an active (but sleepy) host from a dumb charger, or exactly as the OP's situation illustrates. Specifications are written and world-wide adopted for a reason, they represent collective wisdom and experience of many seasoned engineers.

@amoose136: The reference list of Arduino kbd/mouse functions clearly lacking any interface calls to get the USB link status. Apparently the designers of this HID class did not consider the case when USB host might suspend the USB port. As I firmly believe, adherence to USB specifications is your solution. Yes, it is a serious effort. As far as I see, the USB hardware in ATmega32u4 does support "suspend/resume interrupts", so I guess the hardware is USB compliant.

Obviously, rewriting the entire USB implementation is uncalled for here.  If you really want to do that, you could consider making the changes to the upstream code yourself and submitting a pull request to the Arduino folks, but it is not going to get the asker of this question a solution in a reasonable time frame.  You seem somewhat ignorant of the fact that many devices on the market do not implement the full USB specification, but rather only the parts they practically need to.

It is not "re-writing", it is WRITING a CORRECT SOFTWARE. You seem to be ignorant of normal engineering practices if you insist on making a software that does not conform to mandatory USB requirements. You admitted that you are not familiar with USB hardware in Atmega processors, yet you are offering a hacking advice. Why would you suggest to take interrupts every 1ms from SOFs when the hardware already has a 3-ms "watchdog" timeout and can generate proper interrupt on bus suspend?   But then what you would do? Invent your own suspend-resume algorithm instead of following specifications?


text:
Looking for an accurate and fast updating range sensor
I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).
I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.
I'm happy to explain more about the implementation if needed.
UPDATE
I wish more people were reading this post, because I have great suggestions for DIYers after researching a lot of options the past few days. Currently I'm looking at offerings from Turck.com relating to reading a magnetized strip. This would read position from the side rather than from above or below as I describe in my original question. Turck calls it their "LM-2 line" and some options look pretty affordable and quite a bit under $500. Here's a brochure they provide - it documents how they read a magnetic strip: https://www.turck.us/attachment/B1027.pdf
NOTE
There is one answer here related to a different sort of solution involving a device which reads a code every 0.5mm or 1.0mm taped to a rod which is attached to the piston. Device would read in direction perpendicular to direction of motion. This would probably be my 2nd or 3rd choice if I'm unable to find an affordable sensor as described in my question.
NOTE 2
If I had time I'd implement the following solution which I wish I had thought of a month ago: tape a 300mm strip of reflective material which varies in reflectivity along its length. shine a laser on the tape and detect amount of light which reflects. simple solution, easy to calibrate and (if I knew where to get the tape) should be low cost.

None of this discussion has any real bearing on the question. I'm moving it to chat.

Comments are not for extended discussion; this conversation has been moved to chat.

what moves the piston? ... is there any possibility to measure the motion of some other part of the device and calculate the position of the piston?

magnetic fields move magnets in the piston. the piston is attached to a long rod. i'm using that for sensor to detect piston motion. yes, i'd rather measure resistance along a linear pot. however, as accuracy is key I would need to tackle issues related to variable stray capacitance as well as resistivity as it changes wrt. temperature. or i could try my best to calculate position via accelerometer input, but there are bigger unknowns there. in any case, i'm not sure why laser sensors would need to be so expensive. but they are because industry pays for them.

here's an idea I wish I had time to implement: at every millimeter along the rod there can be a series of 1's and 0's that represent the distance value. if I had something that could read that every 0.5 ms ... i still think it would be either slow or inaccurate though. probably too slow.

If you haven't found the answer you want @John Ahearn, maybe it's time to step back.  For instance, is the piston connected to a crankshaft?  It might be easier to measure the rotation of the crankshaft than the position of the piston.  There are loads more ways of doing this as there are loads of rotation sensors for servo motors.  In fact, I'm betting this is a commodity market where the scale of manufacturing is in your favor.

You said: "could read that every 0.5 ms ... i still think it would be either slow or inaccurate though. probably too slow".  Again, step back.  What do you really need?  Why can't you use software to interpolate the position of the piston ever 0.5 ms from, say, samples taken ever 2ms?  And if linear interpolation isn't accurate enough you could curve fit it.  Also, is this a repeatable event?  If so sample a number of repeated events and phase shift the samples just a bit each time building an almost continuous representation of the piston position after a certain amount of time.

Thanks for the input. I've found this is the issue with similar forums and comments: i'm restricted to the guidelines and attitude of respondents, then the crapshoot of "anyone know the topic and want to help". The result is that I'm either too detailed or not detailed enough. My post is a result of "stepping back" at least 4 times. I understand in great detail my apparatus, requirements and most product offerings. I've posted here with what looks to me like a spot on question awaiting a response from the right person. I have options as mentioned. No need for more analysis. Just budgeting.

I'm currently considering a Wenglor OPT20XX product going for about $750 after shipping. It will work like a charm. Overkill even. I'm looking for something similar that's cheaper. I'm not sure it's ok to post the link here and I'm tired of being downvoted and/or criticized for no reason so I won't take a chance by posting it. The product is the Wenglor OPT2003 and if needed I'll have to fork out $250 more than I want.

And no, I didn't know this product before yesterday. The $750 is down from much more expensive offerings I was researching.

Rotary anything doesn't work and isn't a good solution at all even if it did. Many reasons for that.

btw - linear interpolation from 2ms samplings would be the worst case scenario. I don't see any reason at all for why I'd have to settle for that when I'm willing to spend $500. reminds me of an old line from Star Trek: Spock, who was attempting to "construct a mnemonic memory circuit using stone knives and bearskins". The difference is that I don't need stone knives and bearskins.

Regarding Note 2: What about using your favourite word processor to produce a gradient background that's 300 mm long, then print it out onto photographic paper with your printer, then tape it to the rod?

do you mean a printed surface for reflectivity gradient? what is the material that the light reflects off?

i'd worry about noise. spurious reflection.

Inside an inkjet printer, I've found a clear plastic strip with photo-engraved (loose approximation) lines perpendicular to the length of the strip. This strip passes through an optical pair, one side illuminates, the other reads. The strip stretches the entire width of the printer and if I recall correctly, the reading module is on the print head carriage. Consider that many printers are described as 600 dots per inch, which would create a resolution on the strip of 1/600" / 0.04 mm.
Additionally, I've discovered circular plastic encoders on which the rings of black/clear alternated the segment counts with each expanding ring. That is to say, the first ring was half black, half clear. The next ring out was 1/4 black/white alternating, the one following was 8 segments, then 16, etc.
This required a reader for each ring, but provided an absolute reference rather than a relative reference as is the case with the linear strip. One could create a linear strip which would work in a similar manner. One level would be half black, half clear, the next layer would be 1/4 black/clear, etc.

The requirement for 500 mm fits into a binary 512 value, which would require 9 stripes and provide for the accuracy noted in the post.
The aspect I can't answer is the speed of the encoding, although I suspect that any design based on an optical reader could be optimized to work.
I found an article at rp-photonics.com

When light is diffracted at the traveling refractive index grating in
an acousto-optic modulator, the diffracted light experiences a shift
of optical frequency which is plus or minus the acoustic (or drive)
frequency. That effect (which can be interpreted as a Doppler shift)
is exploited in acousto-optic frequency shifters.
Drive frequencies are typically between some tens and hundreds of
megahertz, rarely more than 1 GHz. The resulting change of optical
wavelength is quite small. For larger frequency shifts, or for
realizing very small frequency shifts (e.g. only a few MHz), one may
cascade two or more devices. It is also possible to use a double pass
through a single device in order to obtain twice the frequency shift.

I think from reading that excerpt that the long strip in the inkjet printer is the traveling refractive index grating. I had not considered that a low-power laser could be substituted for a simple optical pair. Doing so would provided even better resolution.
If your project allows for a strip of sufficient length to be attached to the piston, with assurance that it won't buckle under acceleration and jam in the sensor, you'd probably make it work.
But wait, there's more. I can picture the rod on the piston alternately obscuring and uncovering a digital design, which is constantly scanned by a laser. This reduces the number of parts in close contact and possibly the moving mass.

It's a great idea. I may try to implement along these lines, but as I've indicated in my comment above there's no reason to think this is more accurate or as fast as a TOF or triangulation solution setup in the manner I suggest at an affordable cost. The advantage  is a fast binary calc can turn the scanned lines into usable measurement values. The disadvantage is uncertainty of the setup which, even if calibrated perfectly, is not guaranteed to be accurate enough for my needs. Vibration is the first issue to be considered for instance.

Clarifying my comment just above: I'm referring to vibration of the rod which is attached to the piston. Not vibration of the sensor/reader which would be still.

You can mitigate vibration by having supports at both ends of the traveling rod. I suppose if you have a piston running at 1 MHz or higher, you'll have some imbalance in the entire assembly. Horizontally opposed pistons?

Sorry wasn't clear : the rod is as vibration free as is possible. That doesn't mean it won't be an issue. In fact I'm certain it will be, and if I have to spend time and money lessening it even further than I've defeated the purpose and might as well stick with the original idea of a (likely) expensive position sensor.

An alternative could be to use a Gray code instead of the binary code.

yep. that was meant to be a placeholder for "code". please see my note up top regarding magnetic strip reading

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


text:
Arduino UNO IR blaster - storing codes in PROGMEM
I've setup an IR LED on my UNO, with the IRremote library, and have the code working to control an RGB LED strip from certain serial input, however as i'm storing the Raw infrared data in variables, i'm running out of RAM very quickly, and haven't managed to get code working that stores the IR data in PROGMEM, then buffers it to RAM for sending.
The current working code can be found at https://gist.github.com/dan-r/71294eaf9fe2354f1a0c7c13fc5f3bcd, and i've tried setting the int arrays as statics in PROGMEM, but whatever I do, I can't figure out how to buffer them into RAM, or even directly send them with irsend.

The Arduino Uno can not read data from PROGMEM (data in flash memory) in the same way as reading data from ram, there are special functions to read data from PROGMEM.
Create a buffer in ram and use one of those special functions to copy the data into that buffer.
Start with the Arduino PROGMEM reference.
Nick Gammon had made a great tutorial about PROGMEM.
All the PROMEM functions are in <avr/pgmspace.h>
Is the array of numbers always the same length ? That would make the sketch a lot easier.
Then perhaps something like this:
const unsigned int irTable[9][67] PROGMEM = { { ... }, { ... } }

unsigned int irBuf[200];

i = ...   // number of command
memcpy_P ( irBuf, &irTable[i][0], 67 * 2);
irsend.sendRaw (irBuf, 67, ...);

Works perfectly, all cleared up and into the irTable array, thank you for your help! :) (Final code is https://gist.github.com/dan-r/067b4857a0f44079c655855145e1518d for reference)

Well done ! But why lay back ? You could make a table of texts in PROGMEM with "brightup", "brightdown", "off" and so on, in the same order and the same index as the IR codes. Then you can search the table with texts to find the index of the IR code.

Hmm good idea, going to try that!


text:
are 3 connections necessary for a push button?
I'm referring to the 5th circuit (see below screenshot) of the sparkfun manual came with the arduino uno. Instead of connecting all three of the (+) (-) and the digital pin to each push button, can I just connect the (-) through the resistor and the digital pin?
Also a side question, in terms of physics, you need two ends to be connected in order to create pressure for the flow of electrons, but the digital wire for each push button that goes out to the arduino board doesn't have its own ground wiring that suppose to create the pressure as a couple. How to cope with that in terms of electron flow?

You need two connections to the switch, but the pullup resistor requires a voltage source, which is a third connection.  You can place the pullup either at the switch, or at the ditial pin, or somewhere in between.  You may be able to use internal software-configured pullups instead.   All currents have closed paths - but they may be sharing a path with a current headed elsewhere, for example, when you close a switch a small current discharges the pin capacitance, sharing the ground path with a larger one flowing through the pullup resistor.

So can i just connect the (-) with the resistor?

No, you cannot, as then you would not have any signal line.

i meant i kept the signal line, along with the resistor which connects the ground node

The resistor does not connect to ground.

i meant if it does, that's what i said in my question "connect the (-) through the resistor and the digital pin"

That is neither what you should do, nor what you have shown in your diagram.

The diagram is the sparkfun circuit that I am referring to, of course it doesn't show what i'm describing. I thought anyone who played with arduino would recognize that screenshot as something from the manual that came with it, I'll edit the question to make it clear.

You can use the internal pullup e.g.
pinMode(inPin, INPUT_PULLUP);

Then wire your switch between pin and Gnd.

In order for an input pin to be able to read a real value it must be connected to something - either a power source (Vcc) or to ground.  If it's not connected to either of those and left "flapping in the breeze" then it's said to be floating and the input value cannot be determined.
So you need a way of switching that input pin between being connected to Vcc or being connected to GND.  That is why there are three wires - the input pin and the two voltage levels that must be chosen between.
Now an input pin has a very high resistance (impedance) to ground. So when you connect it to Vcc a very tiny current will flow through it to ground, thus completing a circuit.  If you add another resistance between the pin and Vcc the incredibly small amount of current that flows will only cause the smallest of voltage drops across that new resistor (see Ohms Law).  So connecting the input pin to Vcc through a 10kΩ resistor (for example) will mean the voltage read at the input pin will be only fractionally below the +5V of Vcc.
Now when you introduce the pushbutton, which connects the input pin to ground when pressed, will also connect the resistor to ground. So you have the full 5V of Vcc across that resistor, and the input pin will be reading 0V.
Without the resistor in there - if you just connected the input pin to Vcc and then had the button connecting to ground - as soon as you press the button it would connect Vcc directly to ground, which is a really really bad thing to do. That's called a short circuit, and it's when batteries start to explode and wires melt.
So the input pin itself is basically a voltage detector that detects what the voltage at the input pin is.  It has two thresholds known as VIH and VIL - the input logic voltage for HIGH and LOW respectively.  On the Arduino those are 0.6Vcc and 0.3Vcc - or 60% of the supply voltage for high, and 30% for low. At 5V that's 3V and 1.5V respectively.  If the voltage seen at the input pin is above 3V then it's seen as being HIGH. If it's below 1.3V then it's seen as being LOW.


text:
Project wont compile when I place functions below function calls
I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...
So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)
When I place the functions above the function calls it compiles.
Is this normal behavior or do I have to add some settings to get this working as provided?
Fails in VSCode (works in Arduino IDE):
#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

Works in VSCode (Works in Arduino IDE):
#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}

did you try them in Arduino IDE?

@juraj, I edited my examples, so you can copy/paste them into the editors. Both examples are working in Arduino, only the below one is working in VSCode

Arduino builder adds function prototypes when converting .ino to .cpp

You need to declare your function before you use it.  So either the whole function body needs to be before the usage, or you must add a function prototype declaration.
void myfunction();

myfunction();

void myfunction(){
  return 0;
}

So if I understand you right, this could be done in a header file? I never saw them in the examples I used. But that would make sense...

I think Arduino IDE is doing some "magic" behind the scenes to be able to compile without declaring the functions above the function call. I also updated my examples, to be able to copy and paste them into the corresponding IDEs.

void myfunction() should not return an int

@Jan: Indeed. The Arduino IDE edits your .ino file, adds those function prototypes at the beginning of the file, saves the result as a .cpp file, and calls a C++ compiler (g++) to compile that .cpp.

@Jan, why did you accept an answer which doesn't answer your question?

Just make the the abstract method declaration before writing your code after the header files.
#include<Arduino.h>
void myfunction();
void setup();
void loop();

After this you write your code in any order


text:
What is the minimum wattage of resistors for breadboarding with Arduino Uno?
I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?

I know this has been answered, but would you care to elaborate? What is it you're trying to do? Which resistors are you wanting to replace, and why?

I'm building a morse transmitter/reciever, you can find a discussion about it here and here. I don't want to replace my current resistors just buying some I don't have in my repertoire 100R, 500R, 1K. I'm buying 0,25W ones, because it's enough according to the equation P=UU/R=55/100=0,25, 100R is the smallest I'll buy. It is not all for the current project, but for the future. I gladly hear your opinion too.

lol, no worries. I thought the question was a bit odd :)

The answer is: It depends what you want to use them for.
You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them.  There are standard formulae that tell you the power in any given situation.
For instance, if you know the current and the resistance you can use:  P=I²×R. If you know the voltage across the resistor it's P=V²÷R.
Take as an example the common resistor for an LED.  Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.
To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors.  ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.

Thanks. That equation is really useful. I calculated and it seems 0,25W is good for what I'm going to do. Also there are no 1/8 resistors in the shop.

Go with 1/4 Watt resistors but be prepared to use 1/2 Watts if the leads don't press down cleanly into the breadboard which is what I think you are asking about. If you need anything in the higher wattage range and you are working with an Arduino, then you are doing it wrong. An Arduino could not smoke a 1/4 watt if it tried.
I have fought for years with our purchasing agent over this at the college I work for. He buys 1/8th watt resistor in bulk, but fails to heed the advice that you cannot use these on standard classroom breadboard without bending the leads at best and failing to even make a good connection at worst. You need reliable connections and 1/8th and smaller are useless on breadboards. Just my two cents from years and years of experience.

The smaller the better for the most part. On 1/4 or 1/8 W resistors the leads size is small enough to work well in bread boards. Rarely do you need to dissipate large amounts of power so 1/8 is a good size for logic, maybe 1/4-1/2 for power supply areas.  See Majenko's answer for the heavy math, mostly applicable in power supply areas as he points out.

1/8 watt resistor leads are typically too small for easy breadboarding.  Even some modern 1/4 watt resistors have thin soft leads, though that was the traditional size mechanically speaking.

Hmm, I'll have to check that the one's I'm calling 1/8 really are. They are very easy to work with and the leads are much more "breadboard friendly."


text:
What is the correct way to wire a piezzo buzzer with a potentiometer and a button?
I'm working on a morse transmitter (kind-a), this how it looks like now:

It's working, but is it correct? My piezo buzzer is 3-24V. I use the potentiometer as a volume control. The button is for transmitting morse code.
I've seen a way of wiring like this, not using any resistors, it feels wrong, is it correct?
https://cdn.sparkfun.com/assets/learn_tutorials/3/1/0/Arduino_circuit_11_01.png

You are using the Arduino basically as a power supply (in your wiring). The linked wiring is for PWM (analogWrite). This allows pulse output to generate tone (and volume). Here is a good reference.


text:
GPRS/GSM SIM900 Shield not working with Arduino
I have a few questions related to GPRS/GSM SIM900 Shield not working with Arduino.
To keep it short I have a list of concrete questions:

Is the Arduino GSM library compatible with the Geeetech GPRS/GSM SIM900 Shield?
On the board the green LED blinks every 3 seconds which I have read
means that it is connected. However, when I try to use any of the
GSM examples, in regard to internet, I either get error messages or
simply no progress in the program. For instance, in the testGPRS
sketch it sits stuck at the port where it says "Connecting GSM
network...". And in the bandManagement example sketch it can't find
the current band,as well as the modem not responding, well basically nothing works, except that the
shield itself indicates it is connected to a network.

The SIM card I'm using is data exclusively and can't be used for voice calls or SMS. It has no pin code and works as my secondary SIM card (it shares the same subscription as my primary card).
Edit:
I have now tested the SMS capabillities of the board with another simcard, that works with no problems, seems only the internet won't work.

which arduino board are you are using? How are you are powering this board?

Im using arduino UNO, i power it through USB on my laptop.

I have also acquired a 9 Volt battery to test if extra power will help when I have tried it I will respond with the result.

These modules consume a lot of current (2A at least) when using GPRS. A 9V battery is no good as it cant supply this current. Look for an 18650 battery or 3.7 V LiPo cell that can supply 2A easily or a wall adapter coupled with a buck converter. Voltage should be at least 4 V but no more than 4.7V.

Ok so i tried the 18650 batteries and it is still not working.


text:
Is it safe to power the Uno with 18v?
So I'm aware the Arduino Uno can take 6-20 volts, with a recommended voltage of 7-12. But I have an unregulated 12v power adapter, which puts out about 18v with no load.
Most of the time the Arduino won't be doing much of anything but powering a 16x2 LCD, which should take only a couple mA.* I have a 10k ohm resistor on the back light, so it should only take 0.5mA.
*I don't have a datasheet, but from what I've read 1-2mA is reasonable
The Arduino won't be doing anything else that would draw any meaningful amount of current (except looping to check for input, etc). Online sources generally indicate the power draw when not doing anything is a little under 50mA, so I'm guessing that's about what the current draw will be. Using the formula in this answer, I calculate the power dissipation by the voltage regulator to be (18v-5v)*0.05A=0.65 Watts.

Is this correct?
Is the voltage regulator likely to overheat?

I'm not really concerned about power usage, because it will be plugged into the wall all the time. Also, the Arduino will be out of sight, but will have plenty of air around it to disipate heat (though not access to a breeze).

It won't do any harm to try it at 18V for a while. Most voltage regulators have thermal protection and just cut out if they get a little too hot. If it works reliably, stay with it.
EDIT: Their Uno page warns against overheating the board, so I would test it for a short while and make sure there is no overheating or strong "plastic" smell coming from the board. If there's enough heat to worry, then it's best not to run like that for extended periods.
If 18V is too high, you could get a power resistor (I'd guess say a 10 watt resistor around 24 ohms) to waste approximately half an amp from the power supply. Connect this to the supply, in parallel with the Arduino.  It's wasteful (unless your room needs heating anyway) but will lower the voltage (that reaches the Arduino) a little.

Thank you. I should have mentioned I mean 24/7. Probably a power resistor is the way to go. And no, the room is in no need of heat; we run A/C almost 9 months of the year! So I figure it wastes about double, since it burdens the A/C as well. Partially related (because I like this topic): While the power isn't wasted if heating is desirable, there are more efficient heating methods of heating. Thus, we can't fully shrug it off if we're using a more efficient heating system to heat the room.

By the way if the most efficient performance is required, I would actually recommend getting a 12V supply that is better regulated. You then won't need to waste heat. Or build/buy a switching type converter to bring the current 12-18V down to 5V.  (But both of these are going off the topic.)

Fortunately, power efficiency isn't much of an issue. However, wouldn't a regulated power supply simply waste the power itself (assuming it wasn't a switching regulator)? I'll revisit this answer when I settle on a solution. If you know an advertised power dissipation for the Arduino's regulator, that would be nice (I couldn't find it, though probably there would be a way to look at the Arduino's hardware design and find out what regulator they used).

Because the Uno regulators are said to get hot, I simply assume they're the "standard" kind of linear regulator which wastes any excess voltage as heat. Say it reduces 18V to 5V, it's wasting over two thirds of the total DC input as heat. So a suitable switching regulator unit would be more efficient and run cooler, but also more expensive. (Admittedly I've only cared about this on battery operated applications.)

I'd measure the voltage while attached to the Arduino board. A small load could already bring the voltage down enough to be acceptable.

Well... I think my multimeter lied.Or the power adapter decided to behave. More likely the multimeter; the ohm meter is broken but the volt meter seems to work (usually). It registers 12.34v when the Arduino is running, and only slightly more with no load (the other day it was showing 18v, or for a few moments 20v). Had it been 18v, I think I would have used two 1/4Watt 220 ohm resistors in parallel, to drop the voltage by 5.5v. Then if the voltage drooped to 12v, it would still get 6.5v. Running at 0.05A that shouldn't be much of a problem. Thanks for the help, and sorry for the mistake.

authors: สุทธิชัย อนัมบุตร


text:
Ooops, no LSM303 detected ... Check your wiring!
History
I have an Adafruit 10DOF IMU Breakout which has been working on my Mega for some time. This morning my program did not run so I starting troubleshooting.
Scenario
I eventually plugged the IMU breakout into my Uno with the *out-of-the-box accelerometer reader program from Adafruit. That's when I started seeing
Ooops, no LSM303 detected ... Check your wiring!
And upon close inspection have verified all wires are in the correct spot.

Question
How do I troubleshoot this further? Also, I'm starting to think that my IMU may be fried. How can I test this?

* AHRS out-of-the-box Program from Adafruit:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_BMP085_U.h>
#include <Adafruit_L3GD20_U.h>
#include <Adafruit_10DOF.h>

/* Assign a unique ID to the sensors */
Adafruit_10DOF                dof   = Adafruit_10DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
Adafruit_BMP085_Unified       bmp   = Adafruit_BMP085_Unified(18001);

/* Update this with the correct SLP for accurate altitude measurements */
float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

/**************************************************************************/
/*!
    @brief  Initialises all the sensors used by this example
*/
/**************************************************************************/
void initSensors()
{
  if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }
}

/**************************************************************************/
/*!

*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Adafruit 10 DOF Pitch/Roll/Heading Example")); Serial.println("");

  /* Initialise the sensors */
  initSensors();
}

/**************************************************************************/
/*!
    @brief  Constantly check the roll/pitch/heading/altitude/temperature
*/
/**************************************************************************/
void loop(void)
{
  sensors_event_t accel_event;
  sensors_event_t mag_event;
  sensors_event_t bmp_event;
  sensors_vec_t   orientation;

  /* Read the accelerometer and magnetometer */
  accel.getEvent(&accel_event);
  mag.getEvent(&mag_event);

  /* Use the new fusionGetOrientation function to merge accel/mag data */
  if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
  {
    /* 'orientation' should have valid .roll and .pitch fields */
    Serial.print(F("Orientation: "));
    Serial.print(orientation.roll);
    Serial.print(F(" "));
    Serial.print(orientation.pitch);
    Serial.print(F(" "));
    Serial.print(orientation.heading);
    Serial.println(F(""));
  }

  /* Previous code removed handling accel and mag data separately */
  //  /* Calculate pitch and roll from the raw accelerometer data */
  //  Serial.print(F("Orientation: "));
  //  accel.getEvent(&accel_event);
  //  if (dof.accelGetOrientation(&accel_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .roll and .pitch fields */
  //    Serial.print(orientation.roll);
  //    Serial.print(F(" "));
  //    Serial.print(orientation.pitch);
  //    Serial.print(F(" "));
  //  }
  //
  //  /* Calculate the heading using the magnetometer */
  //  mag.getEvent(&mag_event);
  //  if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .heading data now */
  //    Serial.print(orientation.heading);
  //  }
  //  Serial.println(F(""));

  /* Calculate the altitude using the barometric pressure sensor */
  bmp.getEvent(&bmp_event);
  if (bmp_event.pressure)
  {
    /* Get ambient temperature in C */
    float temperature;
    bmp.getTemperature(&temperature);
    /* Convert atmospheric pressure, SLP and temp to altitude */
    Serial.print(F("Alt: "));
    Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                        bmp_event.pressure,
                                        temperature));
    Serial.println(F(""));
    /* Display the temperature */
    Serial.print(F("Temp: "));
    Serial.print(temperature);
    Serial.println(F(""));
  }

  delay(100);
}

-- EDIT --
I'm pretty sure the board is dead. The program stops at accel.begin(), mag.begin(), or bmp.begin(); I've tried each individually.

same issues, ordered board from AliExpress. Using this code however, I can report that in my case, the board is not dead an reports some values - it just is not recognized somehow.   int yAxis = analogRead(A4); // Yout pin of accelerometer   Serial.print(",");   Serial.print(yAxis);

@user2305193 Fascinating. Please let me know how it turns out!

I had a similar issue. Turns out it was faulty wiring, probably due to a cheap breadboard (as a noob you would expect perfect connectivity from something like a breadboard! Turns out: not at all!)
Here's how I went about debugging it, using an i2c scanner to debug connectivity (find library + example here).

remove the while(1) loops that halt your program, so the program doesn't 'stop' on error
Use an 'error variable' e.g. fail. Initialize e.g. as fail=0 at start of script so it's global. Add fail=1 for every oops case in initSensors()
in loop(), check if fail==0, if yes, continue with outputting the 10DOF sensor values, if there is an error (fail==1) call initSensors() and the i2cscanner() so you get a debugging view of your connectivity. This would look like below, and will keep calling the debug function until you connected it properly.

Hope this was useful or at least interesting to you, good luck.
Screenshot of i2c scanner:

Check each of your conditional statement at
if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }

by commenting the others.

I this one of many Arduino invented terminology ?
Normally function returns ZERO on success and -1 or positive number identifying the error.
if(!accel.begin())

{
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }

Different functions return different things. Functions that handle buffers supplied by the caller typically return the caller's buffer pointer on success or a NULL pointer on failure, for one of many counter-examples. You can't assume what choices another author made without reading the description or the code itself. The author of this library wrote the .begin() function to return a bool; TRUE on success, and FALSE otherwise. It is not uncommon.


text:
Problems with running multiple ESC
I've written a program which allows me to use my Arduino Uno to send a PWM to an Electronic Speed Controller. 5 seconds after startup the ESC is sent a config via PWM to signal the low to high PWM range to be used by the ESC. Then I can type into the Serial Monitor a single digit 0-9 to pick the PWM I want to send to my ESC. (n*2 = pwm)
This works great when running code for one ESC, but adding code for a second ESC causes significant issues (I only have one ESC plugged in). When I send a serial command to specify PWM rate, my ESC only receives the PWM change sometimes. About 2/3 times it ignores the PWM change and keeps spinning at the same rate it was already at.
What's going on here?
Code
WorkingESCSoftware (main file of .eno)
#include <SoftwareServo.h>
#include "TestClass.h"

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

TestClass t, t2;

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

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

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

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

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

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

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

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

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

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

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

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

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

You cannot do this simply by creating two instances of the class - you have to have a single instance of code which reads the serial port and dispatches complete commands to them.

You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.
Semiphoras are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.
In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.

Ah, so it's strictly an issue with how I'm handling Serial input? That makes sense. I'll move the serial read out to the main program loop and see how things go.

It may not be the only issue with your code.  But it is the most obvious and explains the undependable behavior.  I believe you will want to keep the serial read in the main loop.  Basically, you will want to  read the serial port, then pass the read data to the correct ESP instance. Then, I assume, you will keep repeating this pattern infinity.  So all this code would remain in the Arduino's loop() method.


text:
PWM Every Other Pin Doesn't Read
Scenario
I've plugged 6 pins from my RC receiver into my Arduino in order to read the incoming values.
Problem
I'm using Digital PWM~ pins 2-6. Oddly the Arduino only reads odd channels:
1480, 0, 1175, 0, 991, 0

I've that if I physically reverse the cables (2-7, 3-6, 4-5) going into the Arduino I get ALL values:
988, 983, 1511, 1174, 1490, 1487

I've found that if I go back to my initial pin setup and merely flip neighbors (2-3, 4-5, 6-7) that works as well.
Question
What could possibly be causing this?
Code
Here is the current code I've written

int ch1, ch2, ch3, ch4, ch5, ch6;
int ch1Pin = 2;
int ch2Pin = 3;
int ch3Pin = 4;
int ch4Pin = 5;
int ch5Pin = 6;
int ch6Pin = 7;

void setup() {
  pinMode(ch1Pin, INPUT);
  pinMode(ch2Pin, INPUT);
  pinMode(ch3Pin, INPUT);
  pinMode(ch4Pin, INPUT);
  pinMode(ch5Pin, INPUT);
  pinMode(ch6Pin, INPUT);

  Serial.begin(9600);
}

void loop() {
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);

  String p = (String)ch1;
  p += ", " + (String)ch2;
  p += ", " + (String)ch3;
  p += ", " + (String)ch4;
  p += ", " + (String)ch5;
  p += ", " + (String)ch6;
  Serial.println(p);

//  delay(100);
}

Photo

EDIT
Since posting this question I've found that reversing the chXpin values accomplishes the same effect as reversing the physical pins. This makes me thing it's a software issue so I'm digging in further.
TEMPORARY SOLUTION
I'm not sure why this works but flipping the neighbor order of pulseIn fixed the issue:
  /* OLD
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  */

  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);

Why did that work? It makes no sense to me.

As a matter of course, not that it's related to your current issue, but your use of the String class at the end of loop is terribly wasteful and the over-use of the + operator on memory limited systems like an Arduino is known to lead to crashes.  There's no reason to assemble that all into a single string to send it.  You could just use back to back Serial.print lines and you would use a lot less memory.  Probably not an issue on this little test code, but as you advance that one will get you into trouble later.

pulseIn() is a blocking function: it waits until it gets a complete
pulse, or until it times out. While it's waiting, the Arduino cannot do
anything else, and it will miss pulses on other channels.
The RC receiver sends the pulses sequentially. Then, if you try to read
them in the right sequence, it may work. If you read them out of
sequence, you will miss some pulses, and the corresponding pulseIn()
calls can timeout, returning zeros.
For this kind of job I would use the pin change interrupt on pins 2 – 7.
This should allow reading the six pulses continuously without blocking
the whole program. But it's low-level (AVR-level) programming, probably
not doable with the standard Arduino libraries.
Edit: Here is what I had in mind when suggesting the use of the pin
change interrupt. Notice that the pin numbers are “hardwired” into the
code and cannot be changed easily. This is because:

Pins 2 – 7 share a single pin change interrupt request
(PCINT2_vect), thus a single ISR is needed to time the six channels.
They also share a port (port D), meaning they can all be read by the
ISR in a single instruction.

The other possible choices having these nice properties would be pins
8 – 13 (PCINT0_vect, port B) or A0 – A5
(PCINT1_vect, port C).
/*
 * Read 6 PWM signals from an RC receiver.
 *
 * Channels 0-5 are on digital pins 2-7 (i.e. PD2-PD7 = PCINT18-23).
 */

// This always contains the last length measured on each channel.
volatile uint16_t last_pulse_lengths[6];

// Interrupt triggered on every change in pins 2-7.
ISR(PCINT2_vect)
{
    static uint8_t last_pin_states;
    static uint16_t start_times[6];  // start time for each channel
    uint8_t pin_states = PIND >> 2;  // shifted to bits 0-5
    uint16_t now = micros();

    // Check every changed bit of the port.
    for (int i = 0; i < 6; i++) {
        uint8_t mask = _BV(i);

        // Record start time on rising edge.
        if ((pin_states & mask) && !(last_pin_states & mask))
            start_times[i] = now;

        // Record pulse length on falling edge.
        if (!(pin_states & mask) && (last_pin_states & mask))
            last_pulse_lengths[i] = now - start_times[i];
    }
    last_pin_states = pin_states;
}

// Return the pulse lengths avoiding race conditions.
static void get_pulse_lengths(uint16_t lengths[6])
{
    for (int i = 0; i < 6; i++) {
        noInterrupts();
        uint16_t tmp = last_pulse_lengths[i];
        interrupts();
        lengths[i] = tmp;
    }
}

void setup()
{
    // Setup the pin change interrupt.
    PCIFR  = _BV(PCIF2);  // clear pin change interrupt flag
    PCICR  = _BV(PCIE2);  // enable pin change interrupt
    PCMSK2 = 0xfc;        // sense changes on pins 2-7 (i.e. PD2-PD7)

    Serial.begin(9600);
}

void loop()
{
    // Report the pulse lengths on the serial console.
    uint16_t pulse_lengths[6];
    get_pulse_lengths(pulse_lengths);
    for (int i = 0; i < 6; i++) {
        Serial.print(pulse_lengths[i]);
        if (i < 5) Serial.print(", ");
        else Serial.println();
    }

    delay(1000);
}

Would this sort of integration count? http://playground.arduino.cc/Main/PinChangeInterrupt

The code you linked to sets individual bits in PCMSKn, PCIFR and PCICR, and it defines the ISR(PCINTn_vect). This is exactly the kind of “low-level” programming I was talking about. Note that if using pins 2 – 7, you only need to set one PCMSK (namely PCMSK2) and only define ISR(PCINT2_vect).

I see you added example code afterward, I must have missed it the first time. I plugged it in and it worked with my RC flawlessly the first time. I modified the delay from 1000 to 10 and that's it. This answer deserves more than the +1 I already gave it.