title: How is the diode here effective?

text:
# Question
Title: How is the diode here effective?
I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.

Here is the schematic:

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.

According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?

If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.

If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.

So how is this diode working?

Thanks!

# Answer
Under normal operation the + connection of any inductive component (motor, relay, etc) is at a higher potential than the - connection.

During a "back EMF" event (the collapsing of the magnetic field) a large voltage *of the opposite potential* is generated. That means that the - connection suddenly becomes a much higher potential than the + connection.

That is very bad for anything connected to the - pin of the inductive load.

With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing. However, when the - pin becomes a higher potential than the + pin the diode will become *forward biased* and start to conduct. That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.

Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.

The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go. It'll (crudely speaking\*) take the shortest, quickest, route to get there. That means it goes through the diode and nowhere else. Straight from the black wire to the red wire of your motor.

---

<sub>* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route. The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.</sub>
> 4 votes

# Answer
Flywheel Diode.

When the transistor shuts off, the stopping of the motor generates *back EMF (ElectroMotive Force)* . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.
> 1 votes

---
Tags: motor, transistor
---


title: Cannot open ov7670 output file

text:
# Question
Title: Cannot open ov7670 output file
I have taken a data file using arduino and ov7670 camera module. In this project I used the famous code https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno . But after taking the datafile ov7670NoRam.hex, I can't open it. I spent 3 hours to search how to open, but failed.

Could anyone please let me know how to have a look the image in .hex? or would it be possible to take image data from ov7670 directly to jpg?

I tried to convert the hex file to bin using hex2bin, but when I opened the bin, only errors occurred.

The following is the content of the ov7670NoRam.hex

```
:100000000C9436000C944B000C944B000C944B0059
:100010000C944B000C944B000C944B000C944B0034
:100020000C944B000C944B000C944B000C944B0024
:100030000C944B000C944B000C944B000C944B0014
:100040000C944B000C944B000C944B000C944B0004
:100050000C944B000C944B000C944B000C944B00F4
:100060000C944B000C944B005244590011241FBEB9
:10007000CFEFD8E0DEBFCDBF12E0A0E0B1E0EAE70D
:10008000F2E002C005900D92A235B107D9F70E94A7
:10009000AF000C943B010C9400008093BB0084E8FB
:1000A0008093BC008091BC0087FFFCCF8091B90099
:1000B000887F90E070E08617970709F408950E9402
:1000C000A00084EA8093BC008091BC0087FFFCCF35
:1000D0008091B900887F883009F408950E94A000BB
:1000E000CF93DF93D82FC62F0E94610068E182E48E
:1000F0000E944D0068E28D2F0E944D0068E28C2F17
:100100000E944D0084E98093BC008FE99FE0019735
:10011000F1F700C00000DF91CF910895CF93DF93F6
:10012000EC0103C00E9470002296FE01849131967A
:1001300064918F3FB9F76F3FA9F7DF91CF91089591
:10014000259A90E285B1892785B92FEF31EE84E0B9
:10015000215030408040E1F700C00000F3CFF89418
:10016000239A8091B6008F798093B60083E48093C0
:10017000B00089E08093B1001092B30087B1807F16
:1001800087B98AB183708AB92FEF8BE792E9215042
:1001900080409040E1F700C000008091B9008C7F62
:1001A0008093B90088E48093B8001092C50081E084
:1001B0008093C4008091C00082608093C00088E179
:1001C0008093C10086E08093C20060E882E10E94D3
:1001D00070002FEF81EE94E0215080409040E1F7D5
:1001E00000C0000080E091E00E948E0060E285E1A6
:1001F0000E94700060E08CE00E9470008AE392E050
:100200000E948E0088E492E00E948E0069E181E104
:100210000E947000E8E6F0E094918091C00085FFB4
:10022000FCCF9093C6008091C00085FFFCCF319633
:1002300084918111F1CF4B9BFECF4B99FECF40EEC5
:1002400051E08FE792E04A99FECF36B129B1207F85
:100250003F70232B2093C6004A9BFECF9C01215068
:100260003109892B11F0C901EECF415051094115D7
:0A027000510539F7CFCFF894FFCF06
:10027A0012803A0412001713180132B619021A7AB8
:10028A00030A0C003E00703A7135721173F0A20134
:10029A0015027A207B107C1E7D357E5A7F69807616
:1002AA0081808288838F849685A386AF87C488D706
:1002BA0089E813C0000010000D401418A505AB070B
:1002CA002495253326E39F78A068A103A6D8A7D84A
:1002DA00A8F0A990AA9413C5300031000E610F4B03
:1002EA0016021E07210222912907330B350B371DEF
:1002FA003871392A3C784D404E20690074108D4F70
:10030A008E008F009000910096009A00B084B10C84
:10031A00B20EB382B80A430A44F045344658472815
:10032A00483A59885A885B445C675D495E0E6C0A94
:10033A006D556E116F9E6A400140026013C74F806F
:10034A00508051005222535E5480589E41083F000B
:10035A00750576E14C0077013D484B09C960564066
:10036A0034113B12A48296009730982099309A84CF
:10037A009B299C039D4C9E3F78047901C8F0790F14
:10038A00C8007910C87E790AC880790BC801790C2F
:10039A00C80F790DC8207909C8807902C8C07903C5
:1003AA00C8407905C8307926FFFF32F617131801BD
:1003BA0019021A7A030AFFFF12013D08413D76E14C
:0203CA00FFFF33
:00000001FF

```

# Answer
What is it you hope to achieve by "opening" the hex file or "converting it to binary"?

A hex file is a compiled sketch. It is intended to be installed into the Arduino Uno using avrdude.
> 0 votes

# Answer
I am the author of the code and needless to say I am very confused right now on what you are trying to do. You run make writeflash in order to do what the target names implies write the hex file to microcontroller's internal flash memory. After that is done the code will run and you will use my frame grabber https://github.com/ComputerNerd/simpleFrameGrabber to capture an image.
> 0 votes

---
Tags: arduino-uno
---


title: Transferring OV7670 data with SPI port

text:
# Question
Title: Transferring OV7670 data with SPI port
I bought an OV7670 camera and I would like to use the following code: https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno

But I wonder whether it is possible to use SPI instead of I2C when I transfer the image data through Arduino to other breakout boards.

# Answer
I2C is not used to get the pixel data. That is used only to configure the ov7670. You can read the pixel data by reading the IO PORTS and then send the data via SPI.
> 1 votes

---
Tags: spi
---


title: Non line of sight radio and arduino uno

text:
# Question
Title: Non line of sight radio and arduino uno
I've been using a pair of arduino uno and nrf24l01 and found it wasn't really suitable due to low range when it comes to obstacles.

Essentially I'd like to use it in country areas where it would ideally transmit through dense trees and over hills at around 500 meters.

I've spotted the SI4432 and the sx1272 (which seems ideal but it doesn't seem popular despite it's high NLOS range capabilities?)

I was just wondering if anyone had any recommendations on which would be the best radio module to try? Any help would be really appreciated. Many thanks in advance.

# Answer
> 1 votes
General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.

The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.

# Answer
> 0 votes
Since you already have the uno+nrf24 working, it might be worth trying a better nrf24 module before trashing the work you've already done. You can buy nrf24 modules with an integrated LNA, PA, and external antenna port. Just do a search for NRF24L01+LNA+PA. You can find them on amazon for \< $10 and usually come with an external antenna.

---
Tags: arduino-uno
---


# Question
Title: What is the diffrence between following arduino boards and which should i buy?
# Arduino UNO R3 Compatible Board ATmega328P ATmega16U2

http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH\_DefaultDomain\_203&hash=item2ee26a3860

# Arduino UNO R3 ATmega328P USB Development Board CH340G

http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH\_DefaultDomain\_203&hash=item463beed1f0

### I will be working on a windows 7 32 bit pc.

# Answer
The first is an unofficial clone of an R3 using the same schematic as the real R3. The second is a rough copy using a cheaper USB serial interface chip.

Neither of them are real Arduino boards. The first one is closer to the real UNO and should do the same things that a real UNO should do (assuming it works at all). The second one - well, who knows? You certainly can't do any of the fancy things to the USB interface that you can with a real UNO R3.

Which should you buy? Well, really, you shouldn't buy either of them - but if you *must* go for one I'd pick the first one. Better to buy a real UNO from Arduino though, at least then you know what it is you're getting, and you expect it to work. With these cheap Chinese clones (Chinduinos) you may just get a bunch of counterfeit chips selotaped to a piece of cardboard.
> 1 votes

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


title: Analog pins all reading same value

text:
# Question
Title: Analog pins all reading same value
I'm trying to read 5 analog inputs, but all the pins are reading the same as pin A0, plus or minus a couple points. I tried using pulldown resistors on all 5 pins and it made no difference. The board is a Leonardo. Thanks for any ideas/help!

