text:
Mega 2560 & smoking/burning 5v requlator, probable cause?
Problem: board seriously fried.
Desired outcome: measures to take in future.
Background:
This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion.  It sits on a shelf with others of the same ilk.  Nothing is touched unless I need to plug in USB cable for update.
The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds [normally off, used to flag specific conditions, each in series with 470 ohm resistor.
The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.
Steps leading to failure:
Plugged in USB cable [no other physical changes, nothing else touched, power jack remained connected]. went to Arduino s/w to make minor changes, would not upload to Arduino.  While scratching my head, smelled something burning, then saw smoke coming from the shelf.
Post failure:
Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary.
Visual wiring inspection revealed no obvious problems.
Input to power jack measured at 10.06v.
Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port [just in case of ?, seen ancedotal posts of possible conflict; a clone after all].  Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in.
Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.
Seeking:
Words of wisdom from others far more knowledgeable and experienced than I.
Could the dual connection of USB and power jack, be the root cause?  Never experienced this with UNO clones.
I do not want to put more boards at risk in the future.

Maybe they tried to save a few cents and not include the the opamp and mosfet, that would turn of usb-power if the jack is present. I think what happened, is that the mega was trying to supply 5V back into the USB port, back into your PC. This would happen if the 5V of your PC is below the 5V the regulator is supplying. Just don't plug in both at the same time, seems like a good solution. Other that reverse engineering the clone, and see what's different from the original.

You said it yourself: a clone after all...

Sometimes the big decoupling caps you put around the regulator have a low voltage limit on clones; I have seen board with a grilled cap. If regulator is also a cheap brand, not up to specs, then you are at risk. The first wise thing to do is to buy genuine boards.

It could be the board, but don't assume it is - could also be a problem like a hot ground or excessive ripple with your power supply or even your computer.

I suggest pulling out your multimeter and measure that you don't have a short between 5V & GND and 3V & GND. I also suggest checking these 10 possible causes: http://ruggedcircuits.com/html/ancp01.html

The "rugged circuits" page is in my reference library, and I had read it. It is good that you mentioned it because I had intended to, but did not. Including the reference may be beneficial to others reading this posting.

They are using the same SOT223 LDO as every other product.  These have a very low limit of output current when run from an input voltage such as 12V.  If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant).  The PDF linked below shows a comparison between the LDO and drop in switcher.  Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.
https://www.sugarsync.com/pf/D3258881_07979653_7526812


text:
Interrupt routine for button somehow respondng to room lamp turning off and on
I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.
Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].
The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.
I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.
The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.
What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]
I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

Long wires to your switch, missing pullup/down resistor are possible causes of sensitivity to electrical activity near by. Polling a switch rather than triggering an interrupt is more usual.

Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

Conducted EMI through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).
Radiated EMI (most likely). There are some things you can do to mitigate its effects:

Use wires as short as possible.
Twist wire pairs whenever possible.
Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this this. You'll have a better grasp about the art of debouncing inputs.
SPOILER: One thing you can do to make your debouncing routine far more robust is to wait for N consecutive readings with the same value (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.

Thank you, very informative.   I'm sure I can handle it from here.
As a note, I used battery power and experienced the same problem, as you predicted.  I also noticed that actually disconnecting the switch has no effect as long as the lead wires [ about 12"] are still in place.  I can easily change the configuration and shorten them considerably.

My guess: pickup on the input line from interference.  (I'd expect this more if the switch were on a long cable away from the Arduino.)
If the button uses an external pull-up resistor, try a smaller value (maybe 5k?).  If it uses the internal pull-up, try adding an external one.

source: Stack Exchange

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

sort: votes


text:
GPS logging on the intel edison breakout board
I'm working on my project car, and I have decided I would like to have a GPS and log some sensors too. I'm just at a bottle neck here, the sensors I have brought pull about 7v each where I can't pull that much from the breakout board that I have, and I can't seam to get the GPS to work.
I've tried using ths code but software serial isn't supported on the edison:
// GPS Setup
#define rxGPS 0
#define txGPS 1
SoftwareSerial serialGPS = SoftwareSerial(rxGPS, txGPS);
String stringGPS = "";

void setup() {
  pinMode(rxGPS, INPUT);
  pinMode(txGPS, OUTPUT);

  Serial.begin(9600);
  Serial.println("Started");

  // GPS Setup
  serialGPS.begin(4800);
  digitalWrite(txGPS,HIGH);

  // Cut first gibberish
  while(serialGPS.available())
    if (serialGPS.read() == '\r')
      break;
}

void loop()
{
  String s = checkGPS();
  if(s && s.substring(0, 6) == "$GPGGA")
  {
    Serial.println(s);
  }
}

// Check GPS and returns string if full line recorded, else false
String checkGPS()
{
  if (serialGPS.available())
  {
    char c = serialGPS.read();
    if (c != '\n' && c != '\r')
    {
      stringGPS  = c;
    }
    else
    {
      if (stringGPS != "")
      {
        String tmp = stringGPS;
        stringGPS = "";
        return tmp;
      }
    }
  }
  return false;
}

Any ideas or help would be much appreciated

You might try my NeoGPS library.  It has a diagostic program and some good information in the Troubleshooting section.  And NeoGPS doesn't use the String class, although you can safely waste lots of RAM on the Edison.  :P
For an Edison build, you may have to change the PACKED_DATA configuration item, described here.
(This is an Arduino product, right?)

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


text:
Hot regulator 7.7V Vin @ 135mA
Sorry folks, I understand this question has been asked quite few times, but I wasn't able to find a definitive answer: my Mega 2560 R3 is powered by 7.7V from Vin, and runs at a steady 135mA (in theory it's 2.7 x 0.135 = 0.38W dissipation). But the regulator with a heat sink still gets hot. Not burning hot but definitely to a point where you'd question whether it's a good idea to leave it running for months.Is this normal? Also is this a sustainable plan for a long running project?The 7.7V (7.7 because I remember the regulator needs a voltage around that to work) is coming from a variable step down module that could deliver a 5V. However I've noticed although it does stabilize at 5V , when the power just comes on it would surge to ~9V for a fraction of a second. My understanding is the 5V input on arduino is assuming clean 5V, so I hesitated there. Any suggestions? Thanks!

That is indeed odd.  How you you measuring the power consumption?  Is there anything else connected to the board?  If you hold the processor in reset, does the regulator remain cool?   How did you measure the 9v spike? It is entirely possible that it is real, but many meters have an "overshoot" in their response to step input changes, so it could also merely be an artifact of how your were measuring.  A storage scope would be useful, but obviously even today costs a few hundred dollars.

5V connects Vin, Gnd connects to multimeter, meter connects to negative. Current fluctuates a bit around 135mA but never goes over 140. For the voltage, the buck converter has a display that tells the output voltage, and it'd show ~9V and then quickly goes down to 5V. You could be right that it's overshooting but again it's a cheap ebay item..

@ChrisStratton The board is driving a GPS module and 10 basic logic chips of various kind, but the current meter should measure all these combined, and I think 140mA is still in the acceptable range of a mega, no?

Using a multimeter to measure current directly is a bad idea. Get a very low value shunt resistor and measure the voltage across it instead,

If you have any communications cables connected which have their own grounds, trying to measure current in the power ground path will be inaccurate anyway, since those grounds may be lower impedance than the one going through the meter's burden voltage.  You really need to unplug everything that unplugs in the way of peripherals and cables and test just the board by itself, both with the chip in reset and running.  Then add things back one by one.

@IgnacioVazquez-Abrams what's wrong with the shunt resistor that is already present in the multimeter?

@Gerben: In the milliampere ranges the resistance is far too high, leading to a not-insignificant burden voltage.

@IgnacioVazquez-Abrams e.g the fluke 83 uses a 1Ohm resistor in the mA range. That will only give a drop of 0.135V. I don't get it. How is this not-insignificant?


text:
How do I interface two Arduino boards so they act as one with double the code space?
Can I connect two ARDUINO UNO circuit boards in serial to increase room for more code and more functionality. For instance I wish to connect six sensors to a board. I need code for all six sensors and there is not enough space on one board. If I connect two circuit boards in serial will that provide the space and functionality to run the code for all six sensors.
If not how is this accomplished? I am a beginner with ARDUINO and I have been assigned a big task to make the ARDUINO UNO circuit boards provide six different functions using sensors such as temperature, pressure, humidity, voltage, current and possibly other functions. I am new at this.

You don't.   Two Unos do not equal a Mega (or a cheaper ARM Cortex with a reasonable amount of resources).  With some care you can probably fit everything you just described in the Uno's ATmega328p, but the ground rules of the assignment really need to be called into question, as unless there is closet full of hardware that is already paid for it is likely they were written by someone ill-informed.

It would probably be easier to optimize your code so that it fits. Reading six sensors doesn't sound too complex for an Uno.

There is no simple way to combine multiple boards into a unified system. What you will need to do is delegate certain tasks to each board and then have them communicate via SPI, I2C, or UART between a master board and each slave board in the system. The master system will then present the interface of the system as a whole via serial, wifi, console, etc.

If you're doing something that exceeds the resources of an UNO, then one simple next step would be to try a MEGA.  It is similar enough to the UNO that porting should be trivial, but has more RAM, more flash, and more I/O ports than two UNO units combined.


text:
Can't use base class and derived class functions
I have made two libraries and one test program.I have made my custom uart library.first i have included all functions for printing in single uart library file.but then i have made print library for printing functions only.my files are listed below.i have not posted my code directly so it can be read separately.
uart.h
uart.cpp
print.h
print.cpp

Test.cpp

#include <avr/io.h>
#include "uart.h"

int main(){
    uart.start(9600);
    uart.print("Test");
}

and i get this error..

Error

src/print.cpp
src/print.cpp: In member function 'void PrintClass::print(unsigned char)':
src/print.cpp:4:12: error: 'write' was not declared in this scope
write(data);
          ^
src/print.cpp: In member function 'void PrintClass::print(char*)':
src/print.cpp:13:22: error: 'write' was not declared in this scope
write(string[index]);
                   ^
.build/uno/Makefile:47: recipe for target '.build/uno/src/print.o' failed make: *** [.build/uno/src/print.o] Error 1
Make failed with code 2

i have referred default arduino libraries like hardwareSerial and LiquidCrystal and i made my library like that but i cant get rid of that.
Please Help me.

Any functions that the base class needs to call that will be defined in the child class must also be defined in the base class.  They should be defined "virtual" so they can be overridden, and can even be "pure virtual" so they have to be defined in the child class.
So for any function in the child class that the base class needs to access, add this to the base class's definition (print.h):
virtual void write(unsigned char data) = 0;

The = 0 bit defines it as pure virtual, and any classes than inherit this class without defining their own copy of the void write(unsigned char) function will thrown an error.
Instead of pure virtual you can provide a default function that a child can override if they want to, which can be useful if most classes will work the same way (define it in the parent) but some want to do it differently (override it in the child), in which case you treat it like a normal class function but add the virtual tag.
The whole topic is called polymorphism and is an incredibly powerful system.  It's discussed in detail here: http://www.cplusplus.com/doc/tutorial/polymorphism/

if you dont mind,can you explain with my code..please

All you should need is the one line of code I show there - add it to print.h

I dont know how can i thank you.thank you for helping again. :) .


text:
How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?
I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]
Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

