title: Arduino Uno-Spider Robot Plan

text:
# Question
Title: 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.

# Answer
> 0 votes
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.

# Answer
> 0 votes
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.

---
Tags: arduino-uno, robotics
---


# Question
Title: 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!

# Answer
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. 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 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
> 8 votes

---
Tags: arduino-nano, usb, mac-os
---


# Question
Title: 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.

# Answer
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?
> 1 votes

---
Tags: arduino-uno, serial, programming, switch, charging
---


title: Motor shields in arduino

text:
# Question
Title: 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?

# Answer
> 1 votes
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, 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.

# Answer
> -1 votes
The dumb ones are basically distributors of power for the servo motors. There are more clever boards that offer the control of multiple servos (usually 10+) by communicating with the Arduino via some higher-than-PWM-level control (Like I2C) thus taking less pins from the Arduino than a dumb servo shield. Both kinds usually require a power supply to power the servos.

G.

---
Tags: servo, arduino-motor-shield
---


# Question
Title: 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, 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?

# Answer
> 1 votes
> 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.

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

---
Tags: arduino-uno, serial, bluetooth, hc-06
---


# Question
Title: How to identify connection lost on HC-06?
I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.

```
int in1 = 4;
int in2 = 5;
int in3 = 6;
int in4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int command = Serial.read();
    move(command);
  }
}

void move(int command) {
    if (command == 'f') forward();
    else if (command == 'b') backward();
    else if (command == 'l') left();
    else if (command == 'L') leftback();
    else if (command == 'r') right();
    else if (command == 'R') rightback();
    else if (command == 's') stop();
}

```

Now what I want is to identify whether there is connection or it is lost. For example:

```
if(Serial.connectionLost()) stop();

```

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

# Answer
My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.

Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) datasheet.

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.
> 1 votes

# Answer
Two possible ways I see:

* Connect the HC-06 LED anode (or cathode, depending on how it's driven) to an Arduino input pin. Since you can tell from the blink frequency if the module is paired with your phone or not, you can use that (through interrupts maybe) as a means to know if you're still connected to your phone.
* Find a way to configure the android app (or write your own app) to either regularly ping your Arduino or to respond to ping requests from the Arduino. If the Arduino fails to get a ping request (in the first case) or a ping response (in the second case) after some pre-agreed interval, it decides the connection has been broken and halts the RC car.

Second way is less messy but may require some android programming skills on your part. I remember coming across an app in the Play Store that sends '#' constantly even when idle, with your own characters in between. That would work as well as a ping, if you could find something similar, and the only programming you'd need to do would be on the Arduino's side.
> 0 votes

---
Tags: arduino-uno, bluetooth, hc-06, l298n
---


# Question
Title: Sending values from Matlab to arduino using serial communication
I want to send numeric value from matlab to arduino but code is not working.

Matlab code is as:

```
doi = 3 ;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
fclose(arduino);

```

Arduino code is as:

```
  int solenoidPin = 13; //This is the output pin on the Arduino
int doi;

void setup()
{
  Serial.begin(9600);
  //pinMode(13, OUTPUT);
  pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
}
void loop()
{

  if(Serial.available()>0)
  {

    doi = Serial.read();
    //Serial.println(doi);
    //Serial.println("\n");
    //doi = doi - 48;
   if (doi == 1)
   {
    //Serial.println(1);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
    delay(1000); //Wait .15 Second
     digitalWrite(solenoidPin, LOW);
    }
  else if (doi == 2)
    {
     //Serial.println(2);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
    delay(2000); //Wait .165 Second
    digitalWrite(solenoidPin, LOW);
    }
  else
    {
      //Serial.println(3);
      digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
      delay(3000); //Wait .180 Second
      digitalWrite(solenoidPin, LOW);
    }

  }
}

```

I used str2num(doi) also instead of `fprintf(arduino, '%s', char(doi))` but no output.

Please give suggestion to correct this.

Thanks.

# Answer
fopen(arduino); takes some time to initialize the serial connection so you should use pause(2); after fopen(arduino); and in fprintf() send doi as interger i.e. fprintf(arduino, '%i', doi);. Suppose the doi is 1 then code would be as

```
doi = 1;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
pause(2);
fprintf(arduino, '%i', doi); % send answer variable content to arduino
fclose(arduino);

```

Another modification required in arduino program as

```
doi = doi - 48;

```

Uncomment this line inside if(Serial.available()\>0) block.
> 0 votes

# Answer
You send a string of ASCII characters representing a number in human readable format.

You then read one of those characters that represents a single digit and then try and use it as if it were a number.

Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.
> 0 votes

---
Tags: arduino-uno, matlab
---


title: Call function and not came back

text:
# Question
Title: 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) .

