message:
Driving two stepper motors using one stepper motor driver

Using an Arduino Mega, I currently control two stepper motors that never operate at the same time and never will. I am using two EasyDriver stepper control boards with two separate power sources. I was wondering if I could go down to just one stepper control board, one power source but somehow switch the 4 input wires from one motor to another when I need to turn a specific motor. Is there a switch I can control with Arduino where I can plug in 8 wires and say "ok, use the 4 left most wires" or "switch to the right most 4 wires". Does that exist or is that more complicated than what I currently have?

body:
If we call the motor leads A1, A2, B1, B2 on each motor and control, you could tie the two motor A1's to A1 on the control, and motor B1's to B1 on control.  Then wire a DPDT relay as below.  (Coil not shown.)  Note, DPDT relays are about $4 on ebay, with labels like “DR21A01 DC 5V DPDT Relay Module Polarity reversal switch Board for Arduino UNO”.

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

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

<!-- End schematic -->

Since you have equipment in place and working, it might not be worthwhile to change your setup.  However, even without adding a relay, you probably can power both motor controls and motors with a single power supply, ie could use one instead of two power supplies.  The current draw when a stepper motor is idle is a small fraction (eg 10-20%) of the high current drawn when the motor steps.  If you don't have power attached to a stepper motor, there is only its cogging resistance to keep it from turning; it does not take a large torque to turn an unpowered stepper motor.  If that's a concern, the DPDT relay approach might be unsuitable.


sender: user

message:
When is it necessary to use "float" instead of "int"?

I'm very new to Arduino and I am making a code for a pedometer.  I have a lot of variables and I have used "int" multiple times, but I just came across a code with "float".
Now because my coding background is next to none, I don't really understand the concept of a float and when it's appropriate to use one.
Could someone please give me an explanation.
Thanks!

sender: assistant

body:
"int" means integer. It's either one whole number (forgive me, mathematicians, for the sloppy definition!) or the next or previous.

A "float" is a floating-point number - that is, a number and part of a number.

3 is an int

3.14 is a float

If you need to store/represent a value that can be between integers, you could use a float.

Floats use more RAM than integers, and there is a limit to the precision they can represent. Don't use a float unless you have a need.


body:
An [integer][1] is a [whole or natural number][2].  Computers use integers for counting and comparisons.  Computers can count precisely using integers and comparisons of two integers can be absolutely true or false.

To make a [float or floating-point number][3], a computer uses two integer numbers.  It uses one integer as the mantissa and the other as the exponent.  Computers use floats for calculations involving very large, very small or fractional values.  In other words the set of [real numbers][4].  Computers can not count very well using floats.  Computer can not even compare two floats very well. That is to say, you may get different results from different computers when testing if two different floats are the same or not. This is due to [rounding error][5].

Consider that the set of real numbers between 0 and 1 to be infinite.  However, intuitively, we know computers can not keep track of an infinite number of unique values between 0 and 1.  After all, computers use a float to do this and a float has a finite number of bits in it's mantissa and exponent.  The difference, if any, between the actual real number from, say, a calculation and the next possible float value is commonly referred to as the roundoff error.  In a program, a difference, for example, in the order of operation is enough to cause different roundoff errors to occur resulting in two slightly different float value results.

Rounding errors are what we end up with for allowing float values to grow very large or very small or to contain factional amounts.  Fortunately, floats are exactly what we need when computers are asked to calculate very large, very small or fractional numbers.

In embedded programming we rarely use floats.  They take up more of our limited RAM space than integers.  And it is rare that we need to calculate very large or very small numbers.  Usually, in embedded programming, we are counting events or measuring sensors.  Usually integers are preferred or are sufficient for our purposes.

Addressing your specific application (pedometer):

It is anticipated you would prefer to track distances in miles.  And it is practical to assume a good pedometer displays factional miles.  You can use floats to calculate this value.  A rigorous programmer would [cast][6] their integers as floats when mixing them in equations to make it clear to the compiler what is desired.

  [1]: https://en.wikipedia.org/wiki/Integer
  [2]: https://en.wikipedia.org/wiki/Natural_number
  [3]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
  [4]: https://en.wikipedia.org/wiki/Real_number
  [5]: https://en.wikipedia.org/wiki/Round-off_error
  [6]: https://www.arduino.cc/en/Reference/Cast


body:
There are much more details on both data types, but to keep it easy, just a rough explanation:

**`integer`** data types only allow a range from -2,147,483,648 to 2,147,483,647 with 4 Bytes of memory per variable.

If your results exceed that numbers, an over- or underflow will occur. If you don't take care, bad things can happen.

And you can only use whole numbers, there is no decimal point.

**`float`** instead allows you to do your calculations directly typing decimal values (like 1.25, 3.14, ...), just like you do on paper.

Plus: You usually don't have to care for range checks, because that data type covers a huge value range (-3.4028235E+38 to 3.4028235E+38 with also only 4 Bytes of memory per variable!

So why not use `float` by default?

One big drawback is that handling this number format requires a special piece of hardware ("Floating Point Unit", FPU) to be efficient.

If your microcontroller doesn't have an FPU (and the small Arduinos don't have one), every calculation using `float` operands requires to call certain functions which use some rules to convert your `float` operands into `integer` data types, do the calculation on `integer` basis and convert the result back to `float`.

This consumes some memory and a lot of CPU cycles, which can slow down calculation speed to about 1/10 compared to using an FPU.

There are some other issues which make working with `float` a little bit tricky, so if your calculation can be done using `integer`, use this instead.

"And what if i *need* decimal numbers?"

You can't type 3.14 in `integer`, but you can multiply it to a value big enough to consider enough decimal places for your application. You just have to define the factor and  imagine the decimal point.
For instance, multiply your values by 1000, then 3.14 * 1.256 = 3.94384 becomes 3140 * 1256 = 3943840 internally.


body:
> When is it necessary to use “float” instead of “int”?

IMHO **in Arduino world it is never necessary to use float** ; well unless you want to do something very fancy like building a space ship route calculation with Arduino. In which case you will have someone on your team who understands the problem in full detail who can decide it is better to use float for some calculations.

> How do I deal with behind the comma numbers?

As integers does not allow you to work behind the coma and you won't use float you may wonder how to work with pi (3.1415..radians). In most cases you will only work with a specific number of digits behind the comma. Lets say you want 3 digits behind the comma. In this case you simply work with milli radians instead of radians ( 3145 milli radians=3.145 radians; [For the Americans it might be time to look at the metric system for a better understanding][1])
Because of this change in "base value", no more floats are needed to calculate.  There are 3 drawbacks:

 - when out-putting information formatting may be needed/desired to
   convert to a user "base value".
 - when in-putting information formatting may be needed/desired to
   convert to a user "base value".
 - When using methods that use float conversions are needed
In and output are normally very small in arduino. The Serial.print() is probably the biggest thing.
If you need to use a method like cos() you do as follows:
long result=DECIMALDIGITS*cos((float)corner/DECIMALDIGITS);
Where DECIMALDIGITS= (float)10^numdigits;

As type I advice to use long on a 8 bitter as int (-32,768 to 32,767) is very likely to get out of range.

**More background behind the dirty details of float**
It is pretty obvious that float supports behind the comma values, but what are the disadvantage of float?

 - float is CPU/RAM intensive
 - float introduces a rounding problem.
 - multiple types int/float can cause casting issues

Lets go through the disadvantages one by one:
**float is CPU/RAM intensive**
IMHO In many Arduino projects there is plenty of CPU/RAM left so I don't think this is a real issue.
To prove this point look at how many Arduino projects contain a delay(x00) in the loop; so if things go to slow simply decrease this number to release some CPU cycles ;-).

**float introduces a rounding problem.**
*When using floats A * B / A does not guarantee to be equal to B!!!* It will be close but ...
This is my main argument to avoid floats. Sooner or later this will hit you and you'll have a hard time finding out why. (I speak from experience here)
Basically 0.1 can not be represented 100% exactly in float. So in float 0.1+0.2 is not equal to 0.3!!!

**multiple types int/float can cause casting issues**
In C/C++ it is pretty hard to predict the casting that will happen in a formula like:

    float z;
    byte r;
    uint32 t;
    ...
    int a=z*r/t*1.5;

I consider myself very experienced in C/C++ and I always convert code like this into something like

    float z;
    byte r;
    uint32 t;
    ...
    byte rfloat=r;
    uint32 tfloat=t;
    int a=(int)(z*rfloat/tfloat*1.5);

I prefer not to explain this to a newbie Arduino user :-s.
More in depth details can be found at [floating-point-gui.de][2]

  [1]: https://en.wikipedia.org/wiki/Metric_system#Decimal_multiples
  [2]: http://floating-point-gui.de/


body:
> I'm very new to Arduino and I am making a code for a pedometer.

others have answered the difference between float and int.

but your project offers an interesting challenge in that it covers a wide range: the pedometer likely counts in miles and have to keep track of total steps, which the increments are done in single steps - much shorter than miles.

what you could do instead of using floats is to use multi-byte types. for example, a 32-bit/4-byte type can support 2 million miles; you can add additional msb to it to create a proprietary data type. a 5-byte type for example would support 5 million miles, and a 128 billion miles for a 6-byte type.

you will need to create your own math routines -> not difficult at all.

the point is that float is a simple solution to simple problems only.