in extended ascii, degree '°' is DEC 248 per  http://www.theasciicode.com.ar/   DEC 167 looks a lot like a degree sign, but it is a 'masculine ordinal indicator'   see https://en.wikipedia.org/wiki/Ordinal_indicator

The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --
For the U+00B0 degree symbol, you'd send the bytes UTF8 0xC2 0xB0 like this:
Serial.print("°");

authors: امیرحسین محمدصالحی


text:
Known conflicts between use of HC-12 and Ethernet Shield on Mega2560?
I have two somewhat similar sketches that use both HC-12 [for data collection] and a W5100-type Ethernet Shield [for Email construction and transmit].
Both sketches run fine until the code for the Ethernet Shield is invoked, which creates a connection and successfully transmits an Email.
Once this happens, the HC-12 no longer receives transmits.  No exceptions are raised, and I am at a loss to determine the cause of the problem.
[The HC-12 is using pins 50-52.]
I have other sketches that use either the HC-12 or the Ethernet Shield, and they work fine.  Before I build a custom sketch to attempt problem isolation,
I thought I would simply ask the question of whether known conflicts exist.  I know that many questions are resolved by posting the sketch and someone other
than the author scanning it.  I think that impractical in this particular case.  The sketch comprises 6,000+ lines of code.
If no helpful responses are forthcoming, I will continue with problem isolation, and post again if no success is achieved.

I'm voting to close this question as off-topic because it is unanswerable without further details, especially which pins the Ethernet shield is using and the interaction between the software attempting to use each.  For that matter, it's bad form to mention something obscure like the HC12 and not explain what it is and what the utilized pins do.

Are you using SoftwareSerial on GPIO pins instead of using one of the three hardware UART ports?

@Majenko I am using SoftwareSerial simply because I started on an Uno, and didn't/don't know any better.   Bad idea, I guess? I've little experience with Mega2560, and none with the hardware UART ports.
I selected pins 50-52 for the HC-12, because I thought they were free, as the Ethernet shield plugs into pins 10-13.  However, my recent reading implies that the Ethernet code references 50-53 anyway, though I don't understand how.  If so, this certainly would be a source of conflict.  Perhaps this is the point you are leading up to?
In any case, i think I now have an avenue to pursue.

I have a feeling (though I am not sure, I'd have to check) you happened to pick the SPI pins which the Ethernet shield uses (through the ICSP header). Never use SoftwareSerial unless you absolutely have to (and you don't - you have Serial1, Serial2, etc available).

One thing I know for sure about the HC-12 is that you need to have an external power supply capable of giving it about 200 mA just for it.  Plus another 350 for the board, and some more for the shield.  I suspect the shield being activated is making the current drop below what the HC-12 needs to operate.  Can you give it a better power supply then come back and give us an update?

As suggested by Majenko, the problem results from using Software Serial for the HC-12, and unfortunately choosing the pin set 50-52, which conflicts with the pin usage specification for the Ethercard Library.
Hence, the HC-12 code works fine until usage of the Ethernet shield is finally activated.  From that point on, the Ethernet code functions properly,  whilst the HC-12 code does not.  The recommended solution, which does indeed solve the problem, is to abandon usage of SoftwareSerial for the HC-12, and use Serial1, or Serial2, or Serial3 instead.
I do not feel that the solution to the problem is truly mine, but post it only that the information may be of subsequent use to a user encountering a problem of similar nature.


text:
Free simulation software for arduino hardware
Hi there i am a beginner and trying to pair some sensors with my arduino. I am looking for some software which will allow me to test my codes in virtual machine also it should be free ...thax in advance


text:
How to simulate Arduino?
QUCS is the only open source software which offers simulation (and designing PCB layout [in future]) of electrical circuits. But the problem with QUCS is that it is under development and many important features are not yet available in it.
I want to simulate Arduino Uno board in it for my circuit. Does anyone know how to simulate Arduino or any other micro-controller in it?
P.S. Also any other open source software for simulation and PCB designing?