# Answer
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;
}

```
> 1 votes

---
Tags: arduino-uno, algorithm
---


title: Why is D3 not activating?

text:
# Question
Title: Why is D3 not activating?
So I made this circuit + a momentary push button on D2 and GND:

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

```

# Answer
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.
> 0 votes

# Answer
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.
> 1 votes

---
Tags: led, transistor
---


title: Unable to program Arduino mega2560?

text:
# Question
Title: 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.

```

# Answer
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.
> 3 votes

---
Tags: arduino-mega
---


# Question
Title: avrdude: stk500_recv(): programmer is not responding - OSX10.11
I'm getting the following error with a genuine Arduino Uno on Mac OSX10.11 El Capitan when uploading to it (the green light is on, the orange light flashes intermittently while attempting to upload). Here's the error:

```
avrdude: stk500_recv(): programmer is not responding

```

I've tried all the solutions I can find. I've selected the correct port and board. I've tried pressing the `reset button` before uploading. I've tried different USB cables. I've tried unplugging and replugging everything. I've read this: `http://arduino.cc/en/Guide/Howto` .

I tried all these solutions here: https://stackoverflow.com/questions/23993111/mac-uno-avrdude-stk500-recv-programmer-is-not-responding

I tried the FTDI fix, (but not sure if was actually able to disable the mac drivers, or which drivers are now running, the example I tried is for for OSX 10.10 Here). I ran into the following issue in the Terminal:

```
Mac-Pro:~ m$ cd /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns
Mac-Pro:PlugIns m$ sudo mv AppleUSBFTDI.kext AppleUSBFTDI.disabled
mv: rename AppleUSBFTDI.kext to AppleUSBFTDI.disabled: No such file or directory

```

I don't get why it says `No such file or directory` because `AppleUSBFTDI.kext` definitely exists as a package in the Extensions folder, but I guess it's talking about another file named that in the plugins folder? Confusing ... Was this moved in OSX 10.11 and should I rename this package in the Extensions folder?

I did download and install the old FTDI drivers, but I don't know if they're actually the ones working right now? How do I clarify that?

Any ideas how to get this working?

I also tried on an old Mac Laptop 10.6.8 - Snow Leopard, and had the same issue :(

# Answer
> 2 votes
Has this ever worked? Can you use avrdude and hit the target?
There is a terminal mode in avrdude you can also use. At least this would help you determine what is working.

Sounds like a configuration issue. If you have the ability to 'follow the tail' (tail -f ) I'm assuming that you have 'like' tools we have in Linux like lsusb to assist?

You can ensure yourself that if it says it isn't found, it's not finding it, so it's not wherever it's looking. :)

# Answer
> 1 votes
I had this problem for some time and what I did was I deleted the Arduino IDE and reinstalled it again and it worked. Thanks!

# Answer
> 0 votes
Nothing I tried could get it to work. I took it back on the hunch it was a bad one, that something was just not working right on it. And got a new one directly from the Arduino people. The new one works just fine! Problem solved :D

---
Tags: arduino-uno, ftdi, programmer
---


title: Scanning for I2C addresses

text:
# Question
Title: 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:

Why could this be happening?

# Answer
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 ?
> 2 votes

---
Tags: arduino-uno, i2c
---


# Question
Title: Use doorbell output (12VDC) to power arduino?
Not sure if this is possible, but could I use my existing doorbell setup to power an Arduino? I'd also like to preserve the existing chime's functionality either through the existing button or triggering it through the arduino.

My doorbell chime is made by Nicor and its input is 120VAC, but outputs 12VDC. This seems to be a very unconventional setup, but I've confirmed its output with a multimeter (it's also printed on the chime itself). The chime is very similar to this: http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU (only difference I can see is the output). The 12V line runs to my front door where it's connected to a light up button. Here is a picture of the button's circuitry: https://i.stack.imgur.com/YsSu0.jpg