body:
`int` stands for **Integer**
and `float` stands for **floating point** number.
For more reference check this out https://www.arduino.cc/reference/en/language/variables/data-types/float/


message:
Arduino Uno-Spider Robot Plan

I have been doing a lot of researching ever since Christmas when I got the Arduino Uno. Anyways, I want to build a 4 leg spider robot using 2 Arduino's. I had a lot of problems on coming up with how to do it, and I think I got it. What I want to be answered is this question, is my circuit good to go and will not fry anything? Anyways, I needed 12 servos. Only 6 pins on 1 Arduino has PWM. So I thought to use 2 Arduino's to communicate through the HC-06 blue-tooth. Power was another problem. I discovered that double AA batteries have an impressive 7 amps on my multi-meter. However, to much for the Arduino. That is why it is only supplying servos and not going directly to the Arduino. A 9v will do that. Anyways, I can't give you guys the schematic as it is to big of a file. However, I will explain the circuit in words. One Arduino is master and the other is slave. These steps go to both master and slave unless stated.

1. 6 servos on master and 6 on slave. Power is going to 4 double AA batteries in series. This supply is not connected to the board except the ground wire. This is a battery holder with switch already on it. All PWM pin's are in use for servos.

2. 9 volt battery going to the Vin pin. I will incorporate a switch.
3. Fan with positive and negative only. Positive goes to the 9 volt battery. Ground goes to ground pin on Arduino.

4. Bluetooth module with VCC going to 3.3v pin. Ground to ground pin. TXD going to the RX pin. RXD going to TX pin.

5. For master Uno only. Distance sensor with Trig going to A5 pin and echo to A4 pin. Ground going to ground pin. VCC going to 5v pin.

6. 2 led's in circuit with 220 ohm resistor. I will use pin 4 and 2. Ground goes to ground pin.

That is the setup. I am in college where soldering is banned. So I am including a fan, like you saw, to cool down the breadboard. Let me know if you think that will work. I could not find a good schematic online for this robot, so I made one. Please let me know if you have any questions. Anyways, please tell me if there are any flaws and thank you so much for your time and effort.

Edit 1:
@gilhad
I did not know about I2C, if that is easier than blue-tooth, then I will get that. Thanks for that input. This way I don't have to use 2 blue-tooth modules. Most of the robot is running in series, not parrel.

Also, I said 4 AA batteries and not 2. If I had 2 in series, then that is 3v only, so that is why I am going for 4 in series for a total of 6v, with amps being the same as with one battery. This will supply 7 Amps. I tested it with my multi-meter. The servo motors are going to need 1 amp of power at max. I have 7. I will probably be using 4 servos at one time. So that is 4 amps. It will run for about an hour. That is fine by me.  This 4 AA battery is not connected to the arduino. There are 2 power sources per arduino. The other one is a single 9v battery, that one is going directly to the arduino, the Vin pin to be clear. If it is going to reset, could I do something in the programming to account for that like a time delay that is short?

 I do not want to mess with my breadboards, that is why I am using a fan to cool them. Will that work?

The power source will not be moving all the servos at once, sorry that I did not include that.

Edit 2:

@killer rabbit

I guess I did not want to get a mega because I have 3 Uno's already, but I see they're pretty cheap online. I will ponder this idea of yours. I looked at my schematic and determine this would eliminate the 2 blue-tooth modules, 1 power source, 1 fan, and 2 leds along with their resistor. I think it would also eliminate an extra switch. Programming would be easier to because I don't have to worry about blue-tooth communication. I had no idea what to do for that one. So maybe I will get a Arduino mega.

The reason I am not using RC battery is because they're kinda heavy and SG90 servos are kinda small. I was worried about torque.  Li-ion is not to heavy, but I was worried about power. The ones you gave me though, look like that might work. There is 2 problems though. First, I can't use 2 of these batteries in series because that is 7.4 volts when the servos I am using is at max 7.2 volts. I would have to reduce voltage somehow, I have no idea how to wire that into the circuit. Problem 2 is that if I wire is parrel, that is 6 amps, which is fine, but only 3.7 volts. The motors can run on that, but that is on the low end. Will torque be less?

About the third paragraph, there is limits on the amount of current an Arduino can take. I looked them up. It is about 2 amps for the Vin pin I think or that might be the DC jack, one of the two.

I am using 2 Arduino, so that is why the blue-tooth was necessary. However, if I go with the mega, it will eliminate both of them. I forgot to mention for the distance sensor, I am using ultra sonic one. That is my fault for not mentioning that.

The reason I need 12 servos is because I am using 4 servos at the base, one for each leg to control direction of leg for steering. Then I have 4 legs, each using 2 servo motors to make the leg kick out and in. So 4 + 2(4)=12.

Yes, I would be using, if 2 Arduino, wireless communications, that is why the blue-tooth module. About the schematics, the picture is too big, so that is why I can't upload it. So sorry about that. I did try, believe me.

body:
There are multiple points where you should reconsider your plans:
First of all, do not use multiple Arduino Unos, it's just a pain in the arse to make them work synchronously, instead use (for example) a single Arduino Mega 2560 which has 14 PWM outputs and still cheap as dirt.

I'm not sure about the life length of the AA batteries, I might consider using Li-Po (something from an RC shop, or something) or Li-ion (18650 is very popular and cheap) batteries. The Arduinos can take basically anything from 9 to 6 volts (and 5 from the USB), so you have a bit of freedom there.

A bit of electrical stuff: High available current is not a problem for the Arduino, it takes as much as it needs, so as long as you are in the voltage range of the board, you won't have any problems. Less amperage however is a problem, so be sure your battery can provide enough current!

You probably won't need cooling, there are no devices in your spider that would require more than a heatsink, if at all. But soldering is very recommended, I urge you to reconsider about that.

The Bluetooth module becomes unnecessary by going with a single Arduino.
For distance sensor I recommend an ultrasound one, those are really (ridiculously) cheap and simple to use. (HC-SR04 is very popular for example and there are tons of tutorials for it)

LED's are okay, most people don't think about the resistors, but those are important!

A question: Why do you need 12 servos?

That's all I got in the first round, feel free to share more info and I'll try to help you with your planing. I highly recommend you to share the schematics with us so we can help you to improve it!

Edit: I almost forgot: do you intend to use some kind of connection to the spider, like Bluetooth or Wi-Fi?

-------------------------

As far as batteries go, I'd recommend at least 6 volts, so you can use the Arduino's barrel connector. You may use 2 serial Li-ion batteries and a buck converter, but I believe you'll do fine without it, your servos will handle the extra 0.2 volts.

About the current limits: Your Arduino can supply around maximum 500 mA from all it's pins, and 40mA from a single pin, BUT it won't be a problem, because you do not connect the servos' VCC (+) and GND (-) pins to the Arduino, instead you hook them up to the battery directly. You only connect the SIGNAL pins to your Arduino which draw less then 10 mA.

For the communication with the spider I'd recommend a Wi-Fi module and UDP, as the protocol for the communication.

G.


body:
For connecting 2 Arduinos use some wires - I2C works good for me, but Serial is also good. Anyway you probabely will came to problem with interrupts and many tasks running in paralel, or the spider be slow - you choose not so easy target (but reacheble).

As for bateries - Arduino need constant power, than it takes as much current as it needs (if it is aviable), so no problem in 2 AA for Arduino.

You would need a lot of servos - they are, what takes energy - even if 2AA can give a lot for short time, this will not last long. Also giving high current means voltage drops (as for cable and mainly internal batery resistence), so if you feed arduino from the same source, it can reset every time, when too much servos try to move/stang agains gravity.

 Different source for Arduino is good idea, as the CPU will last longer, then those actuators and could shutdown properly (not let move just one leg or so). Also the electrical interference from servos would be much less this way. (There are other ways, more complicated to do that).

Breadbourd can be stripped the bottom plastic and have it exchange for more thinner double-size tape, then be put on large alluminium (or other heat-conducting) plate for better cooling too.

Arduino cannot move all those servos from its source, think about alimitation currrent per pin and per arduino itself - you may need some other IC/transistors to power it properly on each servo and the servo power should go direct from bateries, not via Arduino. Connect just grounds.


message:
Arduino Nano not visible in Serial Ports (Mac OS)

I have used by Arduino countless times over the past few years and only after installing an update to Mac OS Sierra did the device stop showing up under the Serial Ports. Now only tty-bluetooth shows up no others. I have looked a countless threads where people suggest installing drivers or uninstalling drivers or rebooting. I have tried everything but still no device shows up.

I switched to my Windows partition using Bootcamp and lo and behold it works perfectly there but not in Mac OS. I would still like to use Mac OS to programme my Arduino. If anyone has any suggestions I would be very grateful!

body:
Is it an original Nano or a clone?

The original Nano uses FTDI's FT232 ship, whereas clones use the CG340 USB-to-TTL chip. The former works fine straight away Mac OS Sierra, whereas the latter needs a driver.

The CG340 driver doesn't work under Mac OS Sierra. Fortunately, someone patched the driver and made it [available at GitHub][1]. There you'll also find some troubleshooting instructions that can help (hopefully).

From Adrian Mihalko's repository at GitHub:

----------

ch340g-ch34g-ch34x-mac-os-x-driver
==================================

Latest **macOS Sierra**-compatible driver for devices using the CH340G, CH34G or CH34X chipset. This chipset is used in several Arduino-clones.