```
void setup() {
    Serial.begin(115200);
    analogReference(EXTERNAL);
}

void loop() {
    int A0, A1,A2,A3,A4;
    delay(200);
    A0= analogRead(A0);
    A1= analogRead(A1);
    A2= analogRead(A2);
    A3= analogRead(A3);
    A4= analogRead(A4);

    Serial.print(A0);
    Serial.print(" ");
    Serial.print(A1);
    Serial.print(" ");
    Serial.print(A2);
    Serial.print(" ");
    Serial.print(A3);
    Serial.print(" ");
    Serial.print(A4);
    Serial.print("\n");
}

```

# Answer
> 6 votes
> ```
> int A0, A1,A2,A3,A4;
> delay(200);
> A0= analogRead(A0);
> A1= analogRead(A1);
> A2= analogRead(A2);
> A3= analogRead(A3);
> A4= analogRead(A4);
>
> ```

Your local variables (`A0` through `A4`) are shadowing the global variables for the pins (`A0` through `A4`). Give your local variables different names.

---
Tags: arduino-leonardo, analogread
---


title: Arduino Due Pinout with Explanations?

text:
# Question
Title: Arduino Due Pinout with Explanations?
I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "*Arduino Due pinout*", "*Arduino Due pin mapping*" and similar.

The best I could find was this table, however it doesn't help you out at all if you are completely new to electronics and have no idea what `TX2`, `SDA` or `NPCSO` mean, etc.

Does anybody know of Arduino/Due documentation that explains what each I/O pin is?

# Answer
The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.

Atmel SAM3X8E ARM Cortex-M3 datasheet
> 1 votes

---
Tags: pins, arduino-due
---


# Question
Title: How to interface arduino nano with sim900A?
I have arduino nano and sim900a modem.

Rx(pin30) and Tx(pin31) pins of **arduino** shows 3.8VDC respectively and Rx and Tx of **SIM900a** shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?

Thanks..

# Answer
The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.

It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.

However, a quick look at the SIM900A docs I could find **suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!**

Essentially, you have two problems:

1. You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter. It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.
2. You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it. You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.

Finally, there's a sort of hackish option: Connect the *transmit* data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 *receive* pin.
> 1 votes

---
Tags: serial, arduino-nano
---


title: Sending serial commands to yourself

text:
# Question
Title: Sending serial commands to yourself
Is it possible to "send" a serial command to the device itself to see the response? I have written a little routine based on a couple of serial sends and receives and want to see if that works out like I want.

EDIT:

I have a device (an AVR with arduino boot loader) and as part of my program, the device exchanges phrases with peripheral devices over a serial connection. Since I have right now just the arduino itself and can't really test, if at least the logic behind the serial part of works out, I would like to get serial commands from somewhere and trigger 'continuous talking', so I want to monitor the response behavior of my module, if it gets a certain command (stability reasons). Instead of waiting for a second device, is it possible to "link the TX/RX line to itself" internally or externally to test my program with itself?

# Answer
Yes, you can do that by cross-connecting the transmit and receive pins on the Arduino. But then your devices sits there silently murmuring to itself (or not...) and you can't really tell what it's saying, or if it's doing anything unless you can observe some other hardware - LEDs, a 'scope, f/ex.

But why not hand-type or script some messages to it on your PC? If the Arduino sketch would make some brief, coherent replies you could confirm what it's doing and debug it if necessary.

I've done just this in your situation: Two of us defined a serial protocol - the ASCII (for human readability!) commands and replies that either end could make or expect. Then each of us wrote the communication code for one of the two devices and proved that it met the protocol. Once both of us had finished and were confident in our respected communication code, we plugged the two devices together, and - they played! Nicely! :) And if they hadn't we could have eavesdropped on the serial line and printed their attempted conversation to discover where it went wrong.
> 1 votes

---
Tags: serial, softwareserial, uart
---


# Question
Title: Can we control an Arduino with voice commands?
I'm looking for some method to control an Arduino with voice commands.

Could this work on this platform?

# Answer
Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.

You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.

FYI: https://www.sparkfun.com/products/13316
> 1 votes

---
Tags: arduino-uno, android
---


# Question
Title: How to increment and decrement an output voltage by using two buttons?
I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below.

The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0.

I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as `attachinterrupt()` and `Debounce()` functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions?

I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic.

simulate this circuit – Schematic created using CircuitLab

Here is my code I have made. I'm using an LED to test the Vout aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?

```
int PWMPin = 6; // output pin supporting PWM
int buttonApin = 9; // buttonA to pin 9 PWM
int buttonBpin = 10; // buttonB to pin 10 PWM
float value = 0; // read the value at 0
int fadeValue = value;

void setup()
{
  Serial.begin(9600); //initialize serial communication at 9600 baud
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(PWMPin, OUTPUT);
}
void loop()
{
  {
    int port = analogRead(0);
    port = map(port, 0, 10, 0, 255);
    analogWrite(6, port);
  }

  {
  if (digitalRead(buttonApin) == LOW, fadeValue)
  {
  // fade from min to max in increments of 25.5 points: basically (0.5 volts)
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)

    digitalWrite(PWMPin, fadeValue);

    // sets the value (range from 0 to 255):
   Serial.println(PWMPin);
   analogWrite(PWMPin, fadeValue);
  }
  }

  {
    if (digitalRead(buttonBpin) == LOW, fadeValue)
  {
  // fade from max to min in increments of 25.5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)

    digitalWrite(PWMPin, fadeValue);

  // sets the value (range from 0 to 255): basically (0.5 volts)
  analogWrite(PWMPin, fadeValue);
  }
  }
}

```

# Answer
I suggest you to use debounce to detect if a pin has been definitely pressed. You could also test using interrupts (hint: interrupts can happen multiple times even if you "only" pressed once). So either use Arduino's example of debounce or take a look at the Bounce2 library found on their website.

Now that you can check whether or not either button A or B has been pressed, how do you keep track of the voltage to be output? You should use a `counter` variable that will be incremented when button A is pressed and decremented when button B is pressed. Here is a pseudocode:

```
if(ButtonA == pressed)
  counter++;
else if(ButtonB == pressed)
  counter--;

```

This `counter` variable can be used to control the output voltage. Remember that the argument for `analogWrite()` function on the Arduino Uno is the duty cycle which takes in values from 0 to 255. So `analogWrite(0)` ≣ 0 Volt and `analogWrite(255)` ≣ 5 Volt. So at the moment, you couldn't just do `analogWrite(counter)` because you would need to press 255 times button A!

Instead, you would need a way to convert your counter to reflect the increment you need. You mentioned that it should require 10 presses to reach 5 Volt at the Arduino output, and the easiest way to accomplish this is to use Arduino's Map function. The pseudocode would look like this:

```
Output = map(counter, 0, 10, 0, 255);
analogWrite(Output);

```

Now there is one last step! The map function will limit the output voltage from 0 to 5 Volt so everything will be safe; however, the counter is not limited to 0 to 10. This means that even if the counter is at 15 (because you pressed button A too many times) the voltage will be 5 Volt and you would need to press button B at least 6 times to see the voltage go down! So to limit the counter you could easily implement your own function:

```
if(counter >= 10)
  counter = 10;
else if (counter<= 0)
  counter = 0;

```

You could also use Arduino's `constrain()` function which more information can be found on their website.

Hopefully this points you in the right direction.
> 3 votes

# Answer
If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop. The Bounce2 library does basically the same.

Also, about the PWM, why not an R-2R?

10V/0.5V + 1 =\> 21 steps \< 32 =\> 5 bits =\> 6 resistors.

But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.
> 4 votes

---
Tags: arduino-uno, c++, pwm, analogread, hardware
---


# Question
Title: Arduino Due and Vin, 3.3V and 5V power inputs
I just want to confirm something before I wire up my first ever Arduino project and fry all the stuff I just spent money on.

It is my *understanding* that the `Vin` power input will tolerate a 9V battery and use voltage regulators to pare it down to either 3.3V or 5V (as different parts of the board require). So it is then my *assumption* that if I have a 9V battery running to `Vin`, that I could then connect a power wire to the `3.3V` connector, and reliably get a 3.3V signal (and ditto for 5V), **yes?**

Or, is it that they are *input* jacks *expecting* either 3.3V or 5V signals? I guess I'm confused over this:

* Will `Vin` then power the 3.3V and 5V inputs, giving me access to voltage at that level; or
* Do I have to choose between 3.3V, 5V or `Vin`, and only use one of those to power my board (with the appropriate voltage level)

# Answer
`DC Jack` is connected, through a diode, to `Vin`.

`Vin` is stepped down to `5V` on-board.

`5V` is stepped down to `3V3` on board.

Thus you can do any one of the following numbered items.

1. Connect a 7-12V supply to the `DC Jack`; thus:

* use `Vin` as a supply @ DC - 0.7V for off-board peripherals, and
    * use `5V` as a supply for off-board peripherals, and
    * use `3V3` as a supply for off-board peripherals.