Oshonsoft have a great AVR simulator. You will be hard-pushed to find an open source Arduino board simulator - especially as the board is nothing more than a crystal, power supply and user-friendly connectors. Hence the need for something that simulates the microcontroller at the specific board's core. The Oshonsoft simulator has almost everything you need to test code, and includes a full list of all registers and their values, viewable instruction by instruction. It's not free, but (in my view) the best you can get for your money.

I think Labcenter Proteus is the best option to simulate an Arduino with miscellaneous Digital & Analog circutry so far...

I'm confused this (wrong) answer is not corrected. KiCAD is mature open source EDA, with circuit simulator (SPICE) and pretty decent library of components - so you are not limited to passive circuits.

Simulating a microcontroller's program is common, but not as part of a circuit, unless you're into Systems on Chips.
Model the micro interfaces and simulate the peripherals separately
Analog systems cannot be modelled accurately by hand calculations alone, therefore simulation is often a necessary step (on top of that, real circuits might behave differently from the model). Non-programmable digital systems are deterministic in their behaviour, but only if the interfaces are correct - tight specifications on impedances and such often mean simulation is required here as well. Generally speaking, for both simulation becomes a must when the system is not dead simple. Microcontrollers on the other hand are sufficiently deterministic not to require any simulation: they do what they're told, except in very very very rare cases (single event upsets from radiation for example). Now, what they're told might allow glitches to happen, but that's a different story*. Therefore, usually the analog, or digital circuits around a microcontroller would be given equivalent interfaces based on the microcontroller's behaviour and physical specifications, and simulated separately.
*: As the code becomes more and more complex, it gets more and more difficult to follow what the microcontroller might do. Unexpected glitches may arise from e.g. concurrent access (though I can't say this is common in the micro realm), or insufficient resources (that is why dynamic allocation [malloc,new] are highly discouraged, so that the resources allocation is known at compilation time) etc. That's usually why tests are required, and step-by-step debugging is used as a means to locate any error that arises. But inherently, microcontrollers are highly predictable and except in certain cases, it is not worth it to go through simulation (do not mix up simulations and tests, tests are always required!).
Advantages of microcontroller simulators
However, microcontrollers simulators do exist. They are particularly helpful to watch what happens inside the microcontroller when the code executes step by step: call stack, watches on variables, interrupt vectors etc. This can also be done on the actual hardware using in circuit debuggers, but simulators are cheaper and are also good to save on EEPROM erase/write cycles and to avoid damaging your micro if you are afraid that the devices around it might be incorrectly configured (some controllers are very expensive, especially if they are qualified for medical, military or aerospace applications). I have seen such ICD's and simulators for Microchip PICs (MPLABX), but there must be equivalents for AVR (the micro which is on the Arduino's), or perhaps even integrated in an arduino-friendly environment (though I doubt it). You might want to take a look here.
If you've got deep pockets: mixed signal simulators
Finally, there are mixed signal simulators which allow you to simulate analog, programmable and non-programmable digital circuits alike; one component will have an analog SPICE model, another a VHDL model, and ADC/DAC blocks will be added automatically by the simulator between those devices depending on the logic input/output technology you specify. Those are extremely expensive (the one I used is Cadence Virtuoso), you don't want to do that unless you're doing an integrated circuit or something critical.
P.S: DesignSpark PCB v3 has LTspice in it. Never tried that feature in there though, I used to use LTspice directly.
Note that your opening "QUCS is the only open source software [...]" is wrong. There are plenty of simulators out there which are open source. I agree QUCS is a very user-friendly one though.

Downvoted for opening your answer by lambasting the user for not knowing stuff.

Fair enough then. I'm not sure I agree that "Microcontrollers on the other hand are sufficiently deterministic not to require any simulation", though - programs are deterministic, but we still test them.

Gets a +1 from me, then. :)

You can use 123d.circuits.io for simulation and PCB design for Arduino circuits.
See this one for example.
More generally, a previous answer states that Microcontroller based circuits are not simulated. Maybe that's true when prototyping costs are low (though I doubt it), but in an SoC or complex embedded system, microcontrollers certainly are simulated as part of the overall system.
Sometimes as a highlevel model such as a symbolic simulator or sometimes as a part of the overall mixed-signal simulation environment in which the digital part is usually simulated at RT level.

How to simulate Arduino? What is the best Arduino simulator?
Following are the main features of the Wokwi Arduino simulator:

It is free :)
Supports multiple file projects
Supports most of the famous Arduino libraries
Whatever compiles on the Arduino IDE will compile on the simulator
Supported by all browsers
Compiles with latest Arduino IDE
Supports FastLED and many other peripherals
No download or installation needed
Easy to share the code and project with just a single click
Smart - Code Autocompletion, Code auto-formatting are supported
Provides standard library demo examples
Project can be compiled on RUN on Mobile browsers as well
Tries to be closer to real circuits – Example – Button bounce like in real hardware
Supports Arduino Mega, Arduino Nano, Arduino UNO, ATtiny85
Supports assembly instruction execution
Provides LED power and FPS features for FastLED projects
Supports a plethora of Arduino peripherals for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more
Serial monitor is supported as well

Website: https://wokwi.com

Here are a few examples

To add to the list of simulator answers, try out Micro-Cap 12. It was a few thousand dollars originally, but the company has ceased operations now and has provided it for free. Pretty cool.

Try this: simulIDE
Google: simulIDE for arduino picture
Supports also: PIC, ATtiny, ATR, Arduino...

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


text:
is any windows application available for accelerometer based computer mouse
I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

try "remotemouse.exe"
its a open source application you can modify the codes according to your requirement


text:
is any windows application available for accelerometer based computer mouse
I want to make an AIR mouse using Arduino
and accelerometer, for this i used USB to TTL
converter i have done everything successfully
but can anyone tell me how use it in computer.
I mean i don't know how to make computer
application for this mouse. please suggest me
any application for this. And give any idea for
"how can i use Bluetooth for this."


text:
Choosing wireless tech for lowest possible lag
I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.
I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.
SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):

Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device
Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry
RF data tranceiver
Pros: dunno, cost seems to be a bit smaller
Cons: multiple buttons at the same frequency will probably create a lot of noise
Simplest "Radio remote"
Pros: zero lag since it's all electromechanical, no data
Cons: multiple buttons at the same frequency won't work

So, did I miss anything? I appreciate any guidance.

How many buttons in total?

The smallest possible requirement is 4, the normal case is 8, anything more would be welcome - I'd like it to be very flexible for some crowd entertainment.

@user31481 So what? Humans can perceive latency under 2ms. See links in the appendix: https://danluu.com/input-lag/

I've used NRF24L01+ chipset 2.4GHz wireless modules with Arduino before, and found them to be great, and super cheap (~$10 for 10 of them on ebay!). They have 3 modes of transmission: 250kbps, 1Mbps, and 2Mbps. The range decreases accordingly with higher bitrate, but the time spent sending a message does too. There are multiple Arduino libraries (e.g. RF24, Mirf, RadioHead) and tutorials for using the modules (see http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01). They also have built-in mesh networking modes which may or may not be of use.
Versions with an RP-SMA antenna connector and an advertised range of up to 1000m are also available for about $5 each. I would recommend using one of these for the referee's button at least, depending on the range you need.
According to Charles Hallard of hallard.me, The non-amplified chips can get 30m line-of-sight range in 250kbps mode, and I have verified this in my own testing.
According to user sporadic on diychristmas.org, sending a 32 byte payload in 250kbps mode takes 1432µs from the start of Tx mode on the transmitter to receiving the full message on receiver. This decreases to 444µs on 1Mbps mode and 283µs on 2Mbps mode.
Given these statistics, they fall well within 2ms latency for triggering, suitable for your application, and they use very little power. It's up to you to work out the best balance of latency, range and expense.