What I'd like to do is use the chime's 12VDC output to power the arduino so I don't have to rely on another power source or batteries. I will be adding smart features to the doorbell via the arduino, but my main hangup is getting power to the arduino. I've tried connecting the doorbell wires to VIN and ground, which successfully powers on the Arduino, but it also triggers the chime. It appears closing the circuit triggers the chime to play.

Is this possible to do?

# Answer
This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.

The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.

Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.

The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.

So what's the easiest way to accomplish your task?

Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.

You need to replace/augment the LED on the ringer with the Arduino. The 2.2k *R19* could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.

The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit pulls all the current out from under the LED, just as it will an MCU in the same slot.

You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.

So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.

Good luck; sounds like a fun project and a good challenge.

EDIT: I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...
> 3 votes

# Answer
You need to find the transformer for your doorbell system and take the power from there. It seems like somehow you are using the signal wires for the door bell instead of the power wires.

The door bell transformer should/could be in a utility room, closet, by your heating and air unit. once you find that look at the output of the transformer. I know some are AC 12 volts, and I feel like that arduino will not like that...
> 1 votes

# Answer
If your extra features only need to sense the button press, then your arduino can go at the chime and use the 12V source that also powers the chime.

You put an opti-isolator's led side in series with either leads of the button loop. A digital input with high pull-up can read the state of the detector side of the opto-isolator.

This assumes that your extra features do not include providing some kind of visual or auditory output **at the button**. But remember that just because you want to read the button state, you need not detect it at the button physically--just electrically.
> 1 votes

---
Tags: arduino-uno, power
---


title: USB DEVICES WITH THE 32U4?

text:
# Question
Title: 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.

# Answer
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.
> 3 votes

---
Tags: usb, shields, hardware, arduino-pro-micro
---


# Question
Title: How to serve multiple connections with an ESP8266 and an Adruino?
I want to make a server using an ESP8266 (12e) and an Arduino Nano. I have got everything hooked and I created a minimal "Hello World" example, based on a number of samples found on the web, which is working fine... as long as the ESP does not receive multiple requests simultaneously.

I am using SoftwareSerial on pins 8 and 9 of my Arduino Nano.

As long as I send one request at the time, things work fine. If I use two browsers and send two requests with little interval, things go wrong, and that figures: the `sendData()` method just reads from the serial connection. It will consume the new request while waiting for an "OK" from the initial request...

Is there any sample code or library (for ESP + Arduino (nano)) that can handle correctly multiple concurrent connections?

Thanks

My code:

```
/*
  Software serial multple serial test
 */
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(8, 9); // RX, TX

void setup() {

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different : 115200

  Serial.println("Setup...");

  /*
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+GMR\r\n",1000,DEBUG); // get version
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
  */

  sendData("AT+RST\r\n", 2000,DEBUG);
  sendData("AT+GMR\r\n", 1000, DEBUG);

  sendData("AT+CWMODE=1\r\n",1000,DEBUG); // configure as station
  sendData("AT+CWJAP=\"******\",\"*******\"\r\n", 6000, DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Setup ready.");
}

//WIRE RESET TO HIGH!!?

void loop() { // run over and over

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

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

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

     String webpage = "<html><h1>Hello World!</h1></html>";

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

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

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

     sendData(closeCommand,250,DEBUG);
    }
  }

}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "?";
    int pos = -5;

    Serial.println("--------------");
    Serial.println(" sending "+command);

    esp8266.print(command); // send the read character to the esp8266

    long int _timeout = timeout + millis();

    while( (_timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
        pos+=1;
        if(pos>=0 && response.substring(pos) == "\r\nOK\r\n"){
          //WE GOT OK -> stop waiting
          _timeout=0;
        }
      }
    }

    if(debug)
    {
      Serial.println(" response: "+response);
    }

    return response;
}

```

# Answer
> 1 votes
I might not have understood what you are trying to do, but if it is to use the ESP8266 to allow the Nano to connect to WIFI and act as a web server then I believe you are doing this the hard way.

The ESP8266 is an 80 or 160MHz microprocessor with 64KB Program Ram + 96KB data RAM. You are using a 16/32MHz microprocessor to generate pages and pass them to it. I would recommend that you investigate using the Arduino IDE to program the ESP8266 in "Arduino C" it comes with a set of examples that include webservers (which is what I think you are trying to do). Keep the Nano if the ESP8266s 10 digital and one analogue ports aren't enough to interface to you hardware.