2. Connect a 6-12V supply to `Vin`; thus:

* use `5V` as a supply for off-board peripherals, and
    * use `3V3` as a supply for off-board peripherals.
3. Connect 5V supply to the `5V`; thus:

* use `3V3` as a supply for off-board peripherals.

The above is only guaranteed for boards that **follow the reference schematic**, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.
> 3 votes

# Answer
Yes your assumption is correct you can power 3.3v and 5v items from those pins as long as you don't take more current than the onboard regulator(s) can supply
> 0 votes

---
Tags: power, arduino-due, voltage-level
---


# Question
Title: How to count the number of times a changing variable reaches a peak value
I am recording a varying distance with an Ultrasonic sensor and Arduino but my problem is I want to display the number of times this variable reaches peak (at an instance the value will be increasing and the next instance decreasing in that order) on an LCD.

So far this is my code:

```
//Libraries
#include <Ultrasonic.h>
#include <LiquidCrystal.h>

//Setup connection with LCD and HC-SR04
LiquidCrystal lcd(12, 10, 5, 4, 3, 2);
Ultrasonic ultrasonic(A0,A1);

void setup() {
  //Lcd init
  lcd.begin(16, 2); //16 rows, 2 columns
}

void loop()
{
  lcd.clear();
  lcd.print("  Ardumotive ;)  "); // You can change this message.
  lcd.setCursor(0, 1);
  lcd.print("Distance: ");
  lcd.print(ultrasonic.Ranging(CM));
  lcd.print("cm");

  delay(300); // 1sec delay
}

```

# Answer
> 1 votes
The counting portion of what you want to achieve is simple - you just increment a variable. The hard part is knowing *when* to count.

You need to remember what your value has been doing in the past in order to know if you have had a peak or not. Also you have to define exactly what a peak is.

The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.

You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone". They could be the same value, but don't need to be.

You then have a flag which remembers if you are in the peak zone or not.

If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone. Set the flag to remember that fact.

If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone. Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak. This is known as hysteresis and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.

# Answer
> 0 votes
If ((current distance - previous distance) \< 0) Max = previous distance;

Current distance = previous distance;

---
Tags: arduino-uno, programming, arduino-mega, pins, variables
---


# Question
Title: how to make an led turn on when something gets close to an ultrasonic sensor
Hey I just started using arduino and so far can't get any help with how to write a code for an led to turn on when someone gets in range of a three pin ultrasonic sensor, and off when they are out of a specific range.

Any help?

# Answer
Try with this and check that at least you can reproduce the desired effect: http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

Then you can refer to this for the part related to driving the LED: http://www.arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED

Since the ultra sound demo already calculates the distance, you can do the test on that to decide when to turn ON/OFF the LED.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Which Arduino Board should I start with?
I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.

My questions are:

1. Which Arduino Board should I start with?
2. Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?

# Answer
My advice: \- get a model with USB port (some do not have one) \- the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up \- you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC \- same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.

I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.
> 1 votes

# Answer
Depending on your budget you could start with an Arduino Uno starter kit that will include the Arduino, breadboard and wires plus different sensors (like this one \- but there are others with less peripherals and cheaper).

If you have a lower budget you can still buy the arduino and many separate sensors/LEDs etc from eBay.

By googling you'll find a lot of tutorials about getting started with the hardware that you bought.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: MPU6050 causing arduino not to run sketch
I have a mpu6050(which I got from here http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html) and I have connected it to special ports on a sensor shield made for the mpu6050(http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem.

This is my code

```
#include <Wire.h>
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <I2Cdev.h>
#include <MPU6050.h>

MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;

#define Gry_offset 0
#define Gyr_Gain 0.00763358
#define Angle_offset 4
#define RMotor_offset 20
#define LMotor_offset 20
#define pi 3.14159

long data;
int x, y;
float kp, ki, kd;
float r_angle, omega;
float f_angle;
float Turn_Speed = 0, Turn_Speed_K = 0;
float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
float LOutput,ROutput;

unsigned long preTime = 0;
float SampleTime = 0.08;
unsigned long lastTime;
float Input, Output;
float errSum, dErr, error, lastErr;
int timeChange;

int TN1=3;
int TN2=4;
int ENA=9;

int TN3=5;
int TN4=6;
int ENB=10;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  pinMode(TN1,OUTPUT);
  pinMode(TN2,OUTPUT);
  pinMode(TN3,OUTPUT);
  pinMode(TN4,OUTPUT);
  pinMode(ENA,OUTPUT);
  pinMode(ENB,OUTPUT);

  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
  Serial.print("Hello");
}

void loop() {
  Recive();
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
  omega =  Gyr_Gain * (gx +  Gry_offset);
  //Serial.print("  omega="); Serial.print(omega);
  if (abs(r_angle)<45){
    myPID();
    PWMControl();
  }
  else{
    analogWrite(ENA, 0);
    analogWrite(ENB, 0);
  }
}

void Recive(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();

    y = data >> 16;
    x = data & 0x0000ffff;
    //Serial.print("  x="); Serial.print(x);
    //Serial.print("  y="); Serial.println(y);
    if(x >= 520){
      Run_Speed_K = map(x, 520, 1023, 0, 100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else if(x <= 480){
      Run_Speed_K = map(x, 480, 0, 0, -100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else{
      Run_Speed_K = 0;
    }
    if(y >= 520){
      Turn_Speed = map(y, 520, 1023, 0, 20);
    }
    else if(y <= 480){
      Turn_Speed = map(y,480,0,0,-20);
    }
    else{
      Turn_Speed = 0;
    }
  }
  else{
    x = y = 500;
  }
}

void myPID(){
  kp = analogRead(A0)*0.1;
  //kp=17;
  Serial.print("  kp=");Serial.print(kp);
  kd = analogRead(A2)*1.0;
  //kd=840;
  Serial.print("  kd=");Serial.print(kd);
  //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

  //kp = 0;  Serial.print("  kp=");Serial.print(kp);
  //kd = 0;  Serial.print("  kd=");Serial.print(kd);
  ki = 0.08;
  Serial.print("  ki=");Serial.print(ki);

  unsigned long now = millis();
  float dt = (now - preTime) / 1000.0;
  preTime = now;
  float K = 0.8;
  float A = K / (K + dt);
  f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;

  Serial.print("  f_angle=");Serial.print(f_angle);

  timeChange = (now - lastTime);
  if(timeChange >= SampleTime){
    Input = f_angle;
    error = Input;
    errSum += error * timeChange;
    dErr = (error - lastErr) / timeChange;
    Output = kp * error + ki * errSum + kd * dErr;
    LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
    ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
    lastErr = error;
    lastTime = now;
  }
}

void PWMControl(){
  if(LOutput > 0){
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, LOW);
  }
  else if(LOutput < 0){
    digitalWrite(TN1, LOW);
    digitalWrite(TN2, HIGH);
  }
  else{
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, HIGH);
  }
  if(ROutput > 0){
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, LOW);
  }
  else if(ROutput < 0){
    digitalWrite(TN3, LOW);
    digitalWrite(TN4, HIGH);
  }
  else{
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, HIGH);
  }
    analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
    analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
}

```

and this is a picture of the mpu6050 on the sensor shield

# Answer
> 0 votes
The shield you linked to is no longer sold.

The current version is

But it has no special connection for an MPU6050 breakout (and BTW that same 6050 board is $6 about everywhere else). A shield serves no purpose for just the 6050 really.

If you connected the 6050 to the I2C lines (aka A4 & A5), Then you also need to connect an additional interrupt line. If you are using unmodified example code, it depends on the interrupt being connected.

Here is a post made a while back using the 6050

http://www.spiked3.com/very-cool-imu-demo/

It is possible to use the 6050 without interrupts but you would have to (understand and) modify the standard example code.

Update: I knew you had a different board, and it had a connector for the 6050, the comment was that the link you provided, since it was 'no longer available', did not link to any documentation. Without a schematic it can not be known how it is hooked up beyond simple I2C. As you are using other devices I am not familiar with, I would expect some sort of conflict on the i2C bus maybe. Are all i2c bus devices using the same reference voltage? It does not matter if they are all 5v or all 3.3V as long as they are all the same.

Since you say 'nothing is printed' and your second line of setup is 'initialize' gyro, odds are good it is not getting past that. Simple (archaic) debugging, put a print (and a small delay) before and after the call to initialize.

My code uses the following for Wire.begin

```
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
    TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif

```

I dont know if your Arduino is different and if it would make any difference.

I have a line after initialize

```
mpu.testConnection();

```

That may or may not help you.

FYI PI is already defined, as is DEG\_TO\_RAD and RAD\_TO\_DEG

```
if (abs(RAD_TO_DEG * headingDelta) > .1F)
    poseChanged = true;

```

Update: I just looked quickly at the code, and the only thing initialize does is write to i2c, it never waits really. And that means writing to I2C is hanging. I ran into this once when I had an unpowered device on the bus. I thought it would not harm, but I was wrong. Does the power light on the mpu come on? (is it really getting power?) I have run them at 3.3v and 5V so I do not think that would be a problem, but if you can, switch it to 3.3V to be sure. Getting down to the nitty gritty, you could check if the default pullup resistors are still on the board and did not get accidentally knocked off. Even better would be to try it with a known good MPU. I have about 10 of them within reach :P (spiked3.com)

---
Tags: arduino-uno, mpu6050
---


# Question
Title: What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi?
I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8). However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.