Thank you! What if multiple buttons are pressed at the same time? Will they collide and eg block each other out?

No, the networking of these chips is very sophisticated for their price, they can negotiate mesh networks and multiple Rx pipes at once happily, and automatically resend if the receiver doesn't acknowledge receipt of a message.

This EE.SE question details how you can have multiple nodes transmit to the same receive address, as in your situation. Then it's simply a matter of taking the sender's address to decide who 'won'.

More helpful examples: http://arduino-info.wikispaces.com/nRF24L01-RF24-Examples

Just a little heads up, those NRF24L01+ chips with antennas are not original, it might cause issues when you try to communicate between clone and original and if you try to use dynamic payloads or shockburst. Also, that wikispace article is outdated. One should use TMRh20 library instead.

Have you considered using real time clocks? You could synchornise them all ahead of time and then use any wireless protocol. Once a button is pressed, you'll look for the unit that reports the earliest time stamp and then once a window of a few seconds has passed let it know that it won. I'd consider using WIFI (802.11) with ESP8266s, RTCs and take a wireless access point along.
This isn't an answer to low lag wireless but eliminates the need for it.

Using millis() for this may cause the devices to lose sync, as millis() does not increment when interrupts are disabled.

In my humble opinion it might be even cheaper if you use IR or some other type of light, assuming you can ensure line of sight.
You can use different wavelengths to ensure separation of the signals.

I'm afraid that "line of sight" and "pub quiz" don't go well together. But thanks for suggesting it, I will look into IR tech for other projects.

Low low tech solution.

The transmitter sends out its clock signal on command.
The receiver just needs to detect detect the prrsence of that signal.

The whole thing can be rf, or light based - for example one of the led lights can be configured as the transmitter.
Everything should be well within 1ms.


text:
Where are RX and TX pins on the GT2560?
I'm adding WiFi (ESP8266) to my GT2560 board. Does anyone know where on the board are the RX and TX pins and the best place to connect to them?
This is all, no more info on the board in the internet and forums: https://www.geeetech.com/Documents/Users%20Manual%20of%20GT2560.pdf

Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this download link for the schematics on this forum page.
Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.
The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

R3 between ATmega Tx -> FT232 Rx
R13 between ATmega Rx <- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.
I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

(original image source)

best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first disconnect them from the on-board FT232, to avoid contention and so the ESP8266 replaces the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)
One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites (example) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.


text:
Arduino RGB component identification

Can someone help me identify this component?
Thanks in advance.

What is the purpose of identifying this product? Do you want to purchase one? Are you after the identification of the individual components or are you wanting the identity of the board?

It's an RGB led... connect GND to ground/0V and R, G or B to 5V to make the LED light up in that color?

It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.

authors: Николай Сулима


text:
How to setup an I2C bus which stays valid if a slave is powered down or fails?
I have setup an I2C bus between 3 Arduinos (Master, Slave1 and Slave2) by connecting all 3 A4 pins together, all 3 A5 pins together and one GND pin of each Arduino to a common ground line. The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.
The slaves use the Wire library: Slave1 is at address 0x07 and Slave2 at 0x08. The Master uses the I2C library by Wayne Truchsess, because this library has timeout functionality. Master polls Slave1 and 100 ms later, polls Slave2. If either Slave is unavailable, Master should still read the other Slave (this is why Master doesn't work with the Wire library).
However, even though Master doesn't get locked-up, it can't read one Slave if the other gets powered down but left connected. If I cut the power of Slave1, Master becomes unable to read data from Slave2 until I physically disconnect Slave1. If I disconnect Slave1, Master is immediately able to read from Slave2 again. I2C scanning suggests the whole bus becomes invalid when a Slave is powered down (SCL and/or SDA turned low?).
From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.
P.S.: I have very little background in electronics and English is not my first language.

From what I have been reading, this is not a software issue but an
  electronics circuitry problem: leaking current related to Slave1 and
  Slave2 having some diodes, something that perhaps could be solved with
  some transistors or N-FETs which would act like check-valves? Please
  advise.

A nice solution to this problem is to use I2C Bus Isolation with TI TCA4311A Hot Swappable 2-Wire Bus Buffers alt. Analog Devices ADUM1250.
Please see the EEVblog Electronics Community Forum for further details and discussion.
Cheers!

That was the forum where I saw the "diodes" issue. I tried to draw an schematic of how I understood things should be wired, but I don't know what to connect to the VCC of the hot swap chip. A4 and A5 are the I2C pins of arduinos and D6 would be a pin I could use to drive the hot swap. Could you take a look? http://www.schematics.com/project/test-44785/

Please see fig. 11, pp. 13, for correct wiring of hot-spot; http://www.ti.com/lit/ds/symlink/tca4311a.pdf

Thank you! It makes sense. Two more questions: 1) what is BD_SEL? 2) can the VCC of the backplane simply be a 5V regulated output from the Master Arduino?

Ah, another question: in the drawing, there is a branch called "Card enable/disable". That is a pin in the slave arduino which would be always set HIGH by the slave's firmware so that a failure would automatically disable that slave, right?

The ADUM1250 might be easier to understand and use. Please see the Application Note; http://www.analog.com/media/en/technical-documentation/application-notes/AN_913.pdf. This is very straight forward.

The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.
Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.

I am powering the slaves down to simulate failures. A slave may fail even if the rest of the system keeps working.

That's not a good model of a recoverable failure, as it imposes an unrecoverable electrical fault.  Holding a slave in reset, especially if you can trigger it mid-transfer might be.  Or put the failure simulations in the firmware of the slaves.

Indeed, but since the slaves are sensor modules that can be hard-reset in seconds and measure data for R&D, I thought I could treat all failures as unrecoverable. If I hard-reset the sensors, they do not lose calibration, and I thought later I could add relays for automatic hard-resetting. Is that a bad idea?

Mikael has the correct answer above.
I had this same issue when using two Megas communicating over I2C, along with other items running on the I2C bus. I needed the system to continue running if one Mega went down due to loss of power. The other Mega should detect it and execute some abort commands for my mission.
Initially I wired the Megas up on the same I2C bus, just as I would any other device. When I unplugged one Mega, the other would freeze the next time it tried to address another device on the bus.
The solution was to use a hot-swappable I2C buffer. I used this one, and everything worked immediately without issue after wiring it up: http://www.mouser.com/search/ProductDetail.aspx?r=595-TCA4311ADR
To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used an adapter from Adafruit.
Cheers and good luck
Chris
High Altitude Photography Platform 360 video from a jet-stabilized platform at the edge of space http://hialtphoto.blogspot.com
Facebook @hialtphoto

An I2C bus should use open drain lines or open collector drivers AND there should be only 1 (one) pull up resistor for each of the 2 I2C wires.  In this way, should a slave fail, it will not effect the I2C bus.
An Arduino does not truly have an open collector driven pin.  Instead people have been clever and either set the pin connected to an I2C line low pulling the I2C bus low or as an input allowing the I2C bus to float high through the pull up resistor. In this way multiple I2C devices (Arduino or not) can share the bus.
However, if you power down an Arduino, it can no longer operate in this manner.  In fact it will likely appear as a load or path to ground and effect the normal operation of the I2C bus.
In the end, I2C is designed for chips (usually) on the same board so that they can talk with one another.  It would follow that they are all powered off the same supply. It is an unlikely scenario for power to fail for only one device on the board.
Alternatives:
There are protocols designed to go between devices (as in separately located and separately powered).  RS485 is one such protocol and has been around for years.  A quick search show both sheilds made specifically for Arduinos as well as tutorials using generic RS485 interfaces.