# Answer
> 0 votes
I had the same experience. When you send data by an AT command and receive something from another connection at the same time, then the ESP chip starts to behave unexpectedly. Sometimes it sends the data but does not respond with OK. Sometimes it does not send. And sometimes it ignores received data (missing +IPD message).

The AT firmware works only well with single telnet-style connections. I mean half-duplex communication where it never happens that more than one sender is "talking" at the same time.

I hoped that this issue becomes solved over time, but the modules that I bought recently (with AT Firmware 1.4) are still not better. However, I did not notice any unexpected auto-reset or hangup anymore in my 2-Week test loop. At least that became better.

---
Tags: arduino-nano, esp8266, web-server
---


title: Serialprint and analogRead time

text:
# Question
Title: 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??
}

```

# Answer
> 1 votes
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.

# Answer
> 0 votes
1000 rounds of analogRead() takes about 100ms.

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

---
Tags: arduino-uno, softwareserial, analogread, time
---


# Question
Title: 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?

# Answer
> 1 votes
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.

---
Tags: communication
---


title: Control time without delay() Arduino

text:
# Question
Title: 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.

# Answer
> 1 votes
Assuming the button isn't held down for 50 days straight, you can use the millis() 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.

# Answer
> 1 votes
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. I think you'll love it!

# Answer
> 1 votes
> 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.

---
Tags: timing
---


# Question
Title: 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 :

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

```

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

simulate this circuit – Schematic created using CircuitLab
> 6 votes

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

simulate this circuit – Schematic created using CircuitLab

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

---
Tags: esp8266, button, electronics
---


title: Finding and loading "libraries"

text:
# Question
Title: 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

# Answer
> 3 votes
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.

---
Tags: arduino-uno
---


title: Input Capture Pin Atmel ATmega328P

text:
# Question
Title: 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.

# Answer
> 1 votes
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.

# Answer
> 0 votes
> 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.

---
Tags: timers, input
---


# Question
Title: 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).

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

```

# Answer
> 1 votes
As no preview is available at the given links (for YMFC-AL\_setup.ino and YMFC-AL\_Flight\_controller.ino 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 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.

# Answer
> 0 votes
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).

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: How to increase SD card write speed in arduino
I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow.

I've read this hack to improve the write speed, but I'm wondering if a more direct approach is possible, maybe by adjusting the SPISettings.

# Answer
> 12 votes
OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino. But that is not how I solved my problem of low data-rate.

I followed the instruction of the author of SDFat library from ***this post***.

According to *fat16lib*, to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O\_WRITE | O\_CREAT' instead of 'FILE\_WRITE'.

This sure increased the speed by a great factor. But I needed more!

Storing the data in binary (check out this blog) improved the performance even more.

My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card!

Finally, I want to thank you guys for your help.

# Answer
> 4 votes
Many factors would decide if you can reach this wanted speed. Only some of these.

---

## 1. Your Software

The SdFat Library is faster than the standard SD Library of the Arduino IDE. It also has an easy to use compatibility function with the standard SD Library. Try it out.

## 2. Your Hardware

You should use a high class SD Card. As you maybe know SD Cards are sorted into performance classes. Most people in the internet recommend a SanDisk SD Card.

# Answer
> 4 votes
Avoid the handshake getting a buffer!

Use **SD.write(buf,size);**

Hi every one, I'm working in a project with the same issue. I was following the same steps of yours and got exactly the same numbers. I've just fixed it out. The problem is the handshake when you call the `SD.write()`.

Instead:

```
//for each loop, it is going to make a handshake
while(<yourCondition>){
    SD.write(<yourValue>);
}

```

Do:

```
char buf[length];
while(yourCondition){
    buf[index] = yourValue;
}
SD.write(buf,index);//only one handshake