What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi?

I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.

# Answer
You can just have a sketch in the arduino that takes the measurements at whatever interval you want using the `analogRead(pin)` function and then forward those results to the raspberry pi via serial using `Serial.print(whatever you want here)`. If you don't know how to use serial with arduino just go to their site, they have very good documentation. Hope that helps :)
> 0 votes

# Answer
Nanpy seems to have a CounterClass that does frequency measurements.

Or do you want to measure the PWM duty-cycle?
> 0 votes

---
Tags: arduino-uno, pwm
---


title: PYM-1 PIR sensor current concerns

text:
# Question
Title: PYM-1 PIR sensor current concerns
I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.

The data sheet states the following:

* Operating Voltage: 4,5~5V.
* Standby current: 65 micro-amps (65uA)
* Operating Current: 40mA (40 milli-amps)

The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.

So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point.

I suspect it might be safer to run this via a transistor and external power than directly on the arduino?

# Answer
This is completely acceptable for your intended purpose.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form using an Arduino is overkill.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form adding an Arduino is overkill.

When it comes to playing overkill can be good :-)

---

**To use it to provide input to an Arduino and NOT to a mains level light:**

**NB** relay contacts may only be connected to mains for light switching **OR** to the Arduino. **NEVER** to both at the same time.

Connect it's DC supply input to your Arduino (or other) power supply.
As long as the **supply** can provide 40 mA when needed it will work OK.
40 mA is a **power supply** rating This is unrelated to the Arduino pin loading.

Connect the output to an Arduino digital pin configured as an input.

The output is a relay, activated when an object is sensed.
When inactive the centre pin is probably connected to the right pin - Check with Ohm meter.

When activated the left pin in connected to the centre pin (see their diagram)

Connect ground to right pin.
Connect Arduino digital input to centre pin. Connect a "high" level to left hand pin.
OR as Majenko suggests, just set the pin to have pullups enabled.

If connecting to V+ as shown then V+ can be Vcc (=5V for a 5V Arduino, 3v3 for a 3V3 Arduino) DO NOT set V+ to higher than Arduino's Vcc. You can connect a say 1k to 10k resistor from V+ to the voltage source bur still do not set V+ above Vcc.
OK - just have pullups enabled:-)

eg (untested)

> int ADCMode = 0;
> int PIRPin = 6; // PIR connected to digital pin 6
> void setup()
> {
> pinMode(PIRPin, INPUT\_PULLUP); // set PIRpin as input with pullup
> }
> void loop()
> {
> ...
> ADCMode = digitalRead(PIRpin); // $Read PIR status
> ...
> }

When the circuit activates digitalRead() will return a high.
When the circuit is not activated digitalRead() will return a low.

---

See here re Arduino pin modes
> 2 votes

# Answer
When I look at the PYM-1 seen here:

http://www.ebay.com/itm/Infrared-PIR-Human-Sensor-NEW-Arrival-Pyroelectric-DIY-Kit-PYM-1-for-Arduino-/271677900953

I don't see any need for an external microprocessor such as an Arduino. It seems that one just applies 5V as input and it switches on/off up to 300W of power. Where would one use an Arduino GPIO?
> 1 votes

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


title: How to call a file from the arduino?

text:
# Question
Title: How to call a file from the arduino?
I am aware of the simplicity of the question. Nevertheless...

I need to code into the arduino the execution of a file. More precisely a .exe. To put things in perspective. I have little to no knowledge of coding. Yet I need to put together a photocabin. I have the arduino to count the coins inserted to my coin collector and I need to take a picture when the precise ammount is reached. Then reset the ammount to avoid taking more pictures. here is what my code looks so far: (taken from the examples on the arduino page)

```
const int coinInt = 0;
//Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1.

    volatile float coinsValue = 0.00;
    //Set the coinsValue to a Volatile float
    //Volatile as this variable changes any time the Interrupt is triggered
    int coinsChange = 0;
    //A Coin has been inserted flag

void setup()
{
  Serial.begin(9600);
//Start Serial Communication
  attachInterrupt(coinInt, coinInserted, RISING);
//If coinInt goes HIGH (a Pulse), call the coinInserted function
//An attachInterrupt will always trigger, even if your using delays

}

void coinInserted()

//The function that is called every time it recieves a pulse
{
  coinsValue = coinsValue + 0.05;
//As we set the Pulse to represent 5p or 5c we add this to the coinsValue
  coinsChange = 1;
//Flag that there has been a coin inserted
}

void loop()
{
  if(coinsChange == 1)
//Check if a coin has been Inserted
  {
    coinsChange = 0;
//unflag that a coin has been inserted

   if(coinsValue >= 0.30)
  {
       here goes the code to open a file, then the code to reset coinsValue

  }
  }
}

```

Thanks a million.

# Answer
> 1 votes
First of all you need to develop a windows app. You can achieve this by downloading visual studio express for windows desktop from here. Then you must create a project in your language of your preference. You will have to add a **serial port** component and set the properties to match your arduino serial ones. Then from the **event** that handles the "data available" of your serial port you can check if there is an incoming character from your arduino and create an if statement that runs the .exe file. Then you must add serial.print('c') to your code when there is a coin inserted. By doing so, you will manage to communicate between arduino and your windows app.

More info and full guide can be found here

# Answer
> 1 votes
I used the following code to run a program, not from the arduino, but from software listening to a specific character sent from the arduino. Thanks for your help. I share the code that I used. It doesn´t need to print the character, but I copied it exactlyy from microsoft help pages (lost the link). I just aded the if statement and the start.process part (I got this from a stackoverflow answer). Without any further delay:

```
using System;
using System.IO.Ports;
using System.Diagnostics;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM3");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
        if (indata == "c")
        {
            Process.Start(@"C:\Users\Laptop\Desktop\print.ahk");
        }
    }
}

```

---
Tags: arduino-uno
---


title: How do you call to a previous function?

text:
# Question
Title: How do you call to a previous function?
I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions?

# Answer
You need to get your head around the Finite State Machine (FSM).

It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State"). One state would be reading pressure. Another state would be "testing", or whatever.

I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine
> 1 votes

# Answer
What do you mean by "previous"? In the call stack or in the code? Either way, you can call any (public|member|static) function you want at any time, even call the very same function you're already in (recursion, but not recommended on Arduino or any other embedded system).
> 0 votes

---
Tags: programming
---


# Question
Title: esp8266 esp-01 crashing, restarting over and over
I flashed my ESP-01 with the nodemcu firmware 512k version, and everything was working fine. I testing some lua scripting on init.lua and it was working. Then, after writing a bunch of code and uploading, the module restarted. And it restarted. And it's still restarting, over and over again, and prints to serial

```
CÀbc0°ýbcü¨HøNodeMcu 0.9.4 build 20141230  powered by Lua 5.1.4
ö,3bþÈH

```

It was always printing the garbage in there before, so I'm not worried about that. However, I can't send anything to the device--I can't send serial commands, or reflash the device. I'm thinking I overloaded the memory or something. Anyone have any ideas for recovering this brick?

# Answer
Turns out I was pulling up on the GPIO0 pin, instead of down. Ensure you have the correct pin-out when flashing.

ESP-01 VCC - 3.3v Serial Adapter ESP-01 GND - Ground or Minus Serial Adapter ESP-01 RX - Connect to TX on Serial Adapter ESP-01 TX - Connect to RX on Serial Adapter ESP-01 CH\_PD - 3.3v Serial Adapter ESP-01 GPIO0 - Pull low by connecting to ground / minus

There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over. That is also what was happening. There is some problem with wifi.sta.getap() that exacerbates this.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Spilt string and convert to float to compare
I'm transmitting: Temperature: 28.22C

and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?

TX end hardware: (Arduino Uno board with Xbee S1) to computer RX end hardware: (Arduino Uno board with Xbee S2) to computer

# Answer
Okk very simple approach :-

Suppose this is your string variable inStr = "Temperature: 28.22C"

```
String inStr = "Temperature: 28.22C";
int indexOfSpace = inStr.indexOf(' ');
//this stores the address of the space character in the string.
int indexOfC = inStr.indexOf('C');

String Temp = inStr.substring(indexOfScace+1,indexOfC);
//as the parameter for the function is supposed to be the starting point of the string to
 be extracted and one more than its ending point.

//Now to convert to float

float TempFlo = Temp.toFloat();

```
> 2 votes