Thanks for the response. As I said, I lack the necessary background so I am going to have to ask further stupid questions: "to drive an open collector configure transistor" -> what does that mean? A transistor has 3 terminals, right? What goes where? Would it be 1 transistor for every slave as an intermediate between the slave and which I2C wire? Would any transistor do the trick?

I think it would be difficult to design an I2C buffer that would  not inhibit the bus if it lost power.  I tried to describe one in the answer.  But w/o electrical experience, I think it would be difficult.  Also, it is an unlikely scenario given I2C devices are expected to be co-located on the same board.  So I offered up RS485 as an alternative in the answer.

RS485 is a good tip and I found that MAX485 chip being sold in my country! "transmit on one pin and receive on another" -> so if I only have 2 slaves and a lot of unused pins in the Master, would the SoftwareSerial library be a simple solution, instead of trying to use I2C? Like, using D7 and D8 as RX and TX for Slave1 and D5/D6 for Slave2?

This theory is simply wrong.  It appears based on guesses that were not checked but easily could have been, and as a result it only confuses readers without helping.  Please delete.

Agreed.  I was adding text based on the comments left by the O.P.  He appears to be happy.  Although he did not vote or accept my answer.  I'll edit it down to a normal stackexchange answer.

I couldn't vote because I didn't have enough points. Upvoted now

Appreciated.  (With enough points you can actually see the individual up/down counts.)  It is a difficult problem.  But, again, I2C is usually a bus which is on the same board as all the parts.  Its just not setup to (by its self) handle one part getting its power cut off.


text:
IDE avoiding math operation
I have no idea why this has been happening:
byte potenciometro = 0;int redpin=9;

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

void loop() {
int valor=analogRead(potenciometro);  delay(50);
Serial.println();
Serial.print(valor, DEC);

analogWrite(redpin,valor);   }

This code above has been working just fine. However, i understand the LEDs will work properly with intensities that range from 1 to 255, so i replaced this line
Serial.print(valor, DEC);

for this
    Serial.print((valor/700)*255, DEC);
and all that the IDE has been returning since then is 0 as console output.
i tried also just
Serial.print(valor/700, DEC);

and i get nothing but 0s
anyone?
my arduino is the UNO version.

Why are you dividing the value by 700? The potentiometer is not connected between GND and 5V (I suppose 3.3V)? If you have full scale values (0..1023) it's possible just divide the value by 4 to get result between 0 and 255.

In the C family of programming languages, the division operator (/),
when used with integer arguments, provides an integer division. You
get the integer quotient, and you can use % to get the remainder.
If you want a floating point division, then at least one of the
arguments should be a floating point number. E.g.:
Serial.print(valor / 700.0 * 255);

(the DEC argument is redundant). The final result is then truncated to
an integer before being passed to Serial.print().
A better option, which is outlined in dhimaspw's answer, is to do the
multiplication before the division. This way you avoid costly floating
point operations. If you do that, however, you should be careful about
overflows: valor*255 can be as big as 1023 × 255
= 260865, which is larger than the maximum value an int can store
(215−1 = 32767). You should then write
Serial.print(valor * 255L / 700);

where the L suffix forces the operation to be carried using long
integers.
The simplest solution, however, is to use the Arduino function map(),
which does essentially the same as above:
Serial.print(map(valor, 0, 700, 0, 255));

Serial.print(valor / 700.0f * 255); would work better. 700.0 is a double not a float and so by the rules of the c language that entire calculation is done as doubles. Adding that f in turns it into a float. On a low end microcontroller you really want to avoid doubles as much as possible, double operations are twice as slow as a floats and floats are slow enough already.

@Andrew: The OP is working on an Uno. A double is the same as a float on the AVRs.

That in this particular case the standards aren't followed and so it doesn't make a difference isn't a good justification for inefficient coding. Pressing 1 extra key is a small price for a good habit and portable efficient code.

Not meaning to nitpick but I'd just point out that mapping floats to doubles on the UNO is a software choice implemented in the gnu compilers, not hardware-driven at all as the hardware has no support for floating point. A different tool-set might well implement a different choice. So could a programmer using gnu for that matter, by defining an 'sfloat' (small- or single-precision float) object and its arithmetic operators.

Using Serial.print (xx,DEC) will give you a number on decimal base (round number). That's why your first code works
To solve this, you just simply change to
Serial.print((valor*255/700),4) //4 digits behind comma

i tried adding this before the analogWrite
valor=((valor*255/700),4);
but the intensity of the led remains fixed

AnalogWrite only receive round numbers.

This solution overflows for values over the 128 (analog read returns values 0..1023) and it doesn't really explain why valor/700 is zero or one if the value is greater or equals to 700


text:
How to use potentiometer data from slave to master Arduino?
I'm trying to make a game where i can use one Arduino as a controller (the controller is a potentiometer) and the other Arduino sending the signals to the computer. Im trying to figure out communication with two Arduino's so i would like to use two instead of one although using one would be logical and easier. Ive tried looking into I2C but cant seem to figure it out.

Why are you using 2 Arduinos? You could do all of this in just one Arduino.

Please also improve the formatting of your question.

Start by reading the potentiometer. Add a Wire request service function and that makes the Slave:
#include <Wire.h>

const uint8_t controllerAddress = 8;
const int controllerPin = A0;
volatile int controllerValue = 0;

void setup() {
  Wire.begin(controllerAddress);
  Wire.onRequest(requestEvent);
}

void loop() {
  int value = analogRead(controllerPin);
  noInterrupts();
    controllerValue = value;
  interrupts();
}

void requestEvent() {
  Wire.write((const uint8_t*) &controllerValue, sizeof(controllerValue));
}

This is minor update of the Arduino Wire Master Reader tutorial. The sketch for the Master is left as an exercise.
Cheers!

I would assign 'A0' to controllerPin instead of '0', to avoid any confusing with digital pins: const int controllerPin = A0;

Nice catch. I will fix that.


text:
Arduino Nano with CH340 reboots on OS X El Capitan
I installed OS X El Capitan beta on my Macbook. Now my Nano-sized Chinese Arduino operating on CH340 chip reboots the laptop when USB is unplugged. While plugged, it works fine, I can upload sketches and send/receive data via Serial.
I've tried reinstalling the CH340 driver and running the following command as per this solution and it didn't help:
sudo nvram boot-args="kext-dev-mode=1 rootless=0"

I appreciate any ideas...

If I may ask, how did you get the Arduino to be detected by the computer? Since I updated to El Capitan, I've been unable to get the Arduino detected on the computer.

@duci9y Frankly, I did nothing special. I just upgraded from Yosemite to El Capitan, plugged in my Arduino, did a bit of coding as normal, unplugged it and boom, my Mac reboots after about 3 seconds.

@duci9y It turns out I didn't have the latest Beta. I now updated to the latest and now my CH340-based Arduino doesn't get detected as well! :)

Ah… so we are at the same place now. I'll post a question about it, maybe someone would know.

There is a new signed driver for OS-X El Capitan and Yosemite. This is all you want.
http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
Open Terminal from Recovery mode
Run the command csrutil enable --without kext
Reboot
Install driver

helped me, thanks. First I ran csrutil disable and it worked, however I feel better with your suggestion because it doesn't disable Protection System

The command you ran only disables driver signing verification, which means OSX stops blocking it. If it is crashing it is likely to be either a bug in OSX, or a bug in the driver. My guess is it is a bug in the driver and you'll probably have to wait until they release an updated version that is compatible with El Capitan.