Introduction
------------

Version 1.3 (2016-09-27) of the [OEM driver][2] for the CH34x chipset currently causes a kernel panic (a.k.a. *crash*) when installed on **macOS Sierra.** To resolve this issue, please download and install the driver in this repo.

Installation
------------

- Remove the old driver by issuing one of the following commands (depending on your installation):
  - `sudo rm -rf /System/Library/Extensions/usb.kext`
  - `sudo rm -rf /Library/Extensions/usbserial.kext`
- Restart your Mac.
- Double-click on the `CH34x_Install_V1.3.pkg` file.
- Restart your Mac.
- Plug in your device. It should now be listed under the `/dev` directory. Examples:
 - `/dev/cu.wchusbserial1410`
 - `/dev/cu.wchusbserial1420`

Troubleshooting
---------------

If, and only if, the device is not recognized after the installation (or you cannot install the driver), please disable *System Integrity Protection*:

- Reboot your Mac into *Recovery Mode* by restarting your computer and holding down `Command+R` until the Apple logo appears on screen.
- Open the Terminal (Applications > Utilities > Terminal).
- In the Terminal window, type in `csrutil enable --without kext` (or to fully disable: `csrutil disable`) and press Enter.
- Restart your Mac.

Please share this page!

Regards,
Adrian Mihalko

  [1]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
  [2]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html


message:
Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code?

I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

body:
Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.

If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.

Update:

> There's a bit more required, for example, the clock rate needs to
> match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.

If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed *without* modifying the code for those differences.


message:
How to use to two different programs into one stkech

I am currently using relay module, but I am facing a problem that, when Arduino pins are LOW then all relay are going HIGH, so I want to use this code so that when arduino starts all pins are getting HIGH, and also can be control with char data/switch(data)/case break;/,

    Here is my code:

    setup() {
      if(conditionIsTrue) {
        aGroup::setup();
      } else {
        bGroup::setup();
      }
    }

    loop() {
      if(conditionIsTrue) {
        aGroup::loop();
      } else {
        bGroup::loop();
      }
    }

    namespace aGroup {
    setup() {

     pinMode(ledPinA, OUTPUT);
        pinMode(ledPinB, OUTPUT);
        pinMode(ledPinC, OUTPUT);
        pinMode(ledPinD, OUTPUT);
        pinMode(ledPinE, OUTPUT);
        pinMode(ledPinF, OUTPUT);
        pinMode(ledPinG, OUTPUT);
        pinMode(ledPinH, OUTPUT);
        pinMode(ledPinI, OUTPUT);
        pinMode(ledPinJ, OUTPUT);
        pinMode(ledPinK, OUTPUT);
        pinMode(ledPinL, OUTPUT);

    }

    loop() {

      digitalWrite(ledPinA, HIGH);
      digitalWrite(ledPinB, HIGH);
      digitalWrite(ledPinC, HIGH);
      digitalWrite(ledPinD, HIGH);
      digitalWrite(ledPinE, HIGH);
      digitalWrite(ledPinF, HIGH);
      digitalWrite(ledPinG, HIGH);
      digitalWrite(ledPinH, HIGH);
      digitalWrite(ledPinI, HIGH);
      digitalWrite(ledPinJ, HIGH);
      digitalWrite(ledPinK, HIGH);
      digitalWrite(ledPinL, HIGH);

    }
    }

    namespace bGroup {
    setup() {
      Serial.begin(9600);
        pinMode(ledPinA, OUTPUT);
        pinMode(ledPinB, OUTPUT);
        pinMode(ledPinC, OUTPUT);
        pinMode(ledPinD, OUTPUT);
        pinMode(ledPinE, OUTPUT);
        pinMode(ledPinF, OUTPUT);
        pinMode(ledPinG, OUTPUT);
        pinMode(ledPinH, OUTPUT);
        pinMode(ledPinI, OUTPUT);
        pinMode(ledPinJ, OUTPUT);
        pinMode(ledPinK, OUTPUT);
        pinMode(ledPinL, OUTPUT);

    }

    loop() {

      char data = Serial.read();
        switch(data)
        {
            case 'A': digitalWrite(ledPinA, HIGH);break;
            case 'B': digitalWrite(ledPinA, LOW);break;

            case 'C': digitalWrite(ledPinB, HIGH);break;
            case 'D': digitalWrite(ledPinB, LOW);break;

            case 'E': digitalWrite(ledPinC, HIGH);break;
            case 'F': digitalWrite(ledPinC, LOW);break;

            case 'G': digitalWrite(ledPinD, HIGH);break;
            case 'H': digitalWrite(ledPinD, LOW);break;

            case 'I': digitalWrite(ledPinE, HIGH);break;
            case 'J': digitalWrite(ledPinE, LOW);break;

            case 'K': digitalWrite(ledPinF, HIGH);break;
            case 'L': digitalWrite(ledPinF, LOW);break;

            case 'M': digitalWrite(ledPinG, HIGH);break;
            case 'N': digitalWrite(ledPinG, LOW);break;

            case 'O': digitalWrite(ledPinH, HIGH);break;
            case 'P': digitalWrite(ledPinH, LOW);break;

            case 'Q': digitalWrite(ledPinI, HIGH);break;
            case 'R': digitalWrite(ledPinI, LOW);break;

            case 'S': digitalWrite(ledPinJ, HIGH);break;
            case 'T': digitalWrite(ledPinJ, LOW);break;

            case 'U': digitalWrite(ledPinK, HIGH);break;
            case 'V': digitalWrite(ledPinK, LOW);break;

            case 'W': digitalWrite(ledPinL, HIGH);break;
            case 'X': digitalWrite(ledPinL, LOW);break;

        }

    }
    }

But this isn't work, Please help me.

body:
In first place, you have to declare the functions setup and loop as `void setup()` and `void loop()`.

If you want your output pins to be high when Arduino starts then you should do that in your setup function, instead of doing it in the loop:

    void setup() {

      Serial.begin(9600);

      // Step 1: configure pins as outputs
      pinMode(ledPinA, OUTPUT);
      pinMode(ledPinB, OUTPUT);
      pinMode(ledPinC, OUTPUT);
      pinMode(ledPinD, OUTPUT);
      pinMode(ledPinE, OUTPUT);
      pinMode(ledPinF, OUTPUT);
      pinMode(ledPinG, OUTPUT);
      pinMode(ledPinH, OUTPUT);
      pinMode(ledPinI, OUTPUT);
      pinMode(ledPinJ, OUTPUT);
      pinMode(ledPinK, OUTPUT);
      pinMode(ledPinL, OUTPUT);

      // Step 2: initialize pins to output HIGH
      digitalWrite(ledPinA, HIGH);
      digitalWrite(ledPinB, HIGH);
      digitalWrite(ledPinC, HIGH);
      digitalWrite(ledPinD, HIGH);
      digitalWrite(ledPinE, HIGH);
      digitalWrite(ledPinF, HIGH);
      digitalWrite(ledPinG, HIGH);
      digitalWrite(ledPinH, HIGH);
      digitalWrite(ledPinI, HIGH);
      digitalWrite(ledPinJ, HIGH);
      digitalWrite(ledPinK, HIGH);
      digitalWrite(ledPinL, HIGH);
    }

Also, you can't declare a variable and assign to it the value of a function other than an object constructor. Furthermore, you should check if there's data available before trying to read it. So you have replace the following sentence:

    char data = Serial.read();

With something like this:

    char data = 0;
    if (Serial.available() > 0) {
        data = Serial.read();
        // do your stuff
    }

This should do the trick.

Last but not least: I don't know why you're using two `namespace`s. The `aGroup` looks useless to me. On top of that, I fail to see where in your code do you declare, initialise and update the `conditionIsTrue` variable. The same goes for all those `ledPinX` variables. Is there more code that you're not showing here? Is your code failing at runtime, or doesn't even compile?


message:
Motor shields in arduino

what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?

body:
Servos require power and PWM. Servo shields come in two main forms:

1. Simple distribution
2. Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.