# Answer
I suppose your communication is working... In order to retrieve a floating number from a string you might use toFloat() function. You can watch the reference page here to understand how does it work.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Fading the brightness of LEDs using MAX7219 and PWM
I am doing a project with bi-color led matrix 8x8 and MAX7219 as the LED driver. I want to implement a fading effect on the LEDs, like mixing the two colors by varying the individual duty cycles.

My idea is the use of the `Iset` parameter; I would connect the PWM pin from Arduino through the `Rset` resistor and feed that into the Iset of the MAX7129 instead of 5V supply. Please suggest whether or not this is possible, if not what can be the alternative approach?

# Answer
This is possible in two ways:

1. The MAX72xx has its own internal intensity control register. From the datasheet:

> Digital control of display brightness is provided by an internal pulse-width modulator \[...\]. The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET \[...\].

This of course requires no extra components or effort, but you are limited slightly by only a 4-bit intensity resolution. Also, there is no 'off' so you'd have to either manually blank the displays or put the ICs into shutdown mode.

2. Your suggested way is possible. However, the low frequency of the Arduino's PWM may lead to flickering if the MAX7219's internal segment current reference driver needs a steady voltage. You'll have to consider smoothing the PWM output through a low pass filter - the TL072/TL082 has two op-amps so you can use one for colour A and the other for colour B. I'd choose an op-amp over passive filtering because the current drawn from the Arduino will be negligible and the stability of the current into the MAX7219 will be improved.
> 3 votes

---
Tags: led, pwm, max7219
---


title: Simple LED circuit is not working

text:
# Question
Title: Simple LED circuit is not working
This is my first circuit ever (!) and so I'm hoping that I'm just making an easy-to-spot rookie mistake. I am trying to power an Arduino Due with a 9V battery and then have the Due in turn power a red LED. No blinking. No sketchpad/C program flashed to the chip. Just straight up electricity:

When I connect the battery, several things happen:

1. There is a green power LED on the Due that lights up; and
2. Right next to it is an orange LED (on the Due itself) that blinks every few seconds (not sure what this LED is or what the blinking means, but providing that detail for good measure); and
3. The red LED on the breadboarrd does **not** light up

This is a 2V/15mA LED, and as you can see I'm powering it from the 5V power jack on the Due. So a 220 ohm resistor should be perfect for it (`R = (Vs - V) / I = (5V-2V) / .015A ~= 220 ohms`).

So, for the first time ever, I busted out my multimeter, set it to the voltage setting, and started testing the circuit. First I tested `Vin` and `GND` on the Due (that is, the connection between the battery and the Due), and the multimeter lit up and hovered (correctly) around 5V. So far so good. Next I tested the power and ground connections on the breadboard power rails (indicated in green above). Again, the multimeter reported a roughly 5V power supply. Then I tested the connection from the power rail to the row (purple in pic above) feeding power to the resistor, and to my surprise, the multimeter reports **no power** at those two purple locations.

My *understanding* was that the power rail will power the entire column its connected to (in my case, the left-most column), and then any rows connecting to a power rail/column will also be powered. So I'm not understanding why there's voltage on my power rail/column, but not on the wire connecting my power rail to the resistor. Any ideas?

---

### Update:

Here is my corrected circuit per initial feedback. Please note this is still not working, but I think I'm getting close:

# Answer
> 5 votes
What connects the resistor to the LED?

Absolutely nothing.

It's hard to work out which holes the LED is plugged into, but I think your current circuit looks something like this:

You need to connect that resistor and LED together.

For your edit:

Now your circuit looks like this:

Behind the 5 pins in that column with the ground wire there is a big chunk of metal connecting them all together. It's no different to if you'd taken the LED and twisted the pins together into one. There's no way the power can get up one and down the other when they are connected together like that. You need to separate them into different columns.

And this is how the (black) connections inside are laid out, and how your (red) electricity is flowing:

And here is how the circuit should look, using a program called Fritzing. It's a pretty basic design tool, but great for showing wiring.

You can see how the green highlighting shows the columns that are connected.

# Answer
> 1 votes
It looks like you've got confused between columns and rows.

You are correct that the power rails run the length of the breadboard -- these are seen as the top and bottom pairs of rows in the diagram below (ignore the middle row). However, the rest of the board is connected up as separate columns. Each column is independent of its adjacent columns.

This means your red wire going from the power rail to the resistor is connected correctly. However, the other end of your resistor is currently going nowhere. It needs to be in the same column as the anode of your LED.

---
Tags: led, power, arduino-due, battery
---