It turns out I didn't have the latest Beta. I now updated to the latest and now my CH340-based Arduino doesn't get detected at all! Pretty much in line with everyone else complaining all over internet.

If you have macOS High Sierra like mine 10.13.4
This is work for me
https://github.com/awangga/NFCReader


text:
Engine Speed Control Observation
I am using an Arduino Mega to control the speed of an internal combustion engine.
The speed is sensed via a Variable Reluctance Sensor (VRS) on the crankshaft. This signal is then converted into a 5V square wave which is feed into Interupt 2 (Pin 21) on the Arduino.
The flywheel of the engine, onto which the VRS is sensing has one tooth. Therefore one square wave blip (from 5v to 0V) as it is passing it and then back up to 5v. The interupt that this is attached to increases a counter by 1. The time taken for the counter to reach 20 is recorded. I want to use this speed reading value in a PID algorithm which then in turn actuates a servo.
This methodology was sucessfully used in a very similar engine with a 22 toothed flywheel but is not working on this engine with 1 tooth.
The problem is the speed reading - the values that I am recording for the time taken for 20 revs ( in micro seconds), and displayed on the serial terminal is wrong and I do not know why. The numbers printed are all mulitples of one another e.g. 440960,551200,661440,771680 which all divide into one another with an even fraction. The correct reading here is 661440, this has been verified with observation of the square wave input through and oscilloscope.
I cannot find why!
I have attached the code here

Why are you using an interrupt instead of Input Capture?

Are you suggesting using PulseIn?

Your methodology there is somewhat flawed. Not only will you never see that Counter1 >= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.
A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.
Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using millis()) and when a certain (to be decided by you) time has elapsed (the sample time) you record the pulse count and reset it to 0. You then have a number of rotations per time period.
If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.
void loop() {
    static uint32_t ts = millis();
    uint32_t pulses;

    if (millis() - ts >= 1000) {
        ts += 1000;
        uint8_t sr = SREG;
        noInterrupts();
        pulses = Counter1;
        Counter1 = 0;
        SREG = sr;
        Serial.print(pulses);
        Serial.println(" revolutions per second");
    }
}

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.


text:
Serial3.available loop issue
I am trying to read information coming from an Atlas Scientific FLO30 chip.
The following code works fine in an individual sketch:
String inputstring = "";                                                       //a string to hold incoming data from the PC
String sensorstring = "";                                                      //a string to hold the data from the Atlas Scientific product
String LPM="";
float LPM_INT;

boolean input_stringcomplete = false;                                          //have we received all the data from the PC
boolean sensor_stringcomplete = false;                                         //have we received all the data from the Atlas Scientific product
#define CIRC_PUMP_PIN 10 // circulation pump pin - high when on, low when off

unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change :
const long interval = 1000;

  void setup(){                                                                //set up the hardware
     Serial.begin(9600);                                                       //set baud rate for the hardware serial port_0 to 9600
     Serial3.begin(38400);                                                      //set baud rate for software serial port_3 to 9600
     inputstring.reserve(5);                                                   //set aside some bytes for receiving data from the PC
     sensorstring.reserve(30);                                                 //set aside some bytes for receiving data from Atlas Scientific product
     pinMode(CIRC_PUMP_PIN,OUTPUT);
     digitalWrite(CIRC_PUMP_PIN,HIGH);

void loop(){

unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

            if(Serial3.available()>0){
              while(sensor_stringcomplete==false){
        char inchar = (char)Serial3.read();                              //get the char we just received
              sensorstring += inchar;                                          //add it to the inputString
              Serial.println("adding to string");
            if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
             }
            }

 if (sensor_stringcomplete){                                                   //if a string from the Atlas Scientific product has been received in its entierty
      Serial.println(sensorstring);                                            //send that string to to the PC's serial monitor
      byte n = sensorstring.length();
      LPM = sensorstring.substring(n-8,n);
      Serial.print("This is the extracted part ");
      Serial.println(LPM);
      LPM_INT=LPM.toFloat();
      Serial.print("Now in float ");
      Serial.println(LPM_INT);
      LPM="";
      sensorstring = "";                                                       //clear the string:
      sensor_stringcomplete = false;                                           //reset the flag used to tell if we have received a completed string from the Atlas Scientific product
      }

      if(sensor_stringcomplete==false){
       Serial.println("Skipping");

      }
  }

      }

however when I try to integrate the code with another master sketch, the Arduino seems to jam or lockup when it enters the following part of the code, which is called periodically from the main void loop():
    if(Serial3.available()>0){
      while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read();                              //get the char we just received
      sensorstring += inchar;                                          //add it to the inputString
      Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
     }
        }

All the code is the same and I do not understand why the Arduino locks up. I intially thought it was a problem with memory as the master code is singificantly bigger but the line  "sensorstring = "";  " and "sensorstring.reserve(30) " should take care of this? Besides it cannot even get one reading from the sensor.
Can anyone give insight as to why this might be?

Firstly, don't use String.  It's wasteful of memory and the dynamic aspects of it don't sit well on a tiny resource-starved 8-bit microcontroller.
Secondly, your method of reading from the serial is flawed right from the start.
if(Serial3.available()>0){

... If there is at least 1 character available ...
while(sensor_stringcomplete==false){
    char inchar = (char)Serial3.read(); //get the char we just received
    sensorstring += inchar;     //add it to the inputString
    Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}

... read characters until I get the end of string character regardless of if those characters are even available.
In order to read the data from the serial port you have to ensure that the data is actually available.  Just waiting for the first character to arrive and then reading (much faster than the serial is able to receive) other characters is doomed to failure.
I have discussed this at great length in a blog article, including how to perform non-blocking string reads that will not interfere with the rest of your program: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
It even mentions your specific situation since it is something that is so commonly done wrong.

Thanks Majenko, interesting stuff. I thought it could be a problem like this. I have integrated this readline function into my master code and have placed: "  static char buffer[80];
if (readline(Serial3.read(), buffer, 80) > 0) {
Serial.print("You entered: >");
Serial.print(buffer);
Serial.println("<");
} " But now the there is nothing being printed on the Serial monitor, again the code works in solitary!

If the code works by itself, but doesn't work when integrated with your sketch, then there must be something else in your sketch that is stopping it.  Can you post your entire non-working sketch?

its too long for comments so Ill post it under the original!

Its too long to add!

Ok, so put it somewhere like PasteBin and provide a link.

MASTER Code:  http://pastebin.com/iiansA2n

Hmm, there is quite a lot there, isn't there?  I'd suggest commenting out everything in loop() except my serial code, then see if it works.  If it does then gradually uncomment each entry in loop() until it stops working.  Also you can reduce the 80 down to 30 in both the buffer and readline call.


text:
How do I run multiple vibration motors from an Arduino Mini with PWM?
I'm building a project for my Physical Computing class that involves 4 vibration motors for varied haptic feedback based on serial input via analogRead. I have each coming out of their own pin and assigned to conditionals.
I'm wondering:

how do i control the PWM of each individual motor?
assuming I need an external power source for the motors, do I need to have a diode and transistor in between each motor and the ground?

Thanks in advance - I'm still learning but definitely looking forward to taking Part II next semester!

https://www.arduino.cc/en/Reference/AnalogWrite

You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check here about more information on AnalogWrite, and here about Arduino Mini
This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

simulate this circuit – Schematic created using CircuitLab

Why specifically use a zener diode as a flyback? Can't a regular diode (granted it can handle the voltage) do the trick? Is there a specific advantage of using a zener diode over a normal diode?

Sure regular diode will also works, I didn't mention anything about specifically using zener diode

Hi - thanks for the help. I'm pretty solid on the physical routing now, at this point, its more the code I'm worried about. I'm guessing I can use an elseif statement? So for example if I have irPin1 = analogread(irVal1) to set the analogRead for the IR sensor I'm using, and then:
'    if (irVal1 < 400){
digitalWrite(vibePin1 = HIGH);
}
else(){
digitalWrite(vibePin1 = LOW);
}'