```

In my project the first one I got **4100** bytes, and the second one using a buffer with 128 (buf\[128\]) I got **145408** bytes in my project. Good enough.

---
Tags: sd-card, spi, datalogging, baud-rate
---


title: Is there any chance of fixing it?

text:
# Question
Title: Is there any chance of fixing it?
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

# Answer
> 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.
> 3 votes

# Answer
> 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.
> 1 votes

---
Tags: arduino-uno
---


title: Brownout with Arduino Nano

text:
# Question
Title: Brownout with Arduino Nano
I'm making an RC car with the Arduino Nano. I'm using RF433 as wireless communication with 2 motors and L293D as the motor driver. I use 4 1.5V batteries to power the Arduin and another 6V battery pack to power the motors, and a joystick with an Arduino Mega to send commands through the RF433 to the Arduino Nano.

I've written a program that sends specific digits when the joystick is in a certain position, i.e. when the joystick is "bent" to the front it sends a "1", a "2" is sent when the joystick is bent towards the back, and so on.

**My problem is this:**

When I bend the joystick towards a certain direction, the RC car moves accordingly without problem; However, when I bend the joystick towards another direction the RC car doesn't respond.

I took a look at what the RC car was receiving, and I've noticed that after the first command was sent (when I bend the joystick towards a certain direction), no more commands get to the RC car (in other words the Arduino Nano), and this occurs occasionally. I think this means the Arduino Nano "froze" after the first command.

# Answer
> 2 votes
You have *at least* three problems here:

1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino *even before* it gets loaded down by a motor, and it only gets worse under load

2) L293/L297 and similar **bipolar** bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip. Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.

3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway. You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).

Granted, you may well have other issues as well, such as errors in your software.

---
Tags: motor, arduino-nano, rf
---


# Question
Title: Why does my code or Serial Monitor hang with analogRead?
I have the following code in loop() to collect values from an electret microphone

```
for(int i=0; i<sampleSize; i++){
  analogVal[i]= analogRead(ADC_Pin);
  sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);

```

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC\_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.

My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

# Answer
Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.

I suppose, that `analogVals[]` is declared as `int` and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome `48 bytes` for all your others variables (including `int i` in the for cycle and `Serial` outside it) and stack for calling functions (like `analogRead` and `sq`) and all theirs variables and functions and arguments.

So `int i` = 2B, `Serial` = 2B, `sumOfSquares` = 2B, `"Sum of squares: "` = 17B of what I see takes anothe `23 bytes` of those `48 bytes` leaving us with only **25 bytes** for all else.

I bet, that you try to use more REAM, than you have and so your `stack overflows` and

1. destroys some variable content on the vay
2. is overwriten by assigning to some variables, which then leads to all sort of problems.
> 0 votes

---
Tags: serial, analogread
---


title: Arduino whack-a-mole game not working

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

```

# Answer
> 1 votes
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.

# Answer
> 1 votes
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
}