# Question
Title: How do I receive more that 64 bytes with Arduino
I am using QtSerialPort to send and receive data from Arduino. I am sending **more than 64 bytes** (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino **sending only 64 bytes** in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.

Here is my Arduino code:

```
void loop() {
    if (Serial.available() > 0) {
        int i = 0;
        delay(500);
        int size = Serial.available();
        while (i < size)
            buffer[i++] = Serial.read();

        Serial.print(buffer);
        //delay(500);
        int j = 0;
        while (j < size)
            buffer[j++] = '\0';
        //while (Serial.available()) Serial.read(); I tried it
        //Serial.flush();   Also tried it, but nothing.
    }
}

```

# Answer
> 2 votes
Instead of blocking the loop for 500 ms, you should be actively reading the data as it comes. Otherwise the internal buffer of the `Serial` object will overflow after only 64 bytes are received.

Here is an example that copies the incoming bytes into a larger buffer (256 bytes) and, upon receiving an end-of-line character, echoes back the whole line.

```
void loop() {
    static char buffer[256];
    static size_t pos;              // position of next write

    while (Serial.available() && pos < sizeof buffer - 1) {

        // Read incoming byte.
        char c = Serial.read();
        buffer[pos++] = c;

        // Echo received message.
        if (c == '\n') {            // \n means "end of message"
            buffer[pos] = '\0';     // terminate the buffer
            Serial.print(buffer);   // send echo
            pos = 0;                // reset to start of buffer
        }
    }
}

```

---
Tags: serial, programming, c++
---


# Question
Title: How do I know when the connections is ready between Arduino and QSerialPort
I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.

***How do I know with QSerialPort is the connections is ready to send data?***

I don't know how much time do I have to wait for that and it happens every time when I run the application.

The configuration of my QSerialPort instance is:

```
mSerialPort = new QSerialPort();
mSerialPort->setPortName("COM3");
mSerialPort->setBaudRate(QSerialPort::Baud9600);
mSerialPort->setDataBits(QSerialPort::Data8);
mSerialPort->setParity(QSerialPort::NoParity);
mSerialPort->setStopBits(QSerialPort::OneStop);
mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
mSerialPort->open(QIODevice::ReadWrite);

```

I check the device configuration of COM port:

I also changed and play the Arduino delay but nothing changed.

I am sending to Arduino little piece of data. Example:

```
X100.10,Y10.23, H9999, ...others

```

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.

I hope all this information be usefull to give me an answer or at less some tips.

# Answer
I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port. That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude. The timeout of that signal is configured in the bootloader, and is usually something like 1 second.

The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.
> 1 votes

---
Tags: serial, arduino-mega, communication
---


# Question
Title: How do I print the reading serial data sending from Arduino
I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert the data to read.

You can see the receive data has some no printer character.

# Workflow of sending and receiving data between QtSerialPort and Arduino

### Sending Data with QtSerialPort

```
void MainWindow::sendData(){

    QString m_allData = m_sendEdit->toPlainText();
    int i = 0;
    int size = m_allData.size();

    QString line = "";
    int c = 0;
    while(i < size){
        line.append(m_allData[i]);
        if(c == 24){
            int sended = m_serialPort->write(line.toUtf8(), 24);
            m_serialPort->flush();
            line.clear();
            c = 0;
        }
        i++;
        c++;
    }
    if(c > 0){
        m_serialPort->write(line.toUtf8(), c);
    }
    m_serialPort->flush();
}

```

I want to send the data with a buffer size of 24 bytes.

### Reading and Sending Data with Arduino

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

 void loop() {

    delay(1000);

    if (Serial.available() > 0){
        short i = 0;
        int size = Serial.available();
        String data = Serial.readString();
        Serial.print(data);
    }
 }

```

The Arduino code is simple.

### Receiving Data with QtSerialPort

```
void MainWindow::readData(){
    int c = 0;
    char * dataBuffer;
    int size = m_serialPort->bytesAvailable();
    dataBuffer = new char[size];
    c = m_serialPort->read(dataBuffer, size);
    m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
        delete dataBuffer;
}

```

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

# Answer
You have no warranty that Qt will receive the whole message in a single chunk. It may receive "no se" as the first chunk, and then "q pasa" as the second chunk. Since `dataBuffer` is dynamically allocated, it initially contains garbage, and you are printing the part of this garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

```
dataBuffer = new char[size + 1];            // + 1 byte for '\0'
c = m_serialPort->read(dataBuffer, size);
dataBuffer[c] = '\0';                       // terminate the string

```
> 1 votes

---
Tags: serial, programming, c++
---


# Question
Title: Arduino Uno coding problem voltage varying
I was wondering whether anyone could help me... I am using an Arduino Uno and I am writing my code in the Arduino IDE. I am trying to implement the code so that the output voltage can be varied from 0 - 5 volts using 2 pushbuttons. I want to be able to increment the voltage by +0.5 volts from 0-5 volts every time I push Button A. Also I want to decrement the voltage by -0.5 volts from 5-0V every time I push Button B.

Example: (push Button A): output voltage 0.5: (push Button A): output voltage 1.0 etc.

So far when I upload my code the LED as my test for output just flickers between 2 - 4 volts. Can anyone tell me what I am doing wrong? I am not that good at coding so any help would be awesome.

Here is my code.

```
int PWMPin = 6; // output pin supporting PWM
int buttonApin = 8; // buttonA to pin 9 PWM
int buttonBpin = 10; // buttonB to pin 10 PWM
float value = 0; // read the value at 0
float fadeValue = value;
float counter = 0;

void setup() {
  pinMode(buttonApin, INPUT);
  pinMode(buttonBpin, INPUT);
  pinMode(PWMPin, OUTPUT);
}
void loop() {
  int port = analogRead(0);
  port = map(port, 0, 10, 0, 255);
  analogWrite(6, port);
  if (digitalRead(buttonApin) == LOW, fadeValue) {
    if (counter >= 10) {
      counter = 10;
    }
    // fade from min to max in increments of 25.5 points: basically (0.5 volts)
    for(fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5) {
      counter = fadeValue;
      // sets the value (range from 0 to 255):
      analogWrite(PWMPin, fadeValue);
      delay(100);
    }
  }
  if (digitalRead(buttonBpin) == LOW, fadeValue) {
    if (counter <= 0) {
      counter = 0;
    }
    // fade from max to min in increments of 25.5 points: basically (0.5 volts)
    for(fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5) {
      counter = fadeValue;
      // sets the value (range from 0 to 255):
      analogWrite(PWMPin, fadeValue);
      delay(100);
    }
  }
}

```

# Answer
There's a number of very basic things wrong with your code - things that aren't doing what you think, or you just telling it completely the wrong things.

Start by formatting your code properly (INDENTS!) and match up all your brackets. You'll soon see what I see as far as what is wrong.

I'll give you some clues:

---

```
{
if (digitalRead(buttonApin) == LOW, counter)

```

Where to I start with that one...?

---

```
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)
  counter = fadeValue;
  digitalWrite(PWMPin, fadeValue);

```

C is not Python!

---

```
digitalWrite(PWMPin, fadeValue);

```

Writing an analog value to a digital pin?!

---

```
Serial.println(PWMPin);

```

Printing the pin number - now what is the point of that?

---

```
... fadeValue += 25.5 ...

```

Adding a float to an integer - bad practice (and ultimately pointless) - pick one, float or integer, and stick to it.

---

And then there is the whole logic of your program. I can't work out what it's supposed to be achieving. It looks like you've tried to get it to do all sorts of parts of different things and not got it to do anything at all. Strip it right out and get it to do ONE thing - provide a specific, STATIC, voltage. Then add in some way of changing that voltage afterwards.
> 0 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Reading values from the register of a slave
I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.

```
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop(){
Wire.beginTransmission(MPU);
Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for   temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(3330);
}

```

Now there are a few things i want to ask regarding this code: 1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous (see datasheet here) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?

2.`AcX=Wire.read()<<8|Wire.read();`

This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works?

# Answer
> 1 votes
For reading non-consecutive bytes, the “normal” way would be to do a one-byte request and a one-byte read for each byte you want. However, if the bytes you want are close enough (e.g. you want every other byte), it would be faster to do a contiguous read and just ignore the bytes you do not want. E.g.:

```
byte data1 = Wire.read();  // read first byte
Wire.read();               // read and ignore second byte
byte data3 = Wire.read();  // read third byte

```

For your question regarding the meaning of `Wire.read()<<8|Wire.read();`:

1. `Wire.read()` return a 16-bit integer, where the 8 most significant bits are zero and the 8 least-significant bits contain the actual data. In binary, it's something like `00000000xxxxxxxx`, where `x` are the data bits.
2. `<<8` means “shift left by eight positions”, where the missing bits are replaced by zeros. Thus `Wire.read()<<8` is `xxxxxxxx00000000` in binary.
3. The second call to `Wire.read()` return another 16-bit integer in the form `00000000yyyyyyyy`.
4. The vertical bar `|` is the bitwise-or operator: each bit of the left operand is or-ed with the corresponding bit of the right operand to give one bit of the result: `x or 0` is `x`, `0 or y` is `y`.
5. Then, the whole expression gives `xxxxxxxxyyyyyyyy`, where `xxxxxxxx` comes from the first `Wire.read()` and `yyyyyyyy` from the second.

The problem here is that the “first” and “second” `Wire.read()` in the sentence above refer to the position of the call in the line, not to the actual order in which the calls are performed. Thus you may be lucky and get the the correct byte order... or not. You should instead do a single read per statement if you want to control the byte order. For MSB first:

```
AcX = Wire.read() << 8;  // read most significant byte first
AcX |= Wire.read();      // then least significant byte

```

And for LSB first:

```
AcX = Wire.read();        // read least significant byte first
AcX |= Wire.read() << 8;  // then most significant byte

```

---
Tags: arduino-uno, mpu6050
---


# Question
Title: Help understanding how to drive Step motors with Arduino
I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.

My method was as follows:

```
#include <Stepper.h>
*declaring the stepper and all that goes here*
void loop(){ etc.
   basic logic flow stuff
   stepper.step(20); // to move forward twenty steps
   stepper.step(-20) // to move back twenty steps

```

However my boss says this is incorrect as I need to be giving the steppers both *step* and *direction*.

After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.

Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.

# Answer
> 1 votes
I think there is some mis-communication between you and your boss. I do not think your boss is stupid, but I do think he's talking on a different level as you do. You're using arduino which covers up a lot of hardware-interfacing, especially with steppers. I suggest you check out this video: https://www.youtube.com/watch?v=bngx2dKl5jU (I haven't watched it, but It will help you get more into the ideas of your boss)

Now you understand your boss's view, you can try to show him your view. When talking about steppers/arduino and how you can put in negative steps, he might think you're talking trash, as steppers require different pairs of coils to be active depending on the direction. (which is all handled by arduino) The best way is to provide him a visual guidance, so that he can see the relation with his (hardware-view) on the issue and your software/arduino solution.

You could make something like the image below. I'm not sure if this is what you're trying to tell him. I guess you should mention/add that the software on the arduino takes integer values, with negative values being clockwise or such. **And that the arduino will convert this to the right coil pairs or direction and step.**

P.S:with *direct driving*, I think he meant toggling the right pins at the right moments so that the stepper will rotate, basically what the stepper library does for you. Maybe he wants you to implement something like the stepper library (is it an internship? so that you can learn?) I suggest you check some tutorials on how stepper motors work, and how you can drive them 'directly' withouth the use of libraries.

---
Tags: arduino-uno, motor
---


title: Burn Arduino Bootloader - Atmega8L

text:
# Question
Title: Burn Arduino Bootloader - Atmega8L
I am making an RGB LED project right now using the Arduino UNO board.

At this point everything is working fine so I would like to transfer this onto a small microcontroller circuit to be put inside the enclosure. Since the enclosure is small, I cannot fit the UNO board inside it, hence I want to make a small circuit on perfboard with minimal components.

I read that you can burn the arduino bootloader on a standalone AVR (hooked up to power, filter caps and 16Mhz crystal) which can then execute Arduino code.

Any idea how can I do this? Also can I do this on an ATmega8l AVR, since my code is small enough to fit in one? No point wasting a 328 if 8L can do the job.

Thanks!

# Answer
> 1 votes
### The Bootlader

If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the `USBasp`. Or, you can simply use the *Arduino* itself to do this.

* Open the `ArduinoISP` sketch from *File* \> *Examples*.
* Upload it.
* Push `reset` on the Arduino.

### Wire it up

Next, wire up the AVR on a breadboard as shown here: Arduino ISP

* If you are using a variant/derivative, use a crystal that matches the crystal on your board. You might have `not_in_sync()` trouble if you don't.
* Add a 10uF capacitor between `RESET` and `GROUND` on the Arduino, if you are using Uno, or something similar.

### Burning the Bootloader

Then select `Arduino as ISP` as the programmer.

* Goto *Tools* \> *Programmer*.
* Select *Arduino as ISP*.

Now click on *Tools* \> *Burn Bootloader*.

### Verifying it all works

Once that is done, open the Blink LED example and try uploading it to the AVR. You have to use the `Upload using Programmer` option from *File* \> *Upload using Programmer*. You can verify if it is successful, by connecting an LED to `pin 19` of the AVR, and checking if it blinks.

### Notes:

* **Remember** that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the ATMega8 to Arduino pin mapping.
* Don't forget to connect the ground lines of the AVR and the Arduino.
* This worked for me using an ATMega8A-PU. It should work with the 8L too.
* Post here if you have any problems. Glad to help `:)`

# Answer
> 0 votes
You can program the 8u2 by either using a ISP programmer such as Pocket AVR Programmer or directly over USB using the FLIPS software as documented

In reference to:

> "hence I want to make a small circuit on perfboard with minimal components"

I would recommend getting Tiny AVR Programmer or alike to program ATtiny's and at use the ATtiny's directly for small specific tasks. Hence you can avoid the cost of the whole UNO if not needed. You can even emulate limited USB connection as done with the DigiSpark. They even support internal oscillator. So they often need now external parts. They can be often applied without PCB.

# Answer
> 0 votes
Problem with Atmega8A-pu

Make sure the correct com port is selected then on the tools menu select Arduino NG or Older as the board type then choose the ATmega8 as the processor from the tools menu and upload any example Program probably i prefer blink to test (courtesy-PARC-India).

All the best

---
Tags: bootloader
---


# Question
Title: How to copy files from local computer to Yun with scp?
I need to transfer files from my local machine to my Arduino Yun.

I have tried:

```
scp /Users/SSCirrus/Documents/index.html root@arduino.local:/root
scp ~/Users/SSCirrus/Documents/index.html root@arduino.local:/root
# No such file or directory (referring to my desktop)

```

I have confirmed that the filepath is accurate. What's wrong here?

# Answer
Try `~/Documents/index.html`

The `~` represents the current user's home directory, so `~/Documents` is the Documents folder for the current user. It means you don't have to make sure you have spelled the user's home directory exactly right.

Other options are:

* `$HOME/Documents/index.html`
* `Documents/index.html` (if you are in your home directory)
* `cd ~/Documents` then just use `index.html`

... the list goes on ...
> 0 votes

---
Tags: arduino-yun, ssh
---


# Question
Title: How to read code from Arduino Uno to Arduino IDE?
we can upload a code into Arduino UNO from our computers, but how about reading code? Can we read and get C codes from compiled codes from Arduino hardwares? My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

# Answer
> Can we read and get C codes from compiled codes from Arduino hardwares?

While it is possible, even trivial, to disassemble machine code, it is very difficult to convert the assembly code into a higher-level language, and essentially impossible to turn it back into an exact copy of the source code it came from. There simply isn't enough information in the machine code to do so.

> My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

The debug port will work in tandem with appropriate software that will already have access to the source code, so this is not a method for conversion either.
> 8 votes

# Answer
You wont be able to get the code in readable C. It would be in Machine code.
> 1 votes

---
Tags: arduino-uno, c, sketch, debugging, code-optimization
---


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

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

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

# Answer
> 1 votes
What you described is not a big task. I suspect you are new to both the Arduino and computers in general, and so it seems big to you. Hang in there, it is a lot easier than you think.

In many cases, a sensor requires 1 electrical pin (plus ground, which is shared by all). So even an Arduino UNO can read a dozen or more sensors. In many cases the instructions to read the sensor is as simple as 'read(x)' and that takes 2 bytes, so if you got really lucky, the UNO's 32k of memory could read 16k sensors (a 'k' being a thousand if you didnt know).

Reality is it is not quite that simple, but it is not far from it. You probably want to find a library that matches your sensor, and the only hard part is figuring out how to combine many libraries, which indeed do interfere with each other on occasion.

Step 1, learn the basics. Get an Arduino experimenters kit or equivalent, play with the examples until you understand them. It will include some of the sensors you may use later.

Step 2, identify which other sensors you will need, find Arduino compatible versions of those. You will know if it is Arduino compatible if it has an accompanying library, get that also.

step 3, make sure you can make each sensor work by itself first.

step 4, start combining sensors and resolving errors that will show up.

Forget the idea of combining boards, it is an advanced topic and you are no where near ready to try that yet.

---
Tags: communication
---


# Question
Title: Powering a 6-12V motor using a lead acid 6V battery with 6Amps of current?
Hi I'm using a adafruit motor shield v2 and I need to power a DC motor 6-12V but I'm not sure if my battery will be okay for the shield. Will it burn the shield? I'm going to be using 6V so it should draw less current?

# Answer
> 1 votes
If you take the "full load" to be the "stall current", then you can work out the resistance of the winding.

R=V/I = 12/14 = 0.857Ω

From that you can then work out the stall current at 6V:

I=VR = 6×0.857 = 5.143A

That, being the *stall current*, is the *maximum* the motor will draw - the current drawn when it is trying to move an impossible amount of load and the rotor cannot move. At that current you will melt the motor drivers (or they will go into thermal shutdown).

Of course, with a geared motor, that becomes a (comparatively) massive load and would be quite hard to achieve. You have a 50:1 gear ratio, so the stall load is effectively 50x greater.

So there is going to be a limit to the load that you can drive with the motor before it becomes a problem for the driver. There are ways of calculating it from the given torque, gear ratio, load/noload current ratings, etc, but I don't have all that at my fingertips right now.

So you can either "play it safe" and invest in a driver that can cope with the stall current, or experiment and measure what current is drawn by the motor with different loads and see if it stays below the 1.2A limit of the shield.

---
Tags: motor, arduino-motor-shield, current
---


# Question
Title: Trouble making TMP102 work with any ADD0 other than ground
I'm trying to get an Arduino Uno to run four sensors (all I2C). The first two are TMP102 temperature sensors. The address is controlled by tying the ADD0 pin to GND, VCC, SDA, or SCL (four possible addresses, without multiplexing). I get it to receive data just fine through the GND setting.

I wrote some code to collect from two, but before I was even talking to the second one, plugging it in causes the data stream from the GND one to stop. Unplugging it from the breadboard makes it work again. Either sensor in either location on the breadboard will work fine, as long as it's addressed as ground. Neither sensor will, even by itself, work with any other address. I tried some other sketches from the net (one attached below that should read from any of four different sensors), but all have the same issue.

```
#include <Wire.h>
byte res;
byte msb;
byte lsb;
int val;

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

void loop()
{
  res = Wire.requestFrom(72,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "72:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(73,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "73:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(74,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "74:");
    Serial.println(val*0.0625);
    delay(1000);
  }
  res = Wire.requestFrom(75,2);
  if (res == 2) {
    msb = Wire.read(); /* Whole degrees */
    lsb = Wire.read(); /* Fractional degrees */
    val = ((msb) << 4);   /* MSB */
    val |= (lsb >> 4);    /* LSB */
    Serial.print( "75:");
    Serial.println(val*0.0625);
    delay(1000);
  }
}

```

Breadboard: (image link: the forum kept crashing when I tried to upload the image directly) https://www.sugarsync.com/pf/D333436\_95042359\_6938296

Thanks!

# Answer
You see that little solder jumper block on the breakout board labelled "ADD0"? You need to remove the solder from that. It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.
> 1 votes

---
Tags: i2c
---


title: Conver char value to variable?

text:
# Question
Title: Conver char value to variable?
I want to pass the preprocessor values(AT commands) to the Serial.println function. Im trying TCP connection using arduino-SIM900A. I've declared all AT commands to each preprocessor variables like below

```
#define A "AT\r"
#define B "AT+CPIN?\"
...

```

I've assigned all preprocessor variables in char array and pass it into Serial.print using for loop.

```
char varAT[12]={'A','B'....};
for(int i=0;i<=12;i++)
{
Serial.print(varAT[i]);
}

```

Its not printing AT, instead it print preprocessor variable name A. I searched the google how to convert char value to variable, in C there is a function called "eval". Using eval we can acheive, but it wont work in arduino lang. How to solve this?

Thanks.

# Answer
> 0 votes
Ok, first, `char varAT[12]` indicates an array of 12 characters.

Second, quotes indicate literals - 'A' means, literally, the character 'A'. Variables and constants are without quotes (same way you use `i`).

I think you mean:

```
char *varAT[12]={A,B....};

```

Also, your constant `B` is invalid - I think you meant for it to end in `\r"`, not `\"`.

---
Tags: programming, c
---


# Question
Title: How to Communicate between arduinos wirelessly?
I am doing a project where I need to send some numbers between arduinos. But it has to be wirelessly because they will be moving. How to Communicate between arduinos wirelessly? I need to send data between them. Wifi would be preferred.

Thank You.

# Answer
> 1 votes
You can use XBees. They are powerful and do provide wifi connections (the recent versions).

And you rely on well-designed devices which guarantee packet retransmission and they achieve up to 1km in an open field.

XBee still works with serial communications making them an excellent tool for your embedded project.

Just plug your Arduinos and write code to send/receive data. This library is a good start point for API mode.

If you don't mind using all the benefits from ZigBee protocol, just use AT mode where all you push in one side is sent to another via serial communication.

# Answer
> 1 votes
As has been mentioned in the comments, you have at least three possible solutions:

* Wifi using the ESP8266
* Private protocol using the nRF24
* Bluetooth using the HC-05

All of these will handle 20 feet of separation. All of these have high quality libraries for Arduinos and lots of free tutorials and assistance via forums and Stack Exchanges.

Some of the primary differences are price, size of data and power consumption.

My personal weapon of choice, and not knowing anything further about your project ... is the nRF24. This is crazy cheap and pretty easy to use. It also benefits from no need for a Wifi access point and also has a broadcast capability so that multiple devices can receive the same message. The down sides are that it is a private protocol that your phone and laptop can't decode natively (it isn't WiFi).