From there, how would I distribute PWM values to each sensor? I'm assuming that I'd be creating a pwmVal variable to store something? AnalogWrite(pwmVal = 30) or something like that? Assuming it goes 0-255.

dhimaspw, while you don't mention diode or zener diode in the text, item D in the diagram is a zener, as denoted by bends in the cathode line.  You could edit and substitute a plain diode with a straight line for cathode.

@jwpat7 as you suggested, I've change the circuit. Hope this doesn't cause any misunderstanding.

@Nick if there are new question, in my opinion you should post another question or edit the original instead of asking in comment section.


text:
loading custom code onto SparkFun Blynk Board
we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?
our code:
#include <Servo.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>
//#define BLYNK_PRINT Serial

char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
char ssid[] = "Linksys23266";
char pass[] = "roboboyz";

Servo servoR;
Servo servoL;

int pos = 90;

void forward()
{
  servoR.write(110);
  servoL.write(110);
}

void turnRight()
{
  servoR.write(80);
  servoL.write(90);
  delay (2000);
}

void turnLeft()
{
  servoR.write(90);
  servoL.write(80);
  delay(2000);
}

void reverse()
{
  servoR.write(70);
  servoL.write(70);
  delay(2000);
}

void Stop()
{
  servoR.write(94);
  servoL.write(94);
  delay(2000);
}

void setup()
{
  Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
  servoR.attach(12);
  servoL.attach(13);
  Serial.begin(9600);
  delay(1000);
}

BLYNK_WRITE(V1)
{
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);
  if(y>220)
  forward();
  else if(y<35)
  reverse();
  else if(x>220)
  turnRight();
  else if(x<35)
  turnLeft();
  else
  Stop();
}

void loop()
{
  Blynk.run();
}

Is this something I'd have to send serial from the Blynk Board of the Joystick X/Y over wifi to another microcontroller, like a Leonardo? How would I do that? Can you add "serial.write" into the blynk board to get that information?

do you really want your steering to travel thousands of miles instead of dozens of feet?

Functions aren't called voids. They are called functions.

That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.
Instead you will have to write a new firmware that contains all the code you need to do the entire job.

Technically all bootloaders prove this wrong.

@Ghanima Yeah, all right Mr Pedant. Bootloaders are a completely separate program stored in a separate section of memory and run separately to your main firmware. You don't modify them either.

A bootloader does not modify existing code. A bootloader deletes existing code and replaces it with completely different code. Just because the bootloader happens to live in flash alongside your program and you have the option of running that instead of your program and it happens to accept programming data and write that to flash it does not "prove it all wrong" since the bootloader does precisely what I described in my answer.

Well, the blynk board is pretty damn limited then, as I can upload a whole crapton of custom code to virtually any other microcontroller.
we're going to try and send ints from the XY coming in via wifi to the Blynk board via serial to another controller.

@Nick You can upload all the code you like, you just have to make sure that it includes the code you require to communicate with the iPhone app.

@Majenko what about with the custom Voids I have? will that mess anything up at all? we're just trying to have the XY values pass through those voids so they can drive the car (aka sending PWM values to the servo motors).

I don't know, I have never used Blynk. Maybe you should check out the Blynk Arduino library. It's linked from the getting started page. I am sure it has examples you can build on.

A bootloader resides in code memory and runs on the µc hence it is firmware. It furthermore allows to store and run other pieces of software - that also qualifies as firmware. So there are two pieces of firmware on the system and that contradicts the point your answer makes one and only one... I know that it is beyond doubt that you know how firmware and bootloaders work and I also know that this is mainly beside the point of the question. So, my apologies if you considered my comment inapt.

@Ghanima A bootloader does not and can not modify existing firmware. So what if it sits there in flash? So what if it allows you to replace code wholesale. It still cannot modify existing firmware!

@Ghanima Oh, and the keyword you have conveniently completely ignored there is "YOU". The user only has one firmware. The bootloader is not something the user ever should tinker with. The user can only upload (yes, using the bootloader if there is one) ONE piece of firmware, and only ONE piece of firmware runs at a time and that firmware CANNOT be modified.


text:
What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it
Suppose delay(10000) function is executed, so Arduino cannot do any other work.

During this time if the other device sends the data to arduino what
  will happen ?

Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.
The reception code in the core is:
void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0)) {
    // No Parity error, read byte and store it in the buffer if there is
    // room
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    // if we should be storing the received character into the location
    // just before the tail (meaning that the head would advance to the
    // current location of the tail), we're about to overflow the buffer
    // and so we don't write the character or advance the head.
    if (i != _rx_buffer_tail) {
      _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer_head = i;
    }
  } else {
    // Parity error, read byte but discard it
    *_udr;
  };
}


text:
Arduino + ESP8266 as Webserver
I want to connect Arduino to my Home Wifi and make it serve as a server to access GPIO pins on Arduino from remote (like controlling LED connected to Arduino from remote).
I am using ESP8266 to connect to my wifi network.
I am facing some issues like:

sometimes it doesn't connect to my wifi router.
not connecting to my mobile Hotspot.
not able to serve default and AP mode.

I am following tutorial from http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/
Here is my code:
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
//  sendData("AT",2000,DEBUG); // send AT command
//  sendData("AT+GMR\r\n",2000,DEBUG); // returns firmware
//  Serial.println("checking mode");
//  sendData("AT+CWMODE=?\r\n",5000,DEBUG); // check supported modes
//
//  Serial.println("scanning APs");
//  sendData("AT+CWLAP\r\n",21000,DEBUG); // scan list of access points

  Serial.println("set mode 1");
  sendData("AT+CWMODE=1\r\n",5000,DEBUG); // configure as both mode

//  Serial.println("joining AP");
  sendData("AT+CWJAP=\"<MY_WIFI_SSID>\",\"<WIFI_PASSWORD>\"\r\n", 16000, DEBUG); // connect to wifi

  Serial.println("Testing CIFSR");
  sendData("AT+CIFSR\r\n",7000,DEBUG); // get ip address

  Serial.println("setting for multiple connection");
  sendData("AT+CIPMUX=1",2000,DEBUG); // configure for multiple connections

  Serial.println("print MAC address");
  sendData("AT+CIPSTAMAC?\r\n",2000,DEBUG); // print current MAC address

  Serial.println("set port 80 for server");
  sendData("AT+CIPSERVER=1\r\n,80",2000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(2000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Tyagi IoT
<button>LED1</button>";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     webpage="<button>LED2</button>";

     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,3000,DEBUG);
    }
  }
}

void sendData(String command, const int timeout, boolean debug)
{
    esp8266.print(command); // send the read character to the esp8266
    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        Serial.write(esp8266.read());
      }
    }
}

I know this is an old question, but posting my 2 cents for future visitors. You're setting "AT+CWMODE=1" which is Client mode. Mode 3 is the correct one for both client and server mode.

Are you using an arduino (as in UNO / mini / nano etc.) and communicating with a separate esp8266 via serial?
I've found esp8266 module to be more reliable by using a 12e or such like and running arduino boot loader on it. There's more memory to play with, and I tend to formulate the data I need within the ESP8266 and then communicate with that via serial or I2C to get data / requests to and from.
Make sure you're supplying the ESP module with enough current - they're juicy little things, so good 300mA @3.3v and use a good 470uf 10v cap or something too.. They can splurge current on occasion, particularly when scanning networks.
Let me know what set up you're running
Cheers