[The second kind](https://www.adafruit.com/product/1411), more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.

Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.


message:
Issues using HC-06 Bluetooth module with arduino

I recently ordered an HC-06 Bluetooth module for my Arduino Uno, and after watching [this video](https://www.youtube.com/watch?v=F6E5mP70jaw&t=1s), and many others, I still have been having many issues figuring out how to get it to work, and some questions for how the code receives and reads serial data from my phone.

1. I assume this wiring is correct, right?
 - Rx  > Tx
 - Tx  > Rx
 - Gnd > Gnd
 - Vcc > 3.3V

2. When I sent a command over the Bluetooth terminal app I have, the serial monitor displays that command over and over, I assume that is correct also?

3. How do I read the serial input? I've been using

        if(Serial.available() > 0)
                phoneInput = (char) Serial.read();
and then displaying the value of phoneInput to the serial monitor, but for some reason I can't seem to have it control anything properly (in this case an LED)

4. What datatype is the Serial.read() returning to my variable before I cast char on to it?

5. I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

body:
> I assume this wiring is correct, right?
>
>     Rx > Tx
>     Tx > Rx
>     Gnd > Gnd
>     Vcc > 3.3V

Almost. The Arduino's TX should be reduced to 3.3V using a 10k/20k potential divider.

> How do I read the serial input? I've been using
>
>     if(Serial.available() > 0)
>            phoneInput = (char) Serial.read();

You should read and digest [this](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/).

> What datatype is the Serial.read() returning to my variable before I cast char on to it?

An integer. It holds either 0-255 representing the ASCII code for a character, or -1 if there is nothing in the buffer to read.

> I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

That will be because you are using pins 0/1 to communicate with the bluetooth which you can't do because those are used to communicate with the PC.


message:
Unable to program Arduino mega2560?

I am using arduino mega for my application .  Board works well for a week , from yesterday it  is not programming at all , it shows me some error like timeout . What could be the problem kindly  help me to solve this.

 avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
    Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
    Copyright (c) 2007-2014 Joerg Wunsch

    System wide configuration file is "C:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf"

    Using Port                    : COM20
    Using Programmer              : wiring
    Overriding Baud Rate          : 115200
 avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified.

 Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
 avrdude: ser_drain(): read error: The handle is invalid.

 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: stk500v2_getsync(): timeout communicating with programmer

 avrdude done.  Thank you.

body: Com 20 is not configured with your arduino. Go to the arduino program and I think it is on the tools tab or the one next to it. There should be a port label and it says which com port to use. Then go to device manager, then ports. Then go to properties on the port that has arduino and change that to the port the arduino program said. It should work then. This topic has been solved many times.


message:
Did I fry my DUE by powering it from a external source and USB at the same time? If so, why?

I guess I just fried my second DUE in a week. The first I didn't really see what happened, but I couldn't upload any sketches, even if the computer could recognize it, and the SAM would get really hot.

Now, I had it powered by a 12V External supply, through a regulator bringing it down to 9V, and in the exact moment I plugged the USB, with power still on, I got a lot of smoke, smelling of fried electronics :p. Afterwards, I have the same symptoms as I had in the other boards: Green and orange LEDs on, chip very hot, computer recognizing it as a Arduino DUE but not being able to upload any sketches.

What just happened?

body:
As Majenko said you should check these voltages.

Arduino DUE uses the LM2734Y DC/DC converter and according to datasheet it works up to 20V so there is no need to use your 9V regulator.

Also on DUE there is comparator which should turns off a USB power supply when external power supply is used. Look for 2 transistors on board (FDN340P) called T1 and T2. There both are turning on/off power from USB source. Also check them. There can be also problem with all components around USB power. For more info check [Arduino] schematic.

[Arduino]: https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf


body:
If it was the same sketch involved in the destruction of both it may be a good idea to check to make sure the sketch that is involved as well to make sure there are no logical shorts to ground or other pins. [Rugged-Circuits][1] has a list of some common ways the Arduino can get shorted. It is showing the Uno but I am sure all similar rules apply with the exception of total power requirements and other differences between the boards.

  [1]: https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


message:
Why won't this code work on an Arduino Mega 2560 (It works on an Arduino Uno)?

The code below was taken online and was written for the Arduino Uno. I know C++ however I am a beginner with Arduino so I don't understand this compatibility issue or how to fix it. I am very thankful for any help. Here is part of the code - the variable declarations: (I can upload the entire code if that would be more helpful).

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

    ISR(PCINT0_vect) {
      current_time = micros();
      //Channel 1=========================================
      if(PINB & B00000001) { //Is input 8 high?
        if(last_channel_1 == 0) { //Input 8 changed from 0 to 1.
          last_channel_1 = 1; //Remember current input state.
          timer_1 = current_time; //Set timer_1 to current_time.
        }
      } else if(last_channel_1 == 1) { //Input 8 is not high and changed from 1 to 0.
        last_channel_1 = 0; //Remember current input state.
        receiver_input[1] = current_time - timer_1; //Channel 1 is current_time - timer_1.
      }
      //Channel 2=========================================
      if(PINB & B00000010 ) { //Is input 9 high?
        if(last_channel_2 == 0) { //Input 9 changed from 0 to 1.
          last_channel_2 = 1; //Remember current input state.
          timer_2 = current_time; //Set timer_2 to current_time.
        }
      } else if(last_channel_2 == 1) { //Input 9 is not high and changed from 1 to 0.
        last_channel_2 = 0; //Remember current input state.
        receiver_input[2] = current_time - timer_2; //Channel 2 is current_time - timer_2.
      }
      //Channel 3=========================================
      if(PINB & B00000100 ) { //Is input 10 high?
        if(last_channel_3 == 0) { //Input 10 changed from 0 to 1.
          last_channel_3 = 1; //Remember current input state.
          timer_3 = current_time; //Set timer_3 to current_time.
        }
      } else if(last_channel_3 == 1) { //Input 10 is not high and changed from 1 to 0.
        last_channel_3 = 0; //Remember current input state.
        receiver_input[3] = current_time - timer_3; //Channel 3 is current_time - timer_3.
      }
      //Channel 4=========================================
      if(PINB & B00001000 ) { //Is input 11 high?
        if(last_channel_4 == 0) { //Input 11 changed from 0 to 1.
          last_channel_4 = 1; //Remember current input state.
          timer_4 = current_time; //Set timer_4 to current_time.
        }
      } else if(last_channel_4 == 1) { //Input 11 is not high and changed from 1 to 0.
        last_channel_4 = 0; //Remember current input state.
        receiver_input[4] = current_time - timer_4; //Channel 4 is current_time - timer_4.
      }
    }

    void set_gyro_registers() {
      //Set up the MPU-6050
      if(eeprom_data[31] == 1) {
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x6B); //We want to write to the PWR_MGMT_1 register (6B hex)
        Wire.write(0x00); //Set the register bits as 00000000 to activate the gyro
        Wire.endTransmission(); //End the transmission with the gyro.
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x1B); //We want to write to the GYRO_CONFIG register (1B hex)
        Wire.write(0x08); //Set the register bits as 00001000 (500dps full scale)
        Wire.endTransmission(); //End the transmission with the gyro
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x1C); //We want to write to the ACCEL_CONFIG register (1A hex)
        Wire.write(0x10); //Set the register bits as 00010000 (+/- 8g full scale range)
        Wire.endTransmission(); //End the transmission with the gyro
        //Let's perform a random register check to see if the values are written correct
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search
        Wire.write(0x1B); //Start reading @ register 0x1B
        Wire.endTransmission(); //End the transmission
        Wire.requestFrom(gyro_address, 1); //Request 1 bytes from the gyro
        while(Wire.available() < 1); //Wait until the 6 bytes are received
        if(Wire.read() != 0x08) { //Check if the value is 0x08
          digitalWrite(12,HIGH); //Turn on the warning led
          while(1)delay(10); //Stay in this loop for ever
        }
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search
        Wire.write(0x1A); //We want to write to the CONFIG register (1A hex)
        Wire.write(0x03); //Set the register bits as 00000011 (Set Digital Low Pass Filter to ~43Hz)
        Wire.endTransmission(); //End the transmission with the gyro
      }