My second choice would be Bluetooth. This would allow your phone and laptop to be transmitters and receivers as there are plenty of great Bluetooth terminal emulators available.

---
Tags: arduino-uno, bluetooth, wifi
---


title: Are arduino passwords safe?

text:
# Question
Title: Are arduino passwords safe?
Is an arduino password controlled lock safe or can the password be seen if they plug it in to a computer?

# Answer
> 1 votes
There are no passwords inherent to Arduino. You can implement them any way you want, resulting in any safety level from zero safely to nearly uncrackable.

**Not so good**: store the passwords straight in EEPROM. No protection of your data means that there's always a way to read them.

**Quite safe**: hash the password before storing it, for instance through SHA-512. Even if you can read the list of hashed passwords, it's pretty hard (read: nearly impossible) to reverse the algorithm to get the password back. For that reason SHA functions are called one-way functions. When you enter a password you run it through the SHA algorithm and check the hash against the list of hashes in EEPROM.

---
Tags: programming, hardware
---


title: Arduino Servo circuit by example

text:
# Question
Title: Arduino Servo circuit by example
I have an Arduino program that uses the Thread library to create two concurrent threads, where:

* Thread #1 blinks an LED every 500ms; and
* Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.

I am now trying to add a 3rd thread that sweeps a servo back and forth.