Using Uno and communicating using AT commands on Software serial as mentioned in the code above.

If you're running the esp straight off the uno 3.3v power supply, that'll be the first thing to change. The esp8266 can draw around 200mA transmitting and around 60mA when receiving. The 3.3v regulator built into the arduino UNO is rated for like 50mA max from memory, so defo get a better 3.3v supply. I usually use a MIC5219 LDO regulator which is good for around 500mA but super efficient. Gotta sort power out before trying anything else at this point :)


text:
Is it possible to see a graphical view of digital and analog pin values?
Using Visual Studio for my Arduino project I am struggling to know the states of various pins during operation.
I do use the Visual Micro debugger but I don't want to have to set a watch for every pin.
How can this be done easily?

Visual Micro provides this for you if you have the debug module enabled. It also optionally shows analog, memory and i2c. Read more about Arduino debug and the digital pin viewer

The Arduino Dashboard project sounds promising but quite likely it loops through the I/O pins periodically and uploads the results to your PC. I'm guessing you want live monitoring (as opposed to snapshots) while your own program (not the Dashboard sketch) is running. In that case, you'd need to isolate the relevant parts of the Dashboard sketch and integrate them with your code, and unless your are looking for fairly low frequency signal changes, have a timer interrupt function that runs the Dashboard frequently, which will have an impact on your own code. If the signals are fairly low frequency you might get away with putting a call to Dashboard in your loop() function instead of running it from a timer interrupt. If you're looking for program bugs that are changing your outputs, once per loop() may be fairly useless. A timer-interrupt would be necessary, and might have to analyze the stack and output the names or addresses of functions that had run recently. At that point you'd be on your way to implementing a debuggerand may want to consider an in-circuit emulator or a bus analyzer to capture the event. Or get smarter about isolating the code responsible for the event until you have a manageable, printf-debuggable code segment.


text:
Arduino Micro and MPU-9150
I'm trying to connect an Arduino Micro to MPU-9150 using the  MPU6050_DMP6 example.
It runs for couple of seconds then the board Hangs, I sometimes see the "FIFO overflow" message.
The same code runs well when i connect the MPU-9150 to Arduino UNO and Arduino Duemilanove.
I tried to lower the serial baud rate but no success with that. I even tried connecting an external 12V to the Micro but it's the same.
should I lower the i2c clock (not sure how to do it)?
another interesting thing i have noticed is that with the Duemilanove i can use a longer line for the i2c (5m of cat5e), with the Uno it only works with less then 2m cables, can anyone tell why?


text:
PCA9685 seemingly no PWM output Arduino Uno when attempting to do LED dimming
Just for a quick test I've wired up the Arduino to a PCA9685 board (similar to http://www.ebay.com.au/itm/PCA9685-16-Channel-12-bit-PWM-Servo-motor-Driver-I2C-Module-For-Arduino-Robot-AU-/162059198475?hash=item25bb7b200b:g:S7IAAOSw9ZdXKa7h) as follows

5v > Vcc & V+
GND > GND
A4 > SDA
A5 > DCL
OE > Not connected

I've wired a 1k resistor in series and an LED in between PWM0 and GND
The same LED dims fine when powered directly via PWM from the Arduino.
The power light on both boards come on and +5v is available at the V+ pins.
The library I'm attempting to use is https://github.com/kasperskaarhoj/PCA9685-Arduino-Library and from what I can tell the I2C address I've configured "works"
The sketch I'm trying to run is (which is one of the example sketches with the address I2C altered):
#include <Wire.h>
#include <PCA9685.h>

PCA9685 ledDriver;

void setup()
{
  Serial.begin(9600); // set up serial
  Serial.println("Serial Started");

  Wire.begin();           // Wire must be started!
  ledDriver.begin(B000000);  // Address pins A5-A0 set to B111000
  Serial.println(ledDriver.init());

}

void loop()
{
  // Notice: setLEDDimmed cannot be used in a loop to give you a pleasant
  // "turning-up" of the LED. This is because each time you set a level for a LED
  // it will calculate random timing intervals for the PWM function in the chip
  // This is done in order to distribute current consumptions of the full time period.
  for(int level=5;level>=0;level--)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
  for(int level=0;level<=5;level++)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
}

Serial monitor outputs:
Serial Started
1
So it looks like the device is detected and I expect that the commands are sent but nothing happens.
I've also tried one other library and setting the duty cycle to 100% on/off just to see if I could get output with no luck. It just seems that all the PWM pins are dead. I also tried wiring up the OE pin and setting it high/low with no luck.
Any thoughts on how I might be able to get the board to output something or how I can test further would be appreciated. I'm beginning to think that maybe the IC is damaged as I've tried most the pins with no luck.
I'm out of ideas and haven't worked with I2C or PCA9685's before at all so any help would be appreciated :)

So you talk to the PCA9685 board using I2C.  Did you put I2C pull up resistors on the lines.  They are normally open collector outputs at both ends.  So w/o pull up resistors the I2C bus lines are usually floating if not pulled to ground by a transmitting device.  If this works, I'll formalize the wording and add it as an Answer you can select.

Try connecting the OE pin to GND (active low).

The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.

Thanks for the great suggestions guys - I hadn't considered any of them really - @Majenko your comment was the one that solved the issue - I'd connected the resistor between PWM and GND not V+ and PWM0 If you'd like to post it as an answer I'll accept it as the solution :)

The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.


text:
How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?
I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.
This is the code I have written for simple rotation of the motor:
const int stepPin = 8;
const int dirPin = 9;
int sensorValue=A0;
int i;

void setup() {
  Serial.begin(9600);
  pinMode(sensorValue, INPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  sensorValue = analogRead(A0);
  float voltage = sensorValue * (5.0 / 1023.0);
  if(voltage==1) {
    digitalWrite(dirPin, HIGH);
    for(int x = 0; x < 200; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(5000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(5000);
    }
    delay(1000); // One second delay
  }
  digitalWrite(dirPin, LOW);
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);
  while(1);//only once
}

When the sensor is pressed constantly your algorithm moves some steps, waits a second and moves some steps and waits a second again. Is this your desired behavior or maybe you want the speed of the stepper depend on pressure?

No, i dont want the speed of the stepper depend on sensor ,speed would be constant.only  when the sensor gives some input stepper motor should move few steps and should stop there until it don't get another input .and if it gets input as previous input then it should return back to that position.

So if the sensor gives out constant value you just want to move some steps and then stop? If sensor gives 4V and after a second gives 3V you want the stepper to move 4 steps, wait and then move 1 step backward?

yes ,i wanted  the same.

Then use s global variable to save previous state of the sensor. Every cycle check if the new one is different. If it's not do nothing. If it is them move the motor and update the previous state of the sensor.

' #include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
Stepper stepper(STEPS, 8, 9);
int previous =0;
void setup() {
// set the speed of the motor to 30 RPMs
stepper.setSpeed(100);
}
void loop() {
// get the sensor value
float val = analogRead(A0);
stepper.step(val - previous);
previous = val;
}'

I have written above code but only problem is how to check  whether value   is new one or previous one.plz reply with code .thanks

I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.
I cannot test this code, because I don't have your hardware. Treat it as pseudo code.
#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
#define NOISE 0.1

Stepper stepper(STEPS, 8, 9);
int previous = 0;
void setup() {
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop() {
  // get the sensor value
  float val = analogRead(A0);

  float difference = previous - val;

  if(difference < -NOISE || difference > NOISE)
  {
    stepper.step(val - previous);
    previous = val;
  }
}

i have tested te code with hardware its working f9 now .thanks for the help :)