body:
As no preview is available at the given links (for [YMFC-AL_setup.ino](https://drive.google.com/file/d/0B5tJTKkHim16NFZUenB6elZEbDA/view) and [YMFC-AL_Flight_controller.ino](https://drive.google.com/file/d/0B5tJTKkHim16VDFhdHhNUDVOcTA/view) at drive.google.com) and I don't want to download the code to my system, I haven't looked at the whole program; however, from the code included in the question, it's clear that it uses direct IO rather than Arduino API IO.

Direct IO expressions like `PINB & B00000001` [see Edit 1, Note 1] affect differently-numbered digital pins on the Mega than on the Uno or Nano.  (Or, more generally, on boards based on ATmega256x vs ATmega328x or 168x vs ATmega32U4 or 16U4.)

On the Arduino Nano and Uno, PB0–PB5 are assigned to Arduino digital pins 8–13.

On the Arduino Micro with 32U4, PB0–PB3 are not assigned to Arduino digital pins; they connect to SS, SCK, MOSI, MISO, while PB4–PB7 are assigned to Arduino digital pins 8–11.

On the Arduino Mega2560 with  ATmega2560,  PB0–PB3 are assigned to Arduino digital pins 53, 52, 51, 50 respectively, and PB4–PB7 are assigned to 10–13.

Summary:  To adapt direct IO code written for an Uno to a Mega, you may need to change ports and pins numbers.  Just moving wires around to corresponding pins may or may not fix problems; if the code uses a mix of direct IO and API IO (with `digitalWrite()` etc.) the code may need to be changed as well.  For example, in `setup()` it might use API pin identifiers, and in ISRs might use direct IO, an approach that will malfunction when transferring code to a differently-mapped board.

Note, see [numerous excellent pinout diagrams](http://www.pighixxx.com/test/pinoutspg/) at pighixxx.com.

*Edit 1:*

Note 1:  In a file called `binary.h`, the Arduino IDE's programming environment defines a set of 510 constants whose names consist of a `B` followed by from 1 to 8 zeroes and ones, with values equal to corresponding binary numbers.  The value of the expression `PINB & B00000001` is equal to the low-order bit (PB0) of input register PINB.    The value of `PINB & B00001000` is 8 (ie, 1<<3) if PB3 is high, and is 0 if PB3 is low.  Typically, these binary constants are used as *bit masks* for bit operations (AND &, OR |, XOR ^).

Note 2:  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k.  (Alternately, highlight the code and click the `{}` icon in the toolbar at the top of the editing box.)

Rather large sections of code can be pasted into questions and answers.  Generally, paste in at least enough to be compilable and exhibit the problem.  If any variable or procedure definitions, `#include` lines, etc., are left out, people may have to play guessing games to answer the question, and that's generally undesirable as it wastes time and does not elicit good answers.


body: The sketch uses I2C to communicate with the Gyro / Accelerometer. On a Uno these pins are A4 (SDA) and A5 (SCL). On a Mega these pins are 20 (SDA) and 21 (SCL).


message:
Call function and not came back

Im having a little problem with my code. here i called a function to make a test, if it passed it goes back and continue if it doesn't it goes to main loop.

    void loop()
    {

        if (call == 1)
        {
            funca();
        }
        print("waiting..");
    }
     void funca()
        {
            gsmtest();
            print("calling..")
        }
     void gsmtest()
        {
            if (test==1)
                 {
                print("test ok");
                 }
            else
                  {
                    print("error");
                    loop();
                  }
        }
here is a simple example, if u press call, the code goes to funca which make a call to gsmtest. if test goes ok it print "calling.." if not it print "error" and goes back to loop. for some reasons here if test failed, it print error and than goes to loop after that it print "calling.." (continuing funca which i want to abort it if test goes wrong) .

body:
You're overflowing your stack due to infinite recursion.

By explicitly calling `loop()` you are breaking the whole call stack system. You effectively have:

    loop() ->
      funca() ->
        gsmtest() ->
          loop() ->
            funca() ->
              gsmtest() ->
                etc...

Instead of>

    loop() ->
        funca() ->
            gsmtest()
        <-
    <-

Instead of calling `loop()` you should use `return;` to "return" back to where the function was called from.

For example:

    void loop() {
     if (call == 1) {
      funca();
     }
     print("waiting..");
    }

    void funca() {
     if (!gsmtest()) return;
     print("calling..")
    }

    bool gsmtest() {
     if (test == 1) {
      print("test ok");
     } else {
      print("error");
      return false;
     }
        return true;
    }


message:
Why is D3 not activating?

So I made this circuit + a momentary push button on D2 and GND: [![enter image description here][1]][1]

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

Because I don't use a real arduino, I use the RAW port to act like the +5V port. It all worked with a single LED without the npn transistor. Now, with the transistor, the strip of LED's doesn't turn off anymore when I hit the button. The code:

     #include <SoftwareSerial.h>

      #include <Keyboard.h>

      boolean toggle = false;
      int inPin = 2;
      int outPin = 3;

      int state = HIGH;
      int ledOn;
      int reading;
      int previous = LOW;

      long time = 0;
      long debounce = 200;

      void setup() {
        // make pin 2 an input and turn on the
        // pullup resistor so it goes high unless
        // connected to ground:
        pinMode(inPin, INPUT_PULLUP);
        pinMode(outPin, OUTPUT);
        Keyboard.begin();
      }

      void loop()
      {
        reading = digitalRead(inPin);
        ledOn = digitalRead(outPin);

        // if the input just went from LOW and HIGH and we've waited long enough
        // to ignore any noise on the circuit, toggle the output pin and remember
        // the time
        if ((reading == LOW) and (ledOn == LOW)) {
          state = HIGH;
          Keyboard.press((char) 128);
          Keyboard.press('r');
          delay(50);
          Keyboard.releaseAll();
          delay(200);
        }

        if ((reading == LOW) and (ledOn == HIGH)) {
          state = LOW;
          Keyboard.press((char) 32);
          delay(10);
          Keyboard.releaseAll();
          delay(100);
          Keyboard.press((char) 177);
          delay(10);
          Keyboard.releaseAll();
          delay(200);

          time = millis();
        }

        digitalWrite(outPin, state);

        previous = reading;
      }

body:
You need to adjust the value of Rc, the collector current limiting resistor. When replacing the single LED with a strip of N LEDs of the same kind, you have increased N times the current required (that's why you need to use a BJT, because the Arduino I/O pins won't supply that much current). So, you need a new value for that resistor, let's call it Rc', much lower: Rc' = Rc/N. Otherwise, the old value may limit the current far below of what the LEDs need to light up.

But that's not all. You also need to add 2 resistors:

 1. Rb: a current limiting resistor between D3 and the BJT base. Its value should be in the range 330 - 2200 Ohm. The higher the current draw of the LED strip, the lower the value of Rb should be.
 2. Rpd: a pull-down resistor between the BJT base and ground to avoid it floating while D3 is not initialised as `OUTPUT`. Make it at least 20x the value of Rb.

All this should be enough to make it work.


body:
Looks like Eric has beaten me to it with his answer, which is more thorough than mine, but I'll explain why the base resistor works anyway.

Your code relies on reading the level of a pin set to output.  It will only switch off the output if that output is already reading "high".

If you don't have a resistor on the base, then a pretty high current will flow from base to emitter.  This will pull the level of the output down below the threshold for "high", even if it's being driven.  (It also might blow the output, but I guess you have been lucky.)

It's unusual, even if perhaps not "wrong", to read the value of an output.  I'd use a global or static variable to hold the on/off state, rather than reading it.


message:
DS1307RTC Outputting cryptic 165/165/2165 date. What are some possible fixes?

My board.

![Arduino Board](https://i.stack.imgur.com/z9L5V.jpg)

I think I have it wired correctly (the lights aren't, but the board is).

I've read through the first few Google results to no avail.

My sample code to test the chip:

    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(57600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
         rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
        }

    void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
    }

Serial output:

    `RTC is NOT running!
    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

body:
Your picure shows also another device on the bread board. Remove that and ensure that:

Uno Ground --> 1307 Ground

Uno 5Volt --> 1307 +5v

Uno A4 --> 1307 Data

Uno A5 --> 1307 Clock

If the 1307 has a power led indicator, it should be lit.

If that still does not work, then in the code, comment this line out:

    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

and uncomment this line to set the 1307 with a specific time stamp:

    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));


body:
Had the same issue, however, my RTC was 1302 (not 1307) and yours seems to be as well, please check.
If it's 1302, use this library:
https://github.com/msparks/arduino-ds1302

Also, make sure you connect pins like this:

 1. Arduino Pin 7 goes to CLK
 2. Arduino Pin 6 goes to DAT
 3. Arduino Pin 5 goes to RST
 4. Arduino 5+ goes to VCC
 5. Arduino GND goes to GND


body:
Put in the following line in void setup():

    Wire.begin();

(Assuming Wire library has been included.)
This will set up the I2C connection between the Master (Arduino) and the Slave (RTC).

For more generic use, the syntax is: Wire.begin(address);

The complete code is:

    void setup () {
      Wire.begin();
      Serial.begin(9600);
      //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // UNCOMMENT TO SET TIME & DATE TO THAT AT COMPILATION.
      //rtc.adjust(DateTime(2017, 8, 31, 14, 45, 14 )); // UNCOMMENT TO SET TIME & DATE MANUALLY. (YEAR, MONTH, DAY, 24-HOUR, MINUTE, SECOND)

    }


body:
On the DS3231 seems like the device can get unsynchronized with the microcontroller. Not sure if the same problem with DS1307 I think worth trying.
My [complete solution][1] on stackoverflow for the same question

> The I2C interface is accessible whenever either VCC or VBAT is at a
> valid level. If a microcontroller connected to the DS3231 resets
> because of a loss of VCC or other event, it is possible that the
> microcontroller and DS3231 I2C communications could become
> unsynchronized, e.g., the microcontroller resets while reading data
> from the DS3231. When the microcontroller resets, the DS3231 I2C
> interface may be placed into a known state by toggling SCL until SDA
> is observed to be at a high level. At that point the microcontroller
> should pull SDA low while SCL is high, generating a START condition.

  [1]: https://stackoverflow.com/a/47027763/1976512


body:
I can verify that the 1302 does not work with the 1307 library.  Very different chips.  No I2C on the 1302.  I'm trying to setup an autosync with the 1302 by studying how the 1307 does it... not having a lot of success.
I did it once before, and it is driving me bonkers that I can't figure it out again.


body:
I had the same "165" problem.  Very intermittent.  Turns out that I was drawing too much power from the Arduino rails for the circuit I was controlling.  I was being lazy by not powering it independently when I started.  Nick Gannon on arduino.cc showed where the 165 came from and solved my problem.  He included the bcd math.
https://forum.arduino.cc/index.php?topic=184908.0


body: I had the same exact issue and discovered that the Tiny RTC 1307 board.  I found that the board I had was operating at 3.3v.  Once I moved the board to a 3.3v pin on my Arduino Nano.


body:
I had same issue.
Put in setup `rtc.begin();`


body:
With the Arduino Due, the 165 problem came up intermittently with a knock off DS3231 (compatible with 1307 supposedly).  Tried switching to a different RTC but it didn't help.  Switching to an Arduino Mega 2560 seems to have resolved it.  The Mega 2560 is a lot slower so maybe it was a clock speed issue?  In any case, it was useful for resolving the intermittent issue.

That said, if you always get 165:165 it means your Arduino is not communicating with your RTC.  This is a different problem and won't be solved by switching Arduinos.


message:
Scanning for I2C addresses

I'm trying to find the I2C address of an IMU plugged into my Arduino using the code from this URL: http://playground.arduino.cc/Main/I2cScanner.  However, the program stalls at this stage:

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

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

Why could this be happening?

body:
When the I2C scanner stops, it halts in the function Wire.endTransmission. The cause is a hardware problem of the I2C bus. For example the SDA or SCL are shortcut to something or pull-up resistors are missing (as already mentioned by TisteAndii) or the sensor module is not powered.

I assume that the IMU module has already pull-up resistors for SDA and SCL on the module. Which IMU module is it ? How did you connect it ? Do you have other I2C modules to test the I2C bus ?


message:
Voltage changes but digitalRead always HIGH

- I developed a simple push button project
- I used a wemos D1 mini
- I connected  D3 pin to a pull down 1K resistor.
- I used a multimeter to measure D3 pin voltage.

When I push the button, D3 pin voltage changes from 0.x volt to 4.x volt. But digital read on D3 always return HIGH.

Please help me find the problem.

This in my sketch :
```c++
    int ledPin = D2; // choose the pin for the LED
    int inPin = D3;   // choose the input pin (for a pushbutton)
    int val = 0;     // variable for reading the pin status

    void setup() {

      pinMode(ledPin, OUTPUT);  // declare LED as output
      pinMode(inPin, INPUT);    // declare pushbutton as input
    }

    void loop(){

      val = digitalRead(inPin);  // read input value
      if (val == HIGH) {
        digitalWrite(ledPin, LOW);
      } else {
        digitalWrite(ledPin, HIGH);
      }
    }
```

body:
First of all - read your post before you actually post it. This code is no readable. And if you have problems with electronics add picture of schematics how you connected your board. There can be problem too.

> D3 IO, 10k Pull-up GPIO0

Source: https://www.wemos.cc/product/d1-mini-pro.html

Your D3 pin have internally pull-up so no doubt that it reads HIGH all the time. Connect your board like on picture below or change your reading pin to D0 for example (It has no other function than simple IO).

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

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

<!-- End schematic -->

For this case you can trust internal pull-up but in more complicated projects you should add your own one.

For more information about pull-ups and pull-downs check this article: http://www.electronics-tutorials.ws/logic/pull-up-resistor.html


body:
The problem is that when the button isn't pressed, the voltage at pin D3 is just floating. Since there is nothing attached, the voltage at the pin can be anything. To prevent this, you use a pull-down resistor, so that when the button isn't pressed, the voltage at D3 is pulled to ground, and you will get a LOW using digitalRead.

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

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

<!-- End schematic -->


message:
MIDI and DMX together

I am fully new to Arduino (even don't have one ... yet), however, I'm looking into possibilities to use both MIDI in/out and DMX together. If I understand correctly the MIDI library (re)uses the UART/COM while the DMX does the same.

I am wondering if it can be used together (e.g. use MIDI in to control MIDI out and/or DMX out).

(Also still checking if I would need some simple MIDI/DMX components or 'full' MIDI or DMX shields/boards.)

body:
Yes you can use multiple UART/Serial devices with a single Arduino.

However, there are some things to consider:

The Arduino Uno supports a single [hardware serial connection](https://www.arduino.cc/en/reference/serial) (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.

The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.

Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.


body:
The DmxSimple/DmxMaster library does not use serial and will work simultaneously with the MIDI library by 47 Effects.  I have used the Sparkfun MIDI shield with the Tinkerkit DMX shield.  The trick to stacking them is using tall headers on the MIDI shield and not soldering the XLR connectors on the DMX shield.

Or you can use a Teensy which has multiple hardware serials and more RAM at a good price but requires building a couple basic circuits.


message:
Multiple push buttons

I am behind a problem of controling multiple leds with multiple push buttons. Lets say that I have 5 push buttons and 3 leds. Led1 turns on if at least 1 out of the 5 push buttons is pressed. Led2 turns on if at lest 3 push buttons are pressed and Led3 turns on if at least 4 push buttons are pressed.
How can this be solved ? With if else ?arrays?
here is my code that i have

     const int led1 = 2;
     const int led2 = 3;
     const int led3 = 4;
     const int bp1 = 9;
     const int bp2 = 8;
     const int bp3 = 7;
     const int bp4 = 6;
     const int bp5 = 5;
     int state;

    void setup()
     {
     Serial.begin(9600);
     pinMode(led1, OUTPUT);
     pinMode(led2, OUTPUT);
     pinMode(led3, OUTPUT);
     pinMode(bp1, INPUT);
     pinMode(bp2, INPUT);
     pinMode(bp3, INPUT);
     pinMode(bp4, INPUT);
     pinMode(bp5, INPUT);
    }

    void loop()
    {
     state = digitalRead(bp1);
     state = digitalRead(bp2);
     state = digitalRead(bp3);
     state = digitalRead(bp4);
     state = digitalRead(bp5);
    if (state = HIGH)
    { digitalWrite(led1, HIGH); }

    if (state = 3 )
    { digitalWrite(led2, HIGH);
    if (state >= 4);
    { digitalWrite(led3, HIGH); }
    }
    else { digitalWrite(led1, LOW); }
    }

body:
Your code won't work as is. Each time you assign a value to `state` you're overwriting it in the next line. You could, for example have multiple int state variables such as `state1` for the first line in the loop then `state2` in the second etc. Then you need to compare values (don't use `=` on its own in a compare as it will assign the value being tested - use `==` instead). This way you gather all the button states first.

Or you could test the state of a button and if pressed add 1 to `state`:

    if (digitalRead(bp1)) {
        state++};

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.

However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.

R3.


body:
I would do this:

     state = (state & ~STATE_MASK1) | ((digitalRead(bp1)==HIGH)?STATE_MASK1:0); //assuming buttons are active high
    ...

    if (state & STATE_MASK1)
    { digitalWrite(led1, HIGH); }

it holds up to 8 button states for a uint8_t type.

edit: here is a quick implementation.

 //state = 0;           //reset the state

 //read the buttons - all active high
 state = (digitalRead(bp1)==HIGH)?STATE_BP1:0;
 state|= (digitalRead(bp2)==HIGH)?STATE_BP2:0;
 state|= (digitalRead(bp3)==HIGH)?STATE_BP3:0;
 state|= (digitalRead(bp4)==HIGH)?STATE_BP4:0;
 state|= (digitalRead(bp5)==HIGH)?STATE_BP5:0;

 //process the buttons
 digitalWrite(led1, (state & STATE_BP1)?HIGH:LOW); //active high - led1 is high if bp1 is high
 digitalWrite(led2, (state & (STATE_BP2 | STATE_BP4))?LOW:HIGH); //active low - led2 mimics bp2|bp4 => led2 high if both bp2+bp4 are low
 digitalWrite(led3, ((state & STATE_BP3) && (~state & STATE_BP5))?HIGH:LOW); //active high -> led3 is high if bp3 is high and bp5 low

the code controls 3 leds:

1. led1: it mimics bp1;

2. led2: it goes high if both bp2/bp4 are high;

3. led3: it goes high if bp3 is high and bp5 is low.

I picked the output logic for no particular reason.

here is the output:

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

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

you can check the waveform against the logic, :)

again, this is just one particular implementation and you can write your own code / logic to produce your desired outcome. the principle is the same.


body:
To get the functionality you want the code should be:

    void loop()
    {
     state = 0;
     if (digitalRead(bp1) == HIGH)
       state = state + 1;
     if (digitalRead(bp2) == HIGH)
       state = state + 1;
     if (digitalRead(bp3) == HIGH)
       state = state + 1;
     if (digitalRead(bp4) == HIGH)
       state = state + 1;
     if (digitalRead(bp5) == HIGH)
       state = state + 1;

     if (state >= 1)
       digitalWrite(led1, HIGH);
     else
       digitalWrite(led1, LOW);

     if (state >= 3 )
       digitalWrite(led2, HIGH);
     else
       digitalWrite(led2, LOW);

     if (state >= 4) // you had a ; here.
       digitalWrite(led3, HIGH);
     else
       digitalWrite(led3, LOW);
    }

There are more shorthand ways to write this e.g.`if (digitalRead(bp4) == HIGH) state = state + 1;` could be replaced with `digitalRead(bp4)?state++;` but until you are familiar with programming it's often best to use the longer but clearer way of writing things.

If all you are doing is lighting LEDs then de-bouncing the buttons isn't necessary, any LED flicker caused by the contacts bouncing won't be visible to your eye.

If however at a later date you want to trigger other logic in your program to run once per button press then you will need to worry about that. All buttons and switches bounce a little when you close them, without something in the electronics or software to cope with that a single button press can look like a dozen very quick presses to your software.


body:
I solved my problem by myself with if..else structures. I am happy that I got this working and I learned something new. Thank you all for help and inputs.

    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int bp1 = 9;
    int bp2 = 8;
    int bp3 = 7;
    int bp4 = 6;
    int bp5 = 5;

    void setup()
     {
     Serial.begin(9600);
     pinMode(led1, OUTPUT);
     pinMode(led2, OUTPUT);
     pinMode(led3, OUTPUT);
     pinMode(bp1, INPUT);
     pinMode(bp2, INPUT);
     pinMode(bp3, INPUT);
     pinMode(bp4, INPUT);
     pinMode(bp5, INPUT);

    }

    void loop()

    {

    if (digitalRead(bp1)== HIGH or digitalRead(bp2)== HIGH or digitalRead(bp3)== HIGH or digitalRead(bp4)== HIGH or digitalRead(bp5)== HIGH )
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
     }
    else
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);

     }

    if (digitalRead(bp1)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH)
        {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, LOW);
        digitalWrite(led3, HIGH);
        }
    else
      {
       digitalWrite(led1, HIGH);
       digitalWrite(led2, HIGH);
       digitalWrite(led3, HIGH);
       }

    if (digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH)
       {digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        digitalWrite(led3, LOW);
    }

    else
     {  digitalWrite(led1, HIGH);
       digitalWrite(led2, HIGH);
       digitalWrite(led3, HIGH);
       }

    }


message:
Arduino whack-a-mole game not working

Everyone, I am new to this. Currently I am trying to make a Whack-a-mole game for my school project. There will be a total of 6 moles (corresponding to 6 LEDs, which will light up randomly). At each moment, there will only be one LED lit up. The whole game duration is 30 seconds. At the end of the game, the score will be displayed.

I use a piezo electric sensor to detect the knock of the user. I program it in such a way that if the reading of the piezo sensor is greater than 50, it will take it as knock, and if the user knocks it correctly, one point will be awarded.

But unfortunately my code isn't working. The score displayed appears to be random numbers, doesn't work as it is supposed to be.

Here is my code, please hep me to have a look and provide me with some guidance. Thank you.

    unsigned long time_since_reset;
    int previousNum=0;
    int currentNum =0;
    int randomGenerator (void);
    void light(int port);
    int checker(int port);
    int score =0;

    void setup() {
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      time_since_reset = millis();
      while((millis()-time_since_reset)<30000) {
        randomSeed(analogRead(0));
        currentNum = randomGenerator();
        light(currentNum);
        checker(currentNum);
      }
      Serial.println("End Game");
      Serial.println(score);
    }

    int randomGenerator(void) {
      int cNum;
      cNum = random(3, 8);
      if(cNum!= previousNum) {
        return cNum;
      }
    }

    void light(int port) {
      digitalWrite(port,HIGH);
      delay(1000);
    }

    int checker(int port) {
      jump:
      int mole1 = analogRead(0);
      int mole2 = analogRead(1);
      int mole3 = analogRead(2);
      int mole4 = analogRead(3);
      int mole5 = analogRead(4);
      int mole6 = analogRead(5);
      while(mole1<10 && mole2<10 && mole3<10 && mole4<10 &&mole5<10 &&mole6<10) {
        goto jump;
      }
      if(mole1>50 && port == 3) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole2>50 && port == 4) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole3>50 && port == 5) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole4>50 && port == 6) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole5>50 && port == 7) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole6>50 && port == 8) {
        score++;
        digitalWrite(port, LOW);
      }
    }

body:
The code as shown has a bunch of problems; the probably-most-important are as follows.

• `score` is not initialized.  Add `score = 0;` after
 `time_since_reset = millis();`

• As noted in a comment, the `delay(1000)` statement in `light()` prevents checking for whacks during the first second of a light being on.  This probably is undesirable – most people expect to whack a mole much sooner than a second after it appears.  If you want a delay there, make it at most 20 milliseconds. [See edit 2]

• The sequence `randomSeed(analogRead(0)); currentNum = randomGenerator();` has a good chance of generating the same value of `currentNum` several times in a row, which may result in multiple counts for a given whack.

• Instead of saying `randomSeed(analogRead(0));` within the inner loop, say it just after `time_since_reset = millis();` or (probably better) in `setup()`.  If `analogRead(0)` changes slowly, the same random seed may get used over and over, resulting in the same sequence of numbers from the `random(3,8)` expression.

• Your `randomGenerator()` routine has undefined behavior:  It doesn't return a valid result if the current random  number is the same as the previous one.  You could add a loop that calls `random()` again if the value is the same as before; but not returning a value results in  undefined behavior.

*Edit 2:*  When you turn a light on, record the current `millis()` time reading, say in `onTime[i]` for light `i`, and set flag `isOn[i]` true.  Later, when `isOn[i] && (millis()-onTime[i] > targetDelay[i])`, turn the light off and clear the flag (via `isOn[i] = false`).  Within `checker()`, a condition like `port == 6` translates to `isOn[6]`, an expression which is true when light 6 is on, else false.

The approach of using arrays like `onTime[]` and `isOn[]` and `targetDelay[]`, variable subscripts, and recorded on-times has several benefits:  It lets you loop through lights, getting rid of that needlessly repetitious code in `checker()`; it enables other processing in the main game loop (such as whack-testing) to proceed independently of light control; it allows multiple moles to pop up at the same time; and it allows different moles to have different or varying up times.


body:
Others have already mentioned the issues with the timing, score initialization and random number generation.

On your checker function you have 2 errors and one ugly piece of code.

Ugly code first - goto is BAD. About the only time it's acceptable is under an error condition, the rest of the time if you find yourself needing to use a goto then look at how you can improve the code structure.

Errors - You exist after an analog input is > 10 but only count >50 as a hit. As they hit it the value will ramp up so they hit a target you could see a value of 10, exit your loop and not score anything. You need to use the same threshold for both. (Another style point, if you have the same magic number in two places (e.g. 10 or 50) consider making them constants or #defines rather than hard coded numbers. It makes it a lot easier to change them without forgetting one of the locations).

The second error is that you only turn the LED off if they hit the correct target, if they get the wrong one you light the next target but never turn the first LED off.

The code below should solve all of these issues.

    int checker(int port){

      char exit = 0;
      int mole;
      while (!exit) {                // until we get a hit
        for (int i = 0; i<5; i++) {  // check each mole in turn
          mole = analogRead(i);      // read the sensor
          if (mole < 50) {           // if over the threshold
            exit = 1;                // exit the while loop after this check
            if (i + 3 == port)       // see if they got the correct target. i goes 0-5, port goes 3-8
              score++;
            digitalWrite(port,LOW);  // turn the LED off
            break;                   // break out of the for loop
          }                          // end if hit
        }                            // end for loop
      }                              // end while loop
    }


message:
Control time without delay() Arduino

For the last couple of day I've been trying and failed many times just to not use the delay() funtion in Arduino. I have to admitted that my coding skill are extremely bad.

What i trying to do is:
If button is pressed:
Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop.
else:
Motor A and B both stop.

I managed to wrote the code by using delay function for that 1 second. However i got no idea how to do it WITHOUT DELAY() there will be sensor reading as well at the same time, i cant afford that 1 second delay of sensor reading).

Here is my code:

    int dir1PinA = 2;
    int dir2PinA = 3;
    int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

    // Motor 2
    int dir1PinB = 4;
    int dir2PinB = 5;
    int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

    int button = 6;

    void setup() {  // Setup runs once per reset
    // initialize serial communication @ 9600 baud:
    Serial.begin(9600);

    //Define L298N Dual H-Bridge Motor Controller Pins

    pinMode(dir1PinA,OUTPUT);
    pinMode(dir2PinA,OUTPUT);
    pinMode(speedPinA,OUTPUT);
    pinMode(dir1PinB,OUTPUT);
    pinMode(dir2PinB,OUTPUT);
    pinMode(speedPinB,OUTPUT);

    // Define button pin
    pinMode(button,INPUT);

    }

    void loop() {
      if( button == LOW){           // if button is pressed
        // Motor A (move slow) and B  moving
        analogWrite(speedPinA, 100);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, HIGH);
        analogWrite(speedPinB, 255);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, HIGH);
        delay(1000);

        // After 1 second Motr A (move fast)and B stop every time button pressed
        analogWrite(speedPinA, 255);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, HIGH);
        analogWrite(speedPinB, 0);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, LOW);
      }
      else
      {
        // Both motor not moving
        analogWrite(speedPinA, 0);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, LOW);
        analogWrite(speedPinB, 0);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, LOW);
      }
    }

Please point me out the direction or give me an example of code. And I have already try the Blinkwithoutdelay Arduino example but it does not work for this case.

Very much appreciated.

body:
Assuming the button isn't held down for 50 days straight, you can use the [millis()][1] function and basically set a marker of the current time when the user pushes the button down. To do this, you need to detect when the user switches from off to on, not when while the button is pushed or you'll be resetting the marker every time.

Then you record the time every loop while the button is pushed down. If the current time is more than one second after the time recorded by the marker, you switch motor B off and make motor A as fast speed like you said. When the button is off, like you said set both motors to off.

  [1]: https://www.arduino.cc/en/reference/millis


body:
You might want to use a timer. There are some libraries available for Arduino that precisely do that.

You can either use a library that implements a software timer (something similar to comparing `millis()`, but with powerful additional built-in features such as button debouncing, timed pulses, etc.) or use a library that deals with the hardware interrupts of the MCU.

As an example take a look at this particular library: [Timer][1]. I think you'll love it!

  [1]: http://playground.arduino.cc/Code/Timer


body:
>  If button is pressed: Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop. else: Motor A and B both stop.

I would do a quick state machine:

>    STATE / button released: do nothing;
    STATE / button pressed: run motors a+b;
    STATE / run motor a+b: run motor a+b; if 1 second has passed, advance to just run motor a;
    STATE / run motor a: run motor a at fast speed and stop motor b.

fairly easy to code as well.


message:
USB DEVICES WITH THE 32U4?

I have an Arduino Pro micro and I need to know if it is possible to use an USB device like a camera or things like that Since the processor is a 32U4. the USB Shield is for the Arduino Uno and I don't want to buy more stuff.

body:
Some important facts:

* The 32U4 cannot act as a USB master, only a USB device (it doesn't have a USB OTG interface).
* The USB shield is an SPI based device. It can communicate with any host MCU that can use SPI, as long as you can wire it in properly.
* The Arduino doesn't have the processing power or memory to deal with the sheer onslaught of data a USB camera sends.

So yes, you could use the USB shield with a 32U4 based board if you can work out the right wiring. However you will not be able to use things like cameras with it since you lack the processing power to do it.

For camera work you need something more like a Raspberry Pi.


message:
Accelerometer (I2C) and Fona Shield (software serial) won't work together

I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.

My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:

    fonaSerial->begin(4800);

    fona.begin(*fonaSerial);

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona.
http://pasteboard.co/A16708fo3.png

My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.

My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?

This is quite urgent so a quick responses are greatly appreciated!

My Code:

    #include <Adafruit_FONA.h>
    #include <Adafruit_Sensor.h>
    #include <My2_Adafruit_LSM303_U.h>
    #include <Wire.h>

    #define FONA_RX 2
    #define FONA_TX 3
    #define FONA_RST 4

    #include <SoftwareSerial.h>
    SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
    SoftwareSerial *fonaSerial = &fonaSS;

    Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

    volatile byte accelMagnitude;

    Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

    void setup() {
      // put your setup code here, to run once:

        accel.begin();

        Serial.begin(115200);

        fonaSerial->begin(4800);
        fona.begin(*fonaSerial);

    }

    void ReadAccel(){

    //Get a new accelerometer sensor event
      sensors_event_t event;
     // Serial.println(F("Accel---------"));
      accel.getEvent(&event);

      accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

    }

    void loop() {
        // put your main code here, to run repeatedly:

        ReadAccel();

        if (accelMagnitude > 20){

            while (accelMagnitude > 20){

                Serial.println("waiting");
                ReadAccel();
            }

            Serial.println("Over 20");

        }
    }

body:
As Gerben suggests, it would not be a good practice to just add a delay and call it a day.

1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and

2) FONA has `getNetworkStatus();` make a small control loop and query it until you get status 1 or 5, depending on what network are you on.
From FONA's example:

    if (n == 0) Serial.println(F("Not registered"));
    if (n == 1) Serial.println(F("Registered (home)"));
    if (n == 2) Serial.println(F("Not registered (searching)"));
    if (n == 3) Serial.println(F("Denied"));
    if (n == 4) Serial.println(F("Unknown"));
    if (n == 5) Serial.println(F("Registered roaming"));

And then proceed with the rest of your code. You can make additional checks for signal quality with `getRSSI();`


message:
Serialprint and analogRead time

How much time takes to print each sample using `Serial.print` and `analogRead` in each iteration?

    #include <SoftwareSerial.h>
    #define Sensor A0
    void setup() {
      Serial.begin(250000);
      pinMode(Sensor,INPUT);
        }
    void loop() {
      Serial.println(analogRead(Sensor));// RUN TIME??
    }

body:
It is quite complex to work out how "long" it will take to print.  Why?

1. If there is room in the serial buffer then the text just gets placed in that buffer. Takes almost no time at all to print.
2. You are printing a variable length string. The longer the string the longer it will take to print if the buffer is full.

However:

* Each character consists of 10 *symbols* (8 data bits plus 1 start and 1 stop bit).
* Characters are transmitted at 250000 symbols per second
* Thus each character takes 1/(250000 / 10), or 40 microseconds to transfer through the actual wire.

So printing the number 100, which also has `\r\n` appended to it (characters 13 and 10) would need 5 characters. If the buffer is full it will take about 5*0.00004s = 200µs. If the buffer isn't full, it will take a fraction of that to just copy the data into the serial buffer.


body:
1000 rounds of analogRead() takes about 100ms.

sustained serial writes will depend mostly on the baud rate picked.


message:
Make device based on CH340G working as keyboard

There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.

I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?

body:
No, it's not possible. The device enumerates as a USB serial device, and the only way to change that is to change the internal silicon of the device.

The closest you could do is (though I have no clue how on Windows) write (or if you are lucky, find) a program that reads serial data through the COM port and somehow injects keyboard commands into the input subsystem of the operating system.


message:
Finding and loading "libraries"

I am 6 months into my Arduino Uno work and I would like a step by step way to find and download a "library". I work using WINDOWS and WORD and although I was eventually successful in getting a 7 segment display library to download and work, I must say I could not do it again since the path I followed was far from clear due to my lack of understanding about basic computer stores etc. I have enjoyed my work with the Uno but I have been very disappointed at lots of "help" offered on other sites since they assume I know far too much. It is a skill to be able to communicate with we lesser people so I am really hoping a step by step guide is possible.
Thanks

body:
Start with the newest Arduino IDE. At this moment that is version 1.8.1.

Try to find the Library Manager. Via the menu: Sketch / Library...

In the Library Manager there is a input field in the upper-right corner where you can search for libraries.

If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.

Your projects are probably at: Documents / Arduino

There is also a folder: Documents / Arduino / libraries

That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


message:
Is there any chance of fixing it?

[![enter image description here][1]][1]I am new to arduino and robotic stuffs and I thought it would be a good idea to test circuits on my breadboard using arduino's R3 5V pin as power supply. The accident happened when I short circuited the things on the breadboard and after a while arduino gave off a nasty smell. The only part overheated on arduino was the left side of the micro-controller. After that I cant upload nor run code on arduino.

After I explained you my situation, can you imagine a potential problem?(e.g I mean is it a voltage regultor problem, a micro-controller faillure, both of them, or something else?)

Can I fix it?

(#1 - I know arduino boards are cheap. I just want to know if I can do anything        with that.

 #2 - No comments about  the accident accepted.)

Thank's in advance.

Regarding the image, my vendor claims the arduino to be an exact copy of "open-source" arduino R3

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

body:
> Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.


body:
> Can I fix it?

it depends on your skills and the nature of the problem and how far you are willing to go to fix it.

I would first try to rule out a supply problem - very rarely a mcu will burn to the extent of giving off smells / overheat. So unplug the mcu and use a multimeter to measure its Vcc vs. GND pin voltage, test trace continuity, etc.

after that, plug in a new / known good chip and see if you could upload code to it.


message:
Arduino based SPI programming of LT1257 not working

I am trying to talk to an [LT1257][1] using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.
[![LT1257 timing diagram][2]][2]

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).

    #include<SPI.h>
    #define SCLK 13
    #define MISO 12
    #define MOSI 11
    #define DAC_LOAD 5

    #define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

    void setup()
    {
    Serial.begin(9600);
    init();
    SPI.begin();
    dac_write();
    }

    void init()
    {
    pinMode(SCLK, OUTPUT);
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(DAC_LOAD, OUTPUT);
    digitalWrite(SCLK, HIGH);
    digitalWrite(MOSI, HIGH);
    digitalWrite(DAC_LOAD, HIGH);
    }

    void dac_write()
    {
    SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
    delay(10);
    SPI.transfer(0x0000);
    delay(10);
    digitalWrite(DAC_LOAD, LOW);
    delay(10);
    digitalWrite(DAC_LOAD, HIGH);
    delay(10);
    SPI.endTransaction();
    }

    void loop()
    {
    while(1)
    {
    Serial.println("Ping!");
    delay(1000);
    }
    }

  [1]: http://cds.linear.com/docs/en/datasheet/1257fc.pdf
  [2]: https://i.stack.imgur.com/UWC9q.png

body: I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.


message:
Input Capture Pin Atmel ATmega328P

I have some code that relies on the input capture timer value.

I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

If you want code or more detail ask in comments and I will post code.

body:
> I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

yes, unless your code writes to the registers involved.


body:
The way IC typically works is completely independent from the CPU and what instructions you are running.

The timer runs freely between the start and end input capture events. At the moment of capture the timer value is frozen into another register. The interrupt is then triggered. You then read that frozen value. It doesn't matter how long after the end event the interrupt executes, or what you do in that interrupt, the captured time is still the same.


message:
X and Y axis on Arduino Serial Plotter?

I am trying to plot my counter vs. time on the serial plotter, but the values on the y axis are so big there is no way that it's displaying the counter values.
I have printed both values:

      Serial.print("counter: ");
      Serial.println(counter);
      time = millis();
      Serial.print("Time: ");
      Serial.println(time);

I expected time to show up in the x-axis, but I think it's displaying on the y-axis and I'm not sure how to change this.
The plot should just be an increasing line as the counter and time get bigger...
what am I missing?
Thanks.

Slashing out the Serial.print("Time:") does not correct anything.

body: Comment out the `Serial.print("Time: ");` line. The Arduino serial plotter wants only numbers.


body:
To plot multiple values over time you need to output just the numbers on a single line per iteration, and delimit with a space or tab:

    Serial.print(counter);
    Serial.print("\t"); // delimit with tab
    time = millis();
    Serial.print(time);
    Serial.println();

It's worth noting however, the time (x axis) is implied by each line. In essence each line of output advances "time" by 1 unit. So I suspect you'll want to remove the time variable output and just output the count variable by it self.


body:
Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.

    Serial.print(counter);
    Serial.print(" ");
    time = millis();
    Serial.println(time);

OR

    Serial.print(counter);
    Serial.print("\t");
    time = millis();
    Serial.println(time);