```

---
Tags: programming, c, code-review, project
---


# Question
Title: Problem burning bootloader on ATmega328P using internal clock
I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this page but I'm getting this error.

```
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 (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

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

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

```

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?

Thanks

**\[EDIT\]**

* I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
* I used the bootloader in "breadboard-1-6-x.zip"
* I am using the Arduino IDE v1.8.1

# Answer
> 1 votes
If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.

# Answer
> 1 votes
As noted in 6v6gt's answer, if the ATmega328 has been set to use a crystal, thereafter a crystal (or an external oscillator) are required for programming, until the fuses have been set to use the internal RC oscillator. Here are a few thoughts, unfortunately somewhat scattered, on the matter.

If you have a parallel programmer (that delivers high voltage to the Reset pin and uses 8-bit parallel data signalling) you can use it to reset the fuses, since with that programming mode the clock is irrelevant.

Also, USBasp programmers interact with Avrdude to generate a programming clock of some specified frequency, 100kHz by default, 8kHz with the “Slow Clock” jumper installed. Also see § “Set the clock in software” within USBasp ICSP programmer quickstart guide at freetronics.com.au. Unlike the Avrdude man page, that reference says the default programming frequency is 375kHz and says “Avrdude’s -B option allows you to set the programming clock speed from software”, while the man page says -B specifies bit clock period (in microseconds) for the JTAG interface or the ISP clock of the JTAG ICE only. Anyhow, a USBasp can reprogram fuses away from the crystal setting if a crystal or external oscillator is used, without depending on serial port data rates. I don't know for certain whether it will work without a crystal or oscillator.

Note, rather than “sharing” a crystal via wires from one board to another – a practice that will broadcast lots of RF noise and might not get the signal across anyway – you could instead write a program on one Arduino to toggle a pin at high frequency, and use that output as an external oscillator to drive one of the crystal pins on another chip. For example, the program below *should* generate a 2.67 MHz square wave on pin PB0 of an Uno or a Nano.

```
void setup() {
  cli();    // Avoid timer interrupts
  pinMode (8, OUTPUT); // PB0 is pin 8 on Uno / Nano
  while (1) PINB = 1;
}
void loop() {}

```

In the ATmega328 data sheet, see §14.3.1, Alternate Functions of Port B, and Table 14-3, which lists PB7 as XTAL2 (Chip Clock Oscillator pin 2), and PB6 as XTAL1 (Chip Clock Oscillator pin 1 or External clock input), indicating external oscillator attaches to the PB6 pin.

---
Tags: bootloader
---


title: Need help with my project

text:
# Question
Title: Need help with my project
Can anyone give me the full code of my project because my code is not working?

My aim is that when the Z axis of an accelerometer is below 370 and a pushbutton connected to a pin 2 becomes high, then pin 13 turns high and remains high. When the Z axis is above 370 and pushbutton is high then the pin 13 goes low and remains low.

P.S I am also a noob to Arduino

Here is my code :

```
const int ledPin = 13;
const int threshold = 370;
const int pull_up_resistor = 12;
const int pull_down_resistor = 11;
const int groundpin = A1;
const int powerpin = A5;
const int xpin = A2;
const int ypin = A3;
const int zpin = A4;

int pushButton = 2;

void setup() {

  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  Serial.begin(9600);

  pinMode(pushButton, INPUT);
  digitalWrite(pushButton, HIGH);
  Serial.begin(9600);

  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
}

void loop() {

  int buttonState = digitalRead(pushButton);

  Serial.println(buttonState);
  delay(100);        // delay in between reads for stability

  Serial.print(analogRead(xpin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(ypin));

  Serial.print("\t");
  delay(100);
  Serial.print(analogRead(zpin));
  Serial.println();

  delay(100);

  if (buttonState = 0) {
    digitalWrite( ledPin, HIGH);
  }
  if (buttonState = 1) {
    digitalWrite (pushButton, LOW);
  }

}

```

# Answer
> 1 votes
Use some formatter before posting it here. For example here is great one, written by KrzaQ edit: didn't noticed that was fixed by Mark

Next thing to do is keep your code clean. Three times you initialized Serial communcation. Why? You should also first initalize Serial then set pinModes into state and then put digitalWrite. It helps reading the code.

**Example:**

```
Serial.begin(value);
pinMode(x,x);
pinMode(y,x);
pinMode(z,x);
digitalWrite(x,x);
digitalWrite(y,x);
digitalWrite(z,x);

```

More readable, isn't it?

Next step: Pull-up and pull-down resistors... It is not thing you need to set in your code. It is hardware connection of 1 resistor, sometimes capacitor and device. There is no use for it in your device. Read about them here: Pull-up/pull-down

Next thing: You **must not** define your outputs as power pins and treat them like one. AVR's have limited power output from each pin and by doing so you can fry it very quickly.

If I understand your sentence correctly you need to save your angle values into variable like this (pseudo code, you have to adjust it to your case no one will write it for free):

```
int xvalue, yvalue, zvalue, button;
void setup(); // all setup should go here do not skip this like me here
void loop() {
  xvalue = analogRead(xpin);
  yvalue = analogRead(ypin);
  zvalue = analogRead(zpin);
  if (button == 1) {
    if (zvalue > 370)
      digitalWrite(ledPin, HIGH);
    else
      digitalWrite(ledPin, LOW);
  } else
    actionWhenPushButtonIsZero();
}

```

If you think about what I wrote and focus on your task I am sure that everything will work in your device. THINK first then ask next questions.

---
Tags: arduino-uno, programming, sensors, button, accelerometer
---


# Question
Title: Can an Arduino emulate a USB mass storage device?
**Question:**

Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?

Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?

This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.

Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?

**Research:**

I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?

**Possible Solution:**

The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?

**Diagram:**

Arduino USB Port -\> USB Cable -\> Embedded Device USB Port Arduino GPIO -\> USB Module -\> USB Cable -\> Embedded Device USB Port

Requirements:

Connection via USB cable between Arduino and an embedded device's USB port. Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

# Answer
The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947
> 1 votes

---
Tags: arduino-uno, usb, sd-card
---