Here's my design:

And the schematic that Fritzing generated for me:

And an accompanying actual picture of the wire up:

If you can see it, I've rigged Pin 10 as an `OUTPUT`, and attached the servo's signal line to Pin 9. Here's the code:

```
#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;

Servo servo;
int pos = 0;

static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;

Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();

void setup() {
    pinMode(LED_1_PIN, OUTPUT);
    pinMode(LED_2_PIN, OUTPUT);
    pinMode(SERVO_PWR_PIN, OUTPUT);

    servo.attach(SERVO_SIGNAL_PIN);

    blinkLED1Thread.onRun(blinkLED1);
    blinkLED1Thread.setInterval(250);

    blinkLED2Thread.onRun(blinkLED2);
    blinkLED2Thread.setInterval(500);

    servoThread.onRun(runServo);

    master.add(&blinkLED1Thread);
    master.add(&blinkLED2Thread);
    master.add(&servoThread);
}

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

void runServo() {
    // Give the servo a few seconds to reset to the starting position.
    servo.write(0);
    delay(5000);

    while(true) {
        for(pos = 0; pos < 180; pos += 1)  {
            servo.write(pos);
            delay(15);
        }

        for(pos = 180; pos >=1; pos-=1) {
            servo.write(pos);
            delay(15);
        }
    }
}

void blinkLED1() {
    LED_1_STATUS = !LED_1_STATUS;
    digitalWrite(LED_1_PIN, LED_1_STATUS);
}

void blinkLED2() {
    LED_2_STATUS = !LED_2_STATUS;
    digitalWrite(LED_2_PIN, LED_2_STATUS);
}

```

When I flash this to the Due, two disappointing things happen:

1. The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
2. The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a *feeling* that once I get those blinking again, the servo will *probably* start sweeping as well.

Can anyone spot *anything* that jumps out at them as being wrong here, wiring and code alike?

# Answer
> 2 votes
One thing that immediately jumps out at me is you are trying to power the servo from a digital pin. That is very very wrong.

The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.

Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays. If one of your functions never returns (like your servo one) then the whole system will lock up. You need to make your servo function non-blocking like your LED functions. Give it a 15ms time setting and only move one step of the servo each time it gets called.

Ok, according to comments and research I can confirm that in fact the Thread library is really badly named. It doesn't run threads, it just runs different functions at different times. Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen. There is absolutely no concurrency whatsoever. It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.

Basically the operation is thus:

* Add a function and its time to a list.
* Work through the list to find a function whose time has expired
* Call that function
* Continue through the table
* Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion. Only when a function returns is the system able to move on to the next entry in the function list.

You *must not* use `delay()` in your "thread" functions for anything more than maybe 1-2ms of delay *in total*. You *MUST* return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.

So your servo thread would look something like this:

1. Add my current "direction" to the servo value
2. If the servo value \< 0 or \> 180 then invert the direction and limit the value to 0-180.
3. Write the value to the servo

That is then triggered every 15ms by the thread library.

So as real code it may look like:

```
void runServo() {
    static int direction = 1; // 1 = up, -1 is down
    static int value = 0;

    value += direction;
    if ((value <= 0) || (value >= 180)) {
        direction = 0 - direction; // Change direction from + to - or - to +
    }

    value = max(min(180, value), 0); // Clamp it to between 0 and 180

    servo.write(value);
}

```

---
Tags: arduino-due, servo, wires
---


# Question
Title: Adafruit_GFX setRotation not working when called from within a class
Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working. The code is very straight forward.

If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.

Outside of the class, the rotation works fine.

Any help would be greatly appreciated!

```
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_DC 5
#define TFT_CS 3

Adafruit_ILI9341 *tft;
uint8_t newRotationAngle = 0;

void drawStuff() {
    tft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
    tft->fillRect(0, 0, tft->width(), tft->height(), ILI9341_BLACK);
    tft->setCursor(0, 0);

    tft->print(F("01234567890"));
    delay(250);
}

class test {
public:
    void init(Adafruit_GFX *_p) { ptrTft = _p; };

    void inClassRotation(int newRotation) {
        ptrTft->setRotation(newRotation);
        drawStuffInClass();
    };

    void drawStuffInClass() {
        ptrTft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
        ptrTft->fillRect(0, 0, ptrTft->width(), ptrTft->height(), ILI9341_BLACK);
        ptrTft->setCursor(0, 0);

        ptrTft->print(F("01234567890"));
        delay(250);
    }

    Adafruit_GFX *ptrTft;
};

test instance;

void setup() {
    tft = new Adafruit_ILI9341(TFT_CS, TFT_DC);

    tft->begin();
    tft->setTextSize(2);

    instance.init(tft);
}

void outsideClassRotation(Adafruit_GFX *passed) {
    passed->setRotation(newRotationAngle);
    drawStuff();
}

void loop(void) {
    newRotationAngle++;

    // This works. No problems.
//    outsideClassRotation(tft);

    // This does NOT rotate but still prints the text fine.
    instance.inClassRotation(newRotationAngle);

}

```

# Answer
I would actually be quite surprised if `outsideClassRotation()` actually worked. My guess is that *it does not work as is*. Maybe it did work at some point, but then you made some subtle changes to your code and did not check that it is still working.

Here is the deal: there are two `setRotation()` methods:

* `Adafruit_GFX::setRotation(unsigned char)` does very little besides storing the rotation angle... which is not used anyway.
* `Adafruit_ILI9341::setRotation(unsigned char)` actually sends commands to the LCD asking it to apply the rotation; this is the method you want.

The problem is that *these methods are not `virtual`*, which means that when you call them through a pointer, as in `some_pointer->setRotation(the_angle);`, you get the method corresponding to *the type of the pointer*, not the type of the actual object. For example:

```
tft->setRotation(the_angle);     // calls Adafruit_ILI9341::setRotation()
ptrTft->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()
passed->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()

```

I checked this by uncommenting your call to `outsideClassRotation()` and disassembling the compiled binary: both times you are calling `Adafruit_GFX::setRotation()`.

**Solution**: change your `Adafruit_GFX *` pointers to be of type `Adafruit_ILI9341 *`, or patch Adafruit\_GFX.h to make `setRotation()` virtual.
> 0 votes

---
Tags: lcd, library, adafruit
---


# Question
Title: What to with reset pin when laying out Arduino PCB?
I'm designing a PCB with a standard arduino ATMEGA328 DIP IC. Do I need to make a connection to the reset pin?

# Answer
"Atmel AVR042: AVR Hardware Design Considerations"
> 1 votes

# Answer
Yes, you do. The pin needs to be pulled up to Vcc via a pullup resistor - typically 10KΩ. Also, if you are using the Arduino bootloader and want to program via serial then this pin should be connected to your serial interface's DTR pin through a 100nF (typically) capacitor. It is also often desirable to provide a reset button which switches this pin to ground.

You should examine the Arduino Uno's schematics and use them as a reference.
> 0 votes

---
Tags: system-design
---