# Question
Title: How can Arduino know that the number in a variable is a pin number and not something else?
I have a question with the topic *variables*.

So, a variable is a place where you can store data.

And when you make a variable with datatype int (`int ledpin=13;`) then you store a value 10 in a variable named `ledpin`.

BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

# Answer
> 3 votes
You need to put the correct number into the pinMode() function.

You could put the number into a variable like:

```
int ledPin = 13;
pinMode(ledPin, OUTPUT);

```

or you can put a number straight into pinMode() like this:

```
pinMode(13, OUTPUT);

```

Whatever number you put in will be the pin that you start using.

Here's an example to blink the onboard LED:

```
int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // Whatever number is in ledPin is made an output.
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(ledPin, LOW);    // sets the LED off
  delay(1000);                  // waits for a second
}

```

# Answer
> 3 votes
Yes, a variable is just somewhere to store some data.

It's what you *do* with the variable that is important.

For instance:

```
int ledpin = 13;
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);

```

That will set the variable `ledpin` to 13, then the next line will query the `ledpin` variable to find out what number it is, then pass that number to the `pinMode` function to set the mode of the pin to `OUTPUT`. The line after then does the same thing but passes the number 13 that it read from `ledpin` to the `digitalWrite` function to turn the LED on.

However, if you do this:

```
int ledpin = 13;
pinMode(ledpin, OUTPUT);
ledpin = 10
digitalWrite(ledpin, HIGH);

```

then it will act just the same at first, but the `digitalWrite` function will get the number 10 not the number 13 since the value in `ledpin` has been changed to 10 in the third line.

Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.

# Answer
> 0 votes
> BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

The Arduino does not "know" the intention of a variable. The variable "becomes" a pin number when passed as an argument to pinMode() or digitalRead().

The use of a variable to "name" a pin is part of a programming style. There are a lot of examples sketches that try to convey programming style. One of these is to reduce the amount of ripple effects of change; reduce the number of line to change for a logical change.

Continuing the LED pin number example above. The "baseline" code is:

```
void setup()
{
  pinMode(13, OUTPUT);
  ...
}
void loop()
{
   digitalWrite(13, HIGH);
   ...
   digitalWrite(13, LOW);
   ...
 }

```

This works just fine BUT what is the ripple effect if we change the pin "13". The example uses symbols OUTPUT, HIGH and LOW which are also just numbers.

Typically in C the tradition is to use the preprocessor and define a macro.

```
 #define LED 13

```

The preprocessor will replace LED in the source code with 13 and the compiler sees the same code as above.

An alternative is using a variable.

```
 int LED = 13;

```

The drawback is that memory is allocated and it is possible to change the value at run-time which is often a very bad idea especially for a pin. The definition should actually be:

```
 const int LED = 13;

```

The drawback with the macro is that it is just a value. In C++ it is best to use a constant variable. This tells the compiler both what data type and value it is. A constant variable cannot be assigned (again).

The next level to strength code quality and reduce ripple effects is to use lexical scope. A lexical scope such as a function body, class or namespace defines "when" a symbol is available.

An example; first global scope where definitions are available across the source code (just as for a macro):

```
const size_t BUF_MAX = 32;
static char buf[BUF_MAX];

const char* read()
{
   ...
   for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
   ...
}

```

Local lexical scope; definitions within a function:

```
const char* read()
{
   const size_t BUF_MAX = 32;
   static char buf[BUF_MAX];
   ...
   for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
}

```

The symbols buffer *buf* and the buffer size *BUF\_MAX* are only available in the function.

```
class Reader {
public:
  void read()
  {
    ...
    for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
  }
protected:
  const size_t BUF_MAX = 32;
  char m_buf[BUF_MAX];
  ...
};

```

Again the symbols are only available within the class and member function. Here is also another example of programming style. The prefix *m\_* is used to show that it is member data.

Last, the same example using a namespace:

```
namespace Reader {
  const size_t BUF_MAX = 32;
  char buf[BUF_MAX];
  ...
  void read()
  {
    ...
    for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
  }
};
...
for (int i = 0; i < Reader::BUF_MAX; i++) Reader::buf[i] = ...;

```

All symbols must have the prefix Reader when used outside the namespace.

These techniques have been developed to allow writing larger programs with reuse. It is important to use them when writing a library for Arduino and especially when sharing. Ripple effects and symbol redefinition/collisions are reduced.

---
Tags: programming
---


# Question
Title: How are HIDs (keyboard,joypad) created and mapped?
I am creating an electronic device that has a 4 position rotator switch and a SPST Momentary ON push button. For the knob, I plan for position 0 to be low (OFF). Position 1-3 are high (ON). But I want these positions to equate to a different signal so they each have different values. When push button is pressed, it sends a high (ON) signal.

Can someone point me into slightly setting up the circuit to accomplish this? And how can I create a remapper program (preferably in C++) that detects the HID device and allows the end-user to remap the pushbutton signal to any QWERTY key? I want replicate this process for each input of my device.

# Answer
When the Arduino sends data to the computer using the HID protocol it sends what is called a *HID Report*. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.

In the case of keyboard events it sends a *HID Keyboard Report*

It can send events for up to 6 keys at once along with up to 8 *meta* keys. How those key events are interpreted are down to the *Keyboard Mapping* used on the computer. This is the setting (usually in the *Language* or *Regional* settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.

While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.

So how would you go about doing what you want to do? Well, my recommendation is not to do it on the computer, but to do it on the Arduino. The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily. So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event. You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings. How you do that communication (what protocol you come up with) is entirely up to you.

---

As for the hardware side of things - all you really need is just the switches / buttons and wire. Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground. For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.
> 1 votes

---
Tags: electronics
---


# Question
Title: Arduino mini being programmed with CH340G
So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.

So, this programmer has pinout of 5V|GND|TX|RX|3V3.

I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).

I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.

There's still no connection between them.

Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?

# Answer
> 1 votes
First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See this page or the arduino uno schematics to see how to put the capacitor (it's simply in series with the signal.

However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.

As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.

---
Tags: programming, arduino-mini
---


# Question
Title: Atmega328 PWM frequency setting not working
I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:

```
DDRD |= (1 << PORTD6); //Setting pin D6 as output
OCR0A = 128; //50% duty cycle
TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

```

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency? Or where am I making the mistake? Thanks for any answers.

# Answer
Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden initialization?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.
> 5 votes

---
Tags: pwm, c, atmega328
---


# Question
Title: What's the difference between setting a variable outside a function and setting a variable inside a function?
I'm programming C++ for arduino and today I have seen an example like this

```
void loop() {
    byte variable = 0; // << This variable is the question.
    //more stuff here
}

```

Is the same as this?:

```
byte variable = 0;

void loop() {
    //stuff here
}

```

If the answer is "no", my question is "why?".

Thanks for your time!

# Answer
> 5 votes
The difference is not only about where you set the variable, but about where you defined it as well.

Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program. If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.

If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.

If you define it inside the function, but *with* a static specifier,

```
static byte variable = 0;

```

then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and *will not* be executed within function.

Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.

# Answer
> 4 votes
No, it's not the same. Instructions within the loop() repeat every time the program gets to the end. If you set your variable at the start of the loop, it will automatically get reset to the default when you might not want it to be reset. The author of the example wants to reset to default every time the loop completes.

---
Tags: arduino-uno, c++
---


# Question
Title: Why does an RGB LED between VCC and PWM work?
I'm an Arduino beginner and I recently bought a cheap starter kit on eBay. One of the lessons in the starter kit is an RGB LED controlled by 3 PWM output pins. However, the arrangement of the connections seems a bit funny to me:

To my surprise, it worked. I could see the three LEDs inside the plastic change colors. Why does this work? Do the PWM pins accept current whilst low? Is this a common arrangement? See the above link for the code provided in the lesson.

# Answer
> 6 votes
This is a common arrangement and is known as *Common Anode*, and the I/O pin is said to be *sinking* current.

To better understand what is happening here it's best to think of an I/O pin as a two-position switch:

When the I/O pin is HIGH point 1 is connected to point 2. When the I/O pin is LOW point 1 is connected to point 3.

So when HIGH the circuit is Vcc -\> D1 -\> R1 -\> Vcc (or the other way around - I have done it that way because of the polarity of the LED), and no current can flow since it has nowhere that isn't at a lower potential than Vcc to flow to.

But when the I/O pin is LOW the circuit is now Vcc -\> D1 -\> R1 -\> GND and so current can flow through it all to ground. As a result the LED now lights up.

One thing you may have noticed now is that the operation is backwards. Set the IO pin to LOW to turn the LED ON. That has the effect, as well, that PWM duty cycles are reversed. `analogWrite(ledPin, 0)` will be full brightness and `analogWrite(ledPin, 255)` will be off.

# Answer
> 2 votes
> Do the PWM pins accept current whilst low?

The pins **sink** current when low. And yes, that is commonly done. The pins are **not** "do nothing" at LOW, and "put 5V there" at HIGH. They are specifically designed to try to source (drive high) current when HIGH and sink (drive low) current when LOW.

To have pins (more or less) do nothing, you have to set them to INPUT mode. Then they try to neither source nor sink.

*Caveat:* if you enable the internal pull-ups they will try to weakly source current.

---

> Is this a common arrangement?

It is quite common, depending on whether the device you are controlling is active high, or active low.

# Answer
> 1 votes
The RGB LED is common anode. This is why it is connected to VCC and the PWM pins pulls down to light resp LED.

A common cathode RGB LED would be connect to GND and the PWM pins would pull up to light

Cheers!

---
Tags: led, pwm
---


# Question
Title: Arduino ethernet need help with game logic!
I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.

Example image: https://i.stack.imgur.com/gtnUm.png

I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.

Code that switches LED:

```
led = random(1, 4);
switch(led) {
  case 1:
    ledLeftState = HIGH;
    break;
  case 2:
    ledMiddleState = HIGH;
    break;
  case 3:
    ledRightState = HIGH;
    break;
}

```

Code that checks if the wrong button is pressed:

```
 if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
    static unsigned long lastTime = 0;
    if(millis() - lastTime > 400) {
      Serial.println("Ouch, minus ten miliseconds!");
      hurt += 10;
      lastTime = millis();
    }
  }

```

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.

Thanks for your time!

# Answer
> 1 votes
The line

```
if(millis() - lastTime > 400)

```

is supposed to test that the button press does not come right after the LED switches. This means the line

```
lastTime = millis();

```

should be right when you change the displayed LED.

# Answer
> 1 votes
First: Your buttons are not wired up properly according to the diagram. They seem to be only connected to 5V.

On Arduino buttons can be wired both active-high and active-low. Active-high means then when the button is pressed you get a HIGH signal, and LOW otherwise. Obviously active-low is the opposite. The code below assumes active-high.

You might want to go do some reading on "button de-bouncing". I've included some rudimentary code to help, but it's not perfect. A 0.1 micro-farad capacitor across the button terminals will help with this too.

So ... onto the code.

It's really the game-loop that needs some work. I'll assume your random LED-lighting code is in a function called newRandomLED(), and variables *ledLeftState*, *hurt*, etc. are globals.

The *new\_pattern\_time* variable should probably also be set in newRandomLED() since they always are called together. But I'm trying to help, not re-write ;)

```
const int debounce_time  =  30; // milliseconds
const int max_push_time  = 400; // milliseconds - How long is a turn

// Draw the first LED pattern
newRandomLED();

// the time the latest LED pattern was re-drawn
unsigned long new_pattern_time = millis();

// Reset the score
hurt = 0;

while (true) // TODO: insert some game-length decision
{
    // Has the time to press a button expired?
    if (millis() - new_pattern_time > max_push_time)
    {
        // TODO: sound the buzzer for *fail*

        // Time is up, penalise the user
        hurt += 10;

        // Time for a new pattern
        newRandomLED();
        new_pattern_time = millis();
    }

    // Perform the initial-read of the buttons
    int butt_left  = digitalRead(BUTTON_LEFT);
    int butt_mid   = digitalRead(BUTTON_MIDDLE);
    int butt_right = digitalRead(BUTTON_RIGHT);

    // de-bounce the button presses
    delay(debounce_time);
    if (butt_left == HIGH)
        butt_left = digitalRead(BUTTON_LEFT);
    if (butt_mid  == HIGH)
        butt_mid = digitalRead(BUTTON_MIDDLE);
    if (butt_right == HIGH)
        butt_right = digitalRead(BUTTON_RIGHT);

    // So now we have the state of the three buttons, de-bounced too.
    // Was there any input from the user?
    if (butt_left == HIGH || butt_mid == HIGH || butt_right == HIGH)
    {
        // So one (or more) buttons have been pressed
        // Check that for each LED that is on, that the button is pressed too
        boolean success = true;
        if (ledLeftState != butt_left)
            success = false;
        if (ledMiddleState != butt_middle)
            success = false;
        if (ledRightState != butt_right)
            success = false;

        // Was the user correct?
        if (success == true)
        {
            // TODO: sound the buzzer for *WIN*
            hurt -= 10;

            // And we need to show the next pattern
            newRandomLED();
            new_pattern_time = millis();
        }
    }
}

```

So essentially you're looping around checking to see if the player pressed anything. Most of the time, there will be no input from the user, and this loop will spin thousands of times without any input.

On each loop the code checks to see if the time is up, or some buttons were pushed. In both cases, it's time for a new pattern. A side effect of this code is that it allows for simultaneous button pushes, so at higher difficulty levels you could illuminate more than 1 LED.

Note: this code is a quick response to the question. It may not be 100% correct, nor have flawless C-textbook syntax.

# Answer
> 0 votes
Off the top of my head and without a compiler would something like this work?

```
int BasePin = 3;
int BaseButton = 7;

int led = random (1, 4); // Are you sure its 4??
digitalWrite(BasePin+led, HIGH);

if (digitalRead(BaseButton+led))
{
  // Success
}
else if (millis() - lastTime > 400))
{
  // Out of time
}
else if (  digitalRead(BaseButton+1)
        || digitalRead(BaseButton+2)
        || digitalRead(BaseButton+3)
{
  // Wrong button
  // (The right one will have been handled by the earlier clause)
}

```

OK the last clause is a bit of a hack, but it should give you a starting point to tidy up.

You are probably going to get issues unless you debounce the switches.

---
Tags: c
---


title: Arduino code not working

text:
# Question
Title: Arduino code not working
Basically its an arduino project in which i am using an analog temperature sensor ky 013. The sensor is reading the temperatures correctly but what i want is to print the temperatures showed on the serial monitor to a lcd screen. I did the wiring and everything correctly but there is something wrong with the code which i couldnt figure out. Here is the code.

```
#include <math.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState=0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000/RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin,INPUT);
}

void loop()
{

 switchState=digitalRead(sensorPin);
 int readVal=analogRead(sensorPin);
 double temp =  Thermistor(readVal);
 Serial.print("Temp. : ");
 Serial.print(temp);
 Serial.println(" Celsius");
 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Temp: ");
 lcd.print(temp);
 lcd.print(" C");
 delay(500);
}

```

# Answer
Please format your code. I know it takes longer, but the payoff is in readability and maintainability. It's well worth the extra effort.

```
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState = 0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000 / RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp)) * Temp);
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin, INPUT);
}

void loop()
{
    switchState = digitalRead(sensorPin);
    int readVal = analogRead(sensorPin);
    double temp = Thermistor(readVal);
    Serial.print("Temp. : ");
    Serial.print(temp);
    Serial.println(" Celsius");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.print(" C");
    delay(500);
}

```

I think the problem is the

```
lcd.print(temp);

```

Try casting it to a float from a double (and two decimal places). Maybe you just need the decimal places.

```
lcd.print((float)temp, 2);

```
> 1 votes

---
Tags: c++, temperature-sensor
---


# Question
Title: avrdude: stk500v2_getsync(): timeout communicating with programmer error
When I try to upload I get this error. I cannot upload the program into my Arduino Mega ADK board. I tried putting the drivers agiain too, but it does not work.

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

```

Is it the problem with the hardware or the system? Please help me. Thank you :)

# Answer
> 1 votes
I get this problem sometimes with some of my boards. I usually solve the problem following these steps:

* Set the compiler on debug/verbose mode to see what's happening
* Launch compilation/upload
* When the compile phase is done, and the upload process is about to start, press the reset button on the board

Usually that takes care of the problem.

# Answer
> 1 votes
What @dda says in his answer are good points.

Removing the board USB for a few seconds, then re-plugging and re-selecting the COM port in the IDE usually fixes it. Sometimes when you un-plug and re-plug the board it changes COM ports.

Also if you have a short-circuit wired to your arduino sometimes it becomes non-responsive in this manner.

---
Tags: uploading
---


title: Where to start?

text:
# Question
Title: Where to start?
I am totally new to Arduino and I'm a real beginner with electronics and robotics. I would like to know where to start, knowing that my ultimate goal is to build an autonomous robot (I know that I will not be able to do this project before learning a lot of things). I am a developer so I have no problem with C and C++, actually I am using C++ at work.

Thanks

# Answer
> 4 votes
I would start with a lot of small projects, each designed to give you confidence over one small aspect. For example:

* Detect variations in light with an LDR
* Operate a motor (there are various types of motors) - including controlling one with a MOSFET or BJT transistor
* Blink LEDs
* Connect something with a fancier interface (eg. I2C or SPI) and get the hang of "talking" to a more sophisticated interface chip (you'll probably need this for things like balancing)
* Try distance detection. Eg. with bouncing light or sound off an obstacle
* Communicate between two Arduinos - get used to communications protocols, reliability, packet loss, etc.
* Get used to detecting switch presses, either individual ones, or a keypad (or both)
* Look into reverse polarity protection
* Look into detecting low voltages on your batteries
* Try radio communications (probably need to send your robot instructions) - there are various different ways of doing that
* Possibly experiment with motor-driver boards (eg. H-bridges) which you may need for driving wheels
* Investigate reading continuous values (eg. potentiometers, rotary encoders)
* Investigate read-outs (eg. 7-segment LED displays, or LCD displays)
* Investigate generating sounds (beeps, tunes)

You could take a look at my radio controlled car project. I look into some of those things there, and describe how I handled them.

I would do these things initially on the bench. Don't try to assemble something fancy until you have some experience with how the individual parts work.

# Answer
> 2 votes
It's sounds silly, but just get an UNO, a breadboard, wires, 1 resistor (220 ohm) and an LED.

Wire up a LED circuit, and program the Arduino to flash the LED. (There's a million examples of this all over the internet).

Without getting into any sort of heavy circuits or complex programming, you'll have a quick stress-free introduction to Arduino.

This will teach you:

* using a breadboard
* wiring digital ports on the Arduino
* polarity of components (LED yes, Resistor no)
* using the Arduino IDE
* uploading to the board

This is a great jumping-in point because it's reasonably fool-proof.

Sure you can eventually be PID-controlling the balance of a 2-wheel robot. But build yourself a working foundation of good knowledge first.

# Answer
> 1 votes
Personally I think the best way to start is hands on with a small robot. I mean the kind that have a couple of wheels, are circular and only a few inches in diameter. You can add many kinds of sensors or actuators as you learn. You get to see it move and hold it and pick it up.

The idea is to start with basic LED control and then get motors turning, sensors on, and then improvements and upgrades.

If you're ok at coding then electronics may be the bottle neck. Get a good book is my advice. As far has hardware the EEVBLOG guy Dave gives a good run down on what he recommends here.

Just start.

---
Tags: arduino-uno
---


# Question
Title: Analogue input 0 staying at 0 when sensing light with Arduino and a photocell
I am doing a circuit for capturing light intensities.

I followed the tutorial provided by Adil Moujahid

Yet, when I plug the jumper wires on 5V the circuit stops working and when I plug on 3.3V the analog in A0 sent back only a series of zero...

What did I missed? I acknowledge that I tried to be the most economical on the jumper wires...

# The sketches, program and circuit given by Adil Mouhajid

# My attempt

# Answer
> 6 votes
The two strips on either side of the bread board, color red and blue (typically) are power rails, and each strip is all connected. Your circuit connections that are on that strip are shorted together and will not work. I suggest following his layout exactly to begin with, and once you've learned the basics of breadboard connections, you can start doing your own layouts.

---
Tags: sensors, hardware, prototype, analog-sampling, photoresistor
---


title: Speeding up Arduino DC Motors

text:
# Question
Title: Speeding up Arduino DC Motors
I am using the Adafruit Motor Shield v2.3 for Arduino Uno. I am using the analogWrite() command to power my DC motor and have set the speed to 255. Is there any way to speed up the Arduino motor even further? Thanks!

# Answer
> 1 votes
The speed of a motor is a function of the motor itself and the voltage applied to it. There is no programmatic way of increasing the speed of a motor. You would either need to increase the voltage being applied to the motor (as long as it is within the limits of your motor and speed controller) or find a different motor to use that is faster.

It appears the Adafruit motor shield accepts between 5-12 volts, if you are not already at the maximum of 12 volts, and your motor is rated to allow it, you can increase the voltage you are applying to the shield. All that `255` means in this case is give the motor all the power that is available, so if you are only giving the controller 5 volts, it is only going to give the motor 5 volts.

~~Also I might recommend instead of using `analogWrite()` that you use the official Adafruit library to control your shield as it uses its own PWM library which is more performant for motor control than the built-in Arduino one.~~

**EDIT**

Actually, with v2 of the shield, it has its own PWM driver controlled over I2C. In which case `analogWrite()` shouldn't work at all, or at least it doesn't do what you think it does. Instead use the official Adafruit library and I also recommend following the official tutorial as well.

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


# Question
Title: Will this AC-DC converter chip really work with arduino?
I am looking for a compact solution to convert some 220V/20amp AC to something edible by our arduinos (like 5V/2amp DC). I would like to plug directly my arduino to the wall. I found many things like some Hi-link (HLK-PM01) chips ... But I also found this one :

That seems perfect, but unfortunatly, I can not find any tuto or example of use for this, shipping included, really cheap chip.

The datasheet is here.

What do you think about it ?

# Answer
> 5 votes
> What do you think about it ?

If you have to ask, don't do it. Mains voltage can be **dangerous** and should only be done if you know what you are doing and how to be safe. The best choice is to just use pre-built adapters from reputable sources.

---
Tags: power, current
---


# Question
Title: Why is my Adafruit motor shield not spinning my motors?
I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.

I removed the vin pin, and I'm using this tutorial/code to make the DC motor spin.

I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.

Any ideas?

Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.

```
// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

AF_DCMotor motor(4);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  // turn on motor
  motor.setSpeed(200);

  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tock");

  motor.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tech");
  motor.run(RELEASE);
  delay(1000);
}

```

# Answer
A couple of things I see...

**1.)** Your motor leads may be shorting out of the housing of the motor. make sure they are not.

**2.)** You may have the motor on the wrong port for the given code:

On line 7 of the code it reads: `AF_DCMotor motor(4);`

So try switching physically your motor to port 4.

**3.)** Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.

```
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknow error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

```
> 5 votes

# Answer
Per the comments above, and the documentation from Adafruit, a 9V battery is insufficient for use with motors as they do not provide enough current.
> 3 votes

# Answer
I see that this is still not working even with a proper battery. My next best guess is you need to update your library:

> ```
> // Adafruit Motor shield library
> // copyright Adafruit Industries LLC, 2009
> // this code is public domain, enjoy!
>
> #include <AFMotor.h>
>
> ```

Judging by `2009` and `AFMotor.h` you have a copy of an old version of the library. I recommend getting the latest version and following the official tutorial.
> 2 votes

---
Tags: arduino-uno, motor, adafruit, arduino-motor-shield
---


# Question
Title: multiple relays not triggering correctly
quick description of the sketch: its a clap on/off relay that turns on only when it's dark.

Cannot seem to get the relays to stay off. What happens is they are off by default then when I do the double clap to turn them on that works, after this I double clap to turn them off and then go off then immediately go on again. I can get a single relay to work perfectly but when I uncomment the rest there seems to be a problem.

I am assuming it has something to do with the delay for the clap sensor, but I am not entirely sure-- I have tried quite a few things to try to resolve it but am really lost as to why this might be happening. ideas?

```
int soundSensor = A2;
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A1;
int photocellReading;
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  /////////////
  // photo sensor
  ////////////////////
  photocellReading = analogRead(photocellPin);
  photocellReading = 1023 - photocellReading;
  LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

  if(photocellReading > 500){
      photoSensor = 0;
  }
  if(photocellReading < 500){
    photoSensor = 1;
  }

  /////////////
  // clap sensor
  /////////////////////
  int sensorState = digitalRead(soundSensor);
  //erial.println(sensorState);
  if (sensorState == 1)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
    }
  }

  if (millis()-detectionSpanInitial >= 500)
  {
    if (claps == 2)
    {
      if (doubleClap == 0)
        {
          doubleClap = 1;
        }
        else if (doubleClap == 1)
        {
          doubleClap = 0;
        }
    }
    claps = 0;
  }

  if(doubleClap == 1 && photoSensor == 0){
    digitalWrite(relay, LOW);
    digitalWrite(relay2, LOW);
    digitalWrite(relay3, LOW);
    digitalWrite(relay4, LOW);
    Serial.println("off");

  }
  else{
    digitalWrite(relay, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);
    digitalWrite(relay4, HIGH);
    Serial.println("on");
  };

}

```

# Answer
As it happens, you are debugging in the dark. You have half a dozen devices attached to (presumably) some Arduino, driven by some hard-to-read code that might not work properly even if all the devices work ok, and definitely won't work properly if any of them fail or are incorrectly attached.

For example, you can't tell from that code whether your photoSensor works, whether your clap sensor works, or whether your relays work. Before messing around further trying to test all at once, run some definitive tests on each device individually. For example, run the following sketch and see if your system is able to turn on all of the relays at the same time.

```
// Test if relays work ok: First individually for a second each,
// then all together for 2.5 seconds
enum {relay=A0, relay2=A3, relay3=A4, relay4=A5, nRelays=4};
byte rePins[] = { relay, relay2, relay3, relay4};

void setup() {
  for (int r=0; r<nRelays; ++r) {
    pinMode(rePins[r], OUTPUT);    // Set pin to outputs
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }
  Serial.begin(115200);
}

void loop() {
  byte r;
  // Turn relays on individually for a second each, with half-second gaps
  for (r=0; r<nRelays; ++r) {
    delay(500);         // Wait half a second
    Serial.print("Turning on relay #");
    Serial.print(r+1);
    Serial.print(" at ");
    Serial.println(millis());
    digitalWrite(rePins[r], HIGH); // Turn on relay
    delay(1000);           // One on for a second
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }

  // Turn all the relays on
  Serial.print("Turning all relays on at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], HIGH); // Turn on relay

  delay(2500);          // Wait 2.5 seconds

  // Turn all the relays off
  Serial.print("Turning all relays off at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], LOW); // Turn off relay
}

```

Next, write a sketch to report results from photosensor and clap sensor readings. Once you know if your hardware is working, try to get your double-clap logic to work without involving the photosensor, or vice versa. Also, try to make the double-clap logic work just using a button in place of the clap sensor.

Note, to shorten your code and to get rid of some of the features that make it hard to read, do some of the following changes. With the code slightly shorter, it may be easier to comprehend and debug.

(a) Instead of introducing program constants as integer variables, introduce them as program constants. For example, instead of the verbose

```
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;

```

say something like

```
enum {relay=A0, relay2=A3, relay3=A4, relay4=A5};

```

which tells the compiler that `relay` is a constant with the value `A0`, etc.

(b) Since you don't use variable `LEDbrightness` for anything, take it out. With that gone, change the verbose

```
photocellReading = analogRead(photocellPin);
photocellReading = 1023 - photocellReading;
LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

if(photocellReading > 500){
    photoSensor = 0;
}
if(photocellReading < 500){
  photoSensor = 1;
}

```

to

```
photoSensor = analogRead(photocellPin) > 523;

```

which will set `photoSensor` to 0 or 1 much as before. (It is slightly different: It handles a `photocellReading==500` case that your code ignores.)

(c) Change the verbose and badly formatted

```
  if (doubleClap == 0)
    {
      doubleClap = 1;
    }
    else if (doubleClap == 1)
    {
      doubleClap = 0;
    }

```

to

```
 doubleClap = 1 - doubleClap;

```

(d) Refactor to cut about half the code involving `detectionSpan`.
> 1 votes

---
Tags: c++, relay
---


# Question
Title: Does a graphical driver chip exist for this project?
I need some expert advice. I'm using an Arduino Leonardo, which I have got working with a Nokia 3310 monochrome screen. I wrote some code to draw any graphics to the screen.

What I want to know is, can I buy a chip from somewhere that will offload most of the CPU usage (for graphics from the Leonardo) that draws numbers and letters to the screen and basic graphics (different types of polygons and lines)? So I'm looking for a chip designed to do the graphical work and a data sheet reference for the chip.

# Answer
I have no idea if there is a chip or not, but I doubt it.

But then, why do you need one?

You already know how to communicate with the screen, so why not off-load those functions on to another Arduino (make your own small ATMega328P based board to do it) and then communicate with that through whatever means you like from your Leonardo?

You don't *need* a dedicated chip to do what you can quite easily program an Arduino to do.
> 6 votes

---
Tags: lcd
---


title: where I can find ground?

text:
# Question
Title: where I can find ground?
there is AVR AVR ATmega32 and a board within. there is outputs for all ports (A, B, C, D) on board, and Vcc. the problem is - I have no external GND output. to watch current - I should search for GND pin everytime. and now I need ground on my solderless board for LEDs and temperature sensor.

let's guess that I have no idea what is current or electricity. so the question is: where I can find ground to connect it to solderless board? maybe I can use something else, except MCU? (like my hand or smth :D)

# Answer
I've just sorted things out.
There is two interfaces - ISP and JTAG. ISP is busy with programmer everytime, but JTAG is free.
So, I have found pinout of JTAG interface and achieved GND.
There is pinout:
<sub>(source: digital-circuitry.com)</sub>
> 2 votes

# Answer
Pin 11 of the chip itself is GND (see below). In the photo it appears to have a decoupling capacitor between GND and VCC (pin 10). You could solder a wire onto pin 11 (on the chip socket, not the pin itself) - it might be easier on the back of the board. Also pin 31 would be an option.

---

Also the reset switch is almost certainly wired (on one side) to GND. It looks to me like most of the board is "ground plane" (continuous copper) so find which part of the switch is wired to that, and solder a wire to it.
> 1 votes

---
Tags: avr, electronics
---


# Question
Title: Problem while writing sketch for GSM module sim800
I wanted to my GSM to recieve SMSs. I have written a sketch for it. But while verifying the sketch an error pops out in this part:

`if (sms.available()) {
 sms.remoteNumber(senderNnumber, 20);
 if (senderNumber == "09432167015") {
 c = sms.read();
 if (c == "yes") {
 alarm_police();
 }
 }
 }`
The error message:

> Arduino: 1.6.5 (Windows 8.1), Board: "Arduino/Genuino Uno"
>
> GuardDog\_v2.5.ino: In function 'void loop()': GuardDog\_v2.5:201: error: 'senderNnumber' was not declared in this scope GuardDog\_v2.5:204: error: ISO C++ forbids comparison between pointer and \>integer \[-fpermissive\] 'senderNnumber' was not declared in this scope
>
> This report would have more information with "Show verbose output during compilation" enabled in File \> Preferences.

I have checked the receiving sms example and have written the sketch according to the example.I need help regarding this error and how to fix it

# Answer
> 2 votes
You misspelled the variable `senderNumber`. Correct it. Also you aren't reading the SMS properly or comparing the phone numbers properly. Your code should be like this (using the examples):

```
#define MAX_MSG 50

char senderNumber[20];
char sms_buf[MAX_MSG];   // a buffer for your sms, max len = 50

if (sms.available()) {    // this part should be in loop()
  sms.remoteNumber(senderNumber, 20);
  if (strcmp(senderNumber, "09432167015") == 0) { // compare numbers
    while (sms.available() == 0);   // wait for a char
    char i = 0;
    while (i < MAX_MSG - 1){    // till max len is reached; 1 byte for null
      c = sms.read();
      if (c == '\0')  // assuming the modem terminates sms with null
        break;
      sms_buf[i++] = c;   // write char to the buffer
      while (sms.available() == 0);   //wait for a char
    }
    sms_buf[i] = 0;   // terminate the string, just in case
    if (strstr(sms_buf, "yes") != NULL)  // look for 'yes' in buffer
      alarm_police();
  }
}

```

---
Tags: gsm, sketch
---


# Question
Title: Creating a library for attiny85 out of working program
Apologies if this is the wrong sub-forum, the involvement of ATTiny and arduino places this into a strange category. Please correct me if I should post elsewhere.

It is important for this to be a library as small kids will be using this program and hardware for their own projects. Its kind of a rip on the LOLshield but it involves a lot more steps to integrate more lessons all at once.

My whole program takes 8 bytes of information and converts it to data for a shift register driving two multiplexers all driving an 8x8 LED matrix. It can also use multiple of these packets to make a slide show. I have it in a working state right now and would like to turn it into a library for easy use. I am a bit lost in this step as I had to create an interrupt timer and this makes it more complicated than the tutorial on the arduino website covers.

Also if someone could point me to a library for ATTiny85 that makes calling a timer interrupt easy then the rest of this project will likewise become easier.

Any help would be great! I will be continuing to look on online resources and will update should I figure it out.

# Answer
> I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc.

---

## Code

In the interests of answering the question though, this works:

```
// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }

void setup()
 {
  pinMode (4, OUTPUT);  // chip pin 3

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare

  }  // end of setup

void loop()
  {
  // other code here
  }

```

---

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.

---

## Prescaler values

From the datasheet:

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.

The delay is then:

```
125 ns * 256 * 124 = 3.968 ms

```

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

---

## Flashing more slowly

If you put an LED on pin 3 and want to **see** the flashing, you need it much slower. For example:

```
TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13);  // prescaler: 16384

```

That toggles the pin every 254 ms, which is visible.

---

## Warning

On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.

---

## More information
> 3 votes

---
Tags: library, attiny
---


# Question
Title: Arduino as voltage monitor shorts to ground
I need to monitor voltages of several DC circuits in a generator's contact box. Whenever the generator has an alarm, a LED is lit in the box and voltage on the line drops to zero. I successfully get readings using analogRead(), but whenever I connect a line it shorts to ground (which is shared between the contact box and the Arduino) and triggers the contact box's alarm. I need to devise a way to monitor voltages without triggering the alarm.

Each 5V line and ground from the generator has a bus bar termination point that connects to a point in the proprietary alarm box that houses the LEDs and buzzer. I connected Arduino ground to generator ground, then used A0-A7 on a Nano to connect to individual lines on the bus bar. Arduino VCC is connected to 5V regulated DC power.

# Answer
A voltmeter does not have a ground reference. An Arduino plugged into the USB port would have one. Conceivably a battery-powered Arduino might work, however a safer solution would be to use an opto-isolator to isolate the voltage being tested from the Arduino. Something like this:

In this case you connect the "data pin" to the thing you are sensing. If it is at 5V then the LED will conduct (taking around 7 mA) and the transistor in the isolator will drive the Arduino pin `LOW`. If the data pin goes to zero volts, the transistor will not conduct, and the 1k resistor will pull the Arduino pin `HIGH`. Thus you can detect if the pin has changed voltage.

The 560 ohm resistor is a current-limiting resistor for the LED in the isolator. A 1k resistor would probably also work, reducing the current draw on the data pin to around 3.8 mA.
> 2 votes

---
Tags: analogread, voltage-level, electricity
---


# Question
Title: Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns
Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:

```
int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

```

The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).

Example:

```
[off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off]
[blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off]
etc etc...

```

Would anyone happen to have code already like this?

Any help would be great! Thanks!

# Answer
To make randomly-changing colours for the whole strip, change:

```
void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

```

to:

```
void loop() {
  rgbFadeInAndOut(random (256),
                  random (256),
                  random (256), ledFadeTime); // random colour
}

```

---

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:

```
#include <Adafruit_NeoPixel.h>

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(ledFadeTime);
}

void rgbFadeInAndOut(uint8_t wait) {

  uint8_t red [totalLEDs];
  uint8_t green [totalLEDs];
  uint8_t blue [totalLEDs];

  // randomly set each colour
  for (int i = 0; i < totalLEDs; i++)
    {
    red [i] = random(256);
    green [i] = random(256);
    blue [i] = random(256);
    }

  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }

     strip.show();
     delay(wait);
  }

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }
     strip.show();
     delay(wait);
  }
}

```
> 2 votes

---
Tags: arduino-uno, c++, led, arduino-ide, adafruit
---


title: Detect external ground on an input pin

text:
# Question
Title: Detect external ground on an input pin
I am making a bike alarm for my bike. I haven't started yet. Basically, I'm thinking of a pin to be connected to the metal post (to which the bike is locked.) I want to detect if that connection (to the ground via the metal post) is broken. Is that possible?

# Answer
> 1 votes
How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.

---
Tags: programming, pins, arduino-micro
---


title: Arduino Uno Wire Transmission Issues

text:
# Question
Title: Arduino Uno Wire Transmission Issues
I am developing code to run a word clock and have noticed a slight problem. I am using a DS3231 to keep time, and using the `Wire` library to communicate with it. I ping the DS3231 every second to get the time and check a few other things. This is all working fine except when the clock loses power. It seems that occasionally upon loss of power to the Arduino, the time that that the DS3231 reports when it regains power, is incorrect.

My thought is that the power is getting cut in the middle of various `Wire.read()` commands and this is causing the chip to mess up and reset its own time, but I am not sure. The DS3231 has a battery backup attached to it, and that battery has only been plugged in for a month or two, so I don't imagine that is the problem.

I am wondering if anyone has an idea how I can deal with this potential problem, or if there is some way I can clear the `Wire` library before it starts up again.

I have put some sample code below to give an idea of what I am doing. There is of course much more code, but this is the only relevant part.

```
#include "Wire.h"
#define kClockAddress 0x68

void readDS3231time(byte * second, byte * minute, byte * hour, byte * dayOfWeek, byte * dayOfMonth, byte * month, byte * year) {
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(kClockAddress, 7); // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { // sets time and date data to DS3231
  Wire.beginTransmission(kClockAddress);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

void setup() {
  // put your setup code here, to run once:
  Wire.begin()
   // DS3231 seconds, minutes, hours, day, date, month, year
   //setDS3231time(0, 36, 10, 2, 21, 12, 15);
}

void loop() {
  // put your main code here, to run repeatedly:
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  delay(1000);
}

```

# Answer
```
  Wire.requestFrom(kClockAddress, 7); // request seven bytes of data

```

Just because you request 7 bytes doesn't necessarily mean you get them. I suggest before reading the date and time you set all those variables to something invalid (like 0xFF). Then after reading, if you get 0xFF in any of them, ignore the entire lot.

---

> we are sending a start bit again, when we never sent a stop bit previosuly. ... Does this sound reasonable

Not really, because I2C doesn't have start and stop bits, it has *start condition* and *stop condition* which are specific changes to SDA and SCL which don't happen at any other times. See I2C for a description. I would be checking the data for validity, as I said. There is no other way of knowing for sure that a transmission wasn't interrupted. If you request 7 bytes of data, the library tells you that you got 7, even if you did not. However if it cannot even find the target device, it returns 0 as the number of bytes (you aren't testing for that anyway).

The very least you should do is test for a valid connection, eg.

```
if (Wire.requestFrom(kClockAddress, 7) == 7)
  {
  // read the data
  }

```

That at least confirms that the clock chip responded in some way. Not checking error returns from function calls, where documented, is not wise.

Similarly when you send your command.

```
  Wire.endTransmission();

```

That should be:

```
if (Wire.endTransmission() != 0)
  {
  // handle error here
  return;
  }

```

You have no tests in your code for either the sending or receiving to be working. And then you are unconditionally using the resulting time values. That's like opening a file, and reading it, without checking if the file exists.
> 1 votes

---
Tags: arduino-uno, c++, power, time, wire-library
---


title: Unstable reading from Raspberry Pi

text:
# Question
Title: Unstable reading from Raspberry Pi
I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal. I'm using Arduino Mega 2560 and Raspberry Pi 2B.

I hope this info is enough!

# Answer
> 2 votes
As Majenko commented, you need to not only connect the data wires together but also the ground wire (from the Arduino to the Pi).

> ... the reading are very unstable ...

Without a consistent "ground reference" the readings would indeed be unstable.

---
Tags: arduino-mega
---


# Question
Title: What's the difference between pow and sqrt in this code?
I'm not the best at Arduino so I'm sorry for my "noobiness".

I'm extending some code that I found online to work on the gyroscope that I'm building.

I'm wondering what the difference is between `pow` and `sqrt` in this code.

I'm also wondering what the `180/pi` is used for. I haven't gotten my mind around this part yet.

```
arx = (180/3.141592) * atan(ax / pow((ay, 2) + pow(az, 2));

```

What's the difference here?

```
ary = (180/3.141592) * atan(ay / sqrt(square(ax, 2) + square(az, 2)));

```

# Answer
Converting Gerben's comment into an answer:

---

pow(x, 2) is the second power, in other words:

---

sqrt(x) is the square root of x, that is:

---

A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of `180 / 3.141592` is used to convert an angle in radians to an angle in degrees.
> 1 votes

---
Tags: mpu6050, gyroscope
---


title: Arduino Mega connect to 2.1 speakers

text:
# Question
Title: Arduino Mega connect to 2.1 speakers
I am new to Arduino and I want to connect it to my 2.1 speakers and later to a 5.1 surround system.

The purpose is to play some wav sounds when a button is clicked or when a trip laser is cut. What should I do in order to play those wav around through the speakers? I also have an SD shield.

# Answer
First, you need to figure out the bandwidth requirements and if this is possible at all. You need to do some basic calculations and answer the question if the Arduino and the different components have the bandwidth (byte/second) that is required.

The Arduino MCU (AVR) is too "weak" to do this on it's own. A special shield is required. Such as https://www.adafruit.com/products/1788

The Arduino Due has more processing power but still not stereo quality; https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

More info to be googled.

Cheers!
> 1 votes

---
Tags: arduino-mega
---


title: It seems my Arduino doesn't work

text:
# Question
Title: It seems my Arduino doesn't work
I've got an Arduino Uno.

I was building a simple circuit with only one switch and it doesn't seem to work (I followed the Arduino project book from the Arduino starter kit).

This is my circuit :

Then I try again to move the switch and then it works (but I don't understand why).

So I tried to understand where the error is and I try to read digital input from the simple circuit with only one LED :

And this is my code :

```
int SWITCH = 13;

void setup() {
    Serial.begin(9600);
    pinMode(SWITCH, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
    int val;
    val = digitalRead(SWITCH);
    if(val == HIGH) {
        Serial.println("OKAY");
    }
}

```

I expect to see on the Serial Monitor "OKAY OKAY" and so on... but nothing appears on the Serial monitor.

Then I try to change the condition :

```
if(val == LOW)

```

And now I see "OKAY OKAY" and so on...

I think that there is something wrong with this Arduino... Can someone tell me something about what is happening? Am I stupid or there is really something wrong with this?

# Answer
> 2 votes
It looks to me like your arduino is working just fine.

In the first two images you use the arduino only to provide 5v power to the circuit on the breadboard. In the first image you haven't connected your button to properly function as a button. I don't know the exact pin layout of the button (which should be explained in a datasheet of that button), but it is also good to know exactly how to holes in a breadboard are connected. This picture shows why your button works on your second image but not your first:

This picture also shows how the breadboard holes are connected:

In your third image you have practically connected input pin 13 to GND, so it makes sense that digitalRead(13) in your code always returns LOW. Thus, the variable var is always LOW (or 0). Thus, the comparison (var == HIGH) is FALSE, which won't send "OKAY" to the serial monitor. And, the comparison (var == LOW) is TRUE, which will\* send "OKAY" to the serial monitor.

I hope you can follow the logical steps and it is clear to you what is happening.

---
Tags: arduino-uno
---


# Question
Title: Use large variables without using much memory
I've wired up a dot matrix, and I display characters on the screen by using something like the example code below.

The `Char_B` variable is a global variable in a library used by the Arduino, and `displayPixels()` is called from inside the library.

```
bool Char_B[8][8] = {
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0}
};

displayPixels(1000, Char_B);

```

However, each time I declare a new character like the array above, I use a relatively massive amount of memory. Is there any way to reduce memory usage? Keep in mind I am willing to change the structure of the array if necessary, since I'll need well over 100 characters loaded onto the Arduino to write text.

# Answer
The data structure will take 64 bytes as sizeof bool is 1 byte not a bit. The first option is to pack each line (or column) in a byte (or bytes). The prefix 0b is for binary constant value (in gcc).

```
uint8_t Char_B[8] = {
0b01111000,
...
0b01111000
};

```

The second option is to move the data structure to program memory.

```
const uint8_t Char_B[8] PROGMEM = { ... };

```

This will require reading each line with a special function.

```
for (int line = 0; line < sizeof(Char_B); line++) {
  uint8_t pixels = (uint8_t) pgm_read_byte(Char_B + line);
  ...
}

```
> 4 votes

# Answer
Use a single byte to store a row of data. As a bool still takes a single byte.

Optionally you could flip the axis, and store column data, instead of row data in the array. Since letters like `i` use fewer columns that letters like `B`. Even in your example you can see you have 3 columns with only `0`s.

A final suggestion would be to use `PROGMEM` and use the `pgm_read_byte_near` function. That way the data will remain in the flash memory, and will not take any space in the program-memory.
> 2 votes

---
Tags: c++, variables, memory-usage
---


# Question
Title: Is SoftwareSerial left out for the ATTiny85/84?
I want to use SoftwareSerial with my ATTiny85 and when I google it several projects claim that they are using it... I downloaded the hardware from https://code.google.com/p/arduino-tiny/, but when I try to add SoftwareSerial and compile I get:

```
fatal error: SoftwareSerial.h: No such file or directory

```

Switching the board to UNO makes the problem go away, so did they leave it out? How can I fix this?

# Answer
Short answer - no. It's not left out, on the contrary.

But before addressing to the compiler error you mentioned, a small clarification:

> I downloaded the hardware from https://code.google.com/p/arduino-tiny/

The link you provided is not *hardware*, but *software* called the **ATtiny core files**. It contains the necessary files that will help you compile and upload code from Arduino IDE to the ATtiny (even when using ArduinoISP as programmer).

The **SoftwareSerial** is a library that comes with the Arduino IDE zip/installation. If you have downloaded the latest version of Arduino IDE from the Arduino Website, you should be able to find the SoftwareSerial library files located at:

```
[Path to Arduino installation folder]\libraries\SoftwareSerial

```

Example for SoftwareSerial library files you should expect to find there are **SoftwareSerial.cpp** and **SoftwareSerial.h**.

> fatal error: SoftwareSerial.h: No such file or directory

The compiler error you receive seems to imply that the compiler cannot find the header file (SoftwareSerial.h) for SoftwareSerial library. This indeed seems quite odd, since this library does not require any special installation, and as mentioned, is part of the libraries that are built into the Arduino IDE installation.

So, to mitigate this, I would recommend that you will:

* Make sure the library folder exists in the location mentioned above
* If it doesn't, then you should probably re-download the Arduino IDE installation, and after that install the ATtiny core files as per the instructions (important!). Installation instructions are located in the **README** file inside the ATTiny core zip file (tiny\avr\README).
* If it does exist, and you still get this compiler error, then you must have a corrupted installation (perhaps the compiler include folders is messed up). I would still recommend following the re-installation as mentioned in the previous bullet.
* Make sure that you can find the **ATtiny 85** in the board list, at Tools-\>Board and that it is selected.
* Another angle that might shed more light on this error, would be to turn on the verbose output for the compiler (you can do it in the Arduino IDE, by choosing File-\>Preferences-\> "Show verbose output during" and checking "compilation"). Verbose output can help you track down any compiler command line errors, like missing include folders.
* Last but not least, if the SoftwareSerial folder exist, you could use the Arduino IDE to check if the IDE can identify its existance, by going to Sketch-\>Import Library, and looking for *SoftwareSerial*. If it's not there, then the folder is not located properly under the 'libraries', verify the path as mentioned above (did you move it?)

Finally, when you will be able to compile your code, try using the SoftwareSerial example that comes with the library to check it. Note that it is not going to work 'out-of-the-box' as with the Arduino Uno; The ATtiny does not have the same FTDI hardware for communicating directly with USB, so for sending and receiving serial messages using the ATtiny you will have to either use the Arduino Uno as a proxy (using the Uno's pins 0 & 1) or to use dedicated USB to Serial hardware similar to this one.

> Switching the board to UNO makes the problem go away

As a side note, switching to the Uno will make most ATtiny problems 'go away' since the Uno is much more equipped than ATtiny85/4, both on the MCU level and on the breakout board level, which you get with the Uno (and which you don't get when working directly with a chip like ATtiny). Also, most of the code base out there is targeting the Uno and not ATTiny. So if you are doing your first steps with the ATtiny, be prepared that many things that 'just worked' with the Uno will require extra/different code before they could work with the ATtiny (and some won't work at all).

You can use my simple Analog to Serial code :

```
/*
Takes an input on the AtTiny85 from the VERY TRICKY analogue input pin 2 (as labeled in HLT tutorial)
 and outputs these with Software serial to the arduino uno, or Duemillanove
 Hookup
 ATTINY85 pin 3 -> Arduino Uno pin 0
 ATTINY85 pin 4 -> Arduino Uno pin 1

http://www.instructables.com/id/Easy-ATTiny-Serial-Communication-with-Tiny-AVR-Pro/
 */

#include <SoftwareSerial.h>
// Definitions
#define rxPin 4
#define txPin 3
SoftwareSerial mySerial(rxPin, txPin);
int sensorPin = 7; //ACTUALLY PIN LABELED AS "2" on the HLT tutorial
int sensorVal = -1;

// the setup routine runs once when you press reset:
void setup() {
  pinMode(sensorPin, INPUT);
  mySerial.begin(9600);
analogWrite(0,1); // This is kind a heart beat to show the ATTINY is "alive"
}

// the loop routine runs over and over asensorpingain forever:
void loop() {
  sensorVal = analogRead(sensorPin);
  mySerial.print("Input Val: ");
  mySerial.print(sensorVal);
  mySerial.println();
}

```
> 6 votes

# Answer
Below you can find the code for a minimal bit-bang send serial implementation ideally suited for debugging. Code size is about 60 bytes.

It gives 38400 baud for 1 MHz or 230400 baud on 8 MHz Attiny clock.

I wrote it for an Attiny 85.

ArminJo/AttinySendSerial\_1Mhz\_38400Bd
> 3 votes

# Answer
Yes, in IDE 1.6.x, libraries are defined "per board", they reside in special folders and are provided by the atuhor of the board-bundle. Digispark's library is named SoftSerial and is included. In IDE Check File/Examples/DigisparkSoftSerial. Also check https://digistump.com/wiki/digispark/tutorials/debugging

In short, you have to include:

```
   #include <SoftSerial.h>
   #include <TinyPinChange.h>

```

and then define RX and TX pins (could be also the same in special cases):

```
   SoftSerial mySerial(SOFT_RX_PIN, SOFT_TX_PIN); // RX, TX

```

Then use `mySerial.println()` & co.
> 1 votes

# Answer
I had the same problem and it appears that with Arduino IDE 1.6.x, libraries are defined "per board" and not shared any more. At least, not all libraries are shared, and SoftwareSerial appears to be one of those.

So the solution is to copy the SoftwareSerial library from the Arduino installation at `[programs]/Arduino/hardware/arduino/avr/libraries/SoftwareSerial` to your ATTiny hardware folder at `[documents]/Arduino/hardware/tiny/avr/libraries/SoftwareSerial`, and restart the IDE, as per \[this thread\].
> 0 votes

---
Tags: serial, attiny, softwareserial
---


# Question
Title: Generating digital positive (+5 V) and negative (-5 V) signal?
Problem in getting -5 V with Arduino.

```
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(20);
  digitalWrite(13, LOW);
  delay(20);
}

```

Above code is generating below digital signal:

I want this type of digital signal output:

I read this for generating negative -5 V signal:

https://electronics.stackexchange.com/questions/10322/what-is-negative-voltage

but not able to understand very well WRT Arduino.

Also read this:

Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?

seems to much complicated circuit diagram with TL802.

**My questions:**

1. How do I get above digital signal?
2. I was wondering if we can use some 1 microF capacitor or transistor to generate negative signal? (simplest way)

# Answer
> 4 votes
It is not so easy to create a -5v power supply using a capacitor or transistor.

A very easy way is to use an additional Wall wart power supply to create -5 volts (while still using your original +5 volt power supply).

For the additional (new -5 volts power supply), use the two wires (positive and negative to create your -5 volts). The positive lead goes to your board ground, and the negative lead becomes your -5 volts.

EDIT 1 : Make certain that the Wall wart that you use is isolated from the mains voltage (line voltage you plug it into). Most Wall warts are isolated, but check to be sure.

Then you need level translation, which can be done with an op-amp and a couple of resistors :

You have not mentioned what frequency (data rate) you need. This circuit is not fast, so for high frequency or high data rates, the circuit could be improved.

---
Tags: arduino-uno, voltage-level, electronics
---


# Question
Title: Synchronization and Implementing hamming code on Software Serial
I want to learn and use Hamming Code. Would it be wise to alter the Software serial library to do this or just change the data being transmitted in the actual Arduino sketch?

Also, for means of better synchronization, what would be the best method with regards to these tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here?

**EDIT**

For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem?

# Answer
> 2 votes
Could look something like this:

```
class HammingStream : public Stream {
public:
  HammingStream(Stream& ios) : m_ios(ios) {}
  virtual size_t write(uint8_t byte);
  virtual int read();
  virtual int available();
  virtual void flush();
protected:
  Stream& m_ios;
  uint8_t encode4(uint8_t nibble);
  uint8_t decode8(uint8_t code);
};

size_t HammingStream::write(uint8_t byte)
{
   m_ios.write(encode4(byte >> 4));
   m_ios.write(encode4(byte & 0xf));
   return (1);
}

int HammingStream::read()
{
  if (available() == 0) return (-1);
  uint8_t nibble = decode8(m_ios.read());
  return ((nibble << 4) | decode8(m_ios.read());
}

int HammingStream::available()
{
  return (m_ios.available() / 2);
}

void HammingStream::flush()
{
  m_ios.flush();
}

```

Then you could:

```
HammingStream HammingSerial(SoftwareSerial);
HammingSerial.println(F("hello world"));

```

The above leaves out the encoding/decoding but also error detection. Hamming decoding can capture up to two bit errors and do one bit correction (on 4-bit data).

An example of implementation of the coder may be found in Cosa. Here Hamming(8, 4) is used to improve VirtualWire performance. Please note that the coder table is adjusted for RF and avoiding DC signal (i.e. long periods of zero or one).

Cheers!

# Answer
> 2 votes
You can use this info and code: Hamming(8,4) with Arduino.

There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.

You can use any class that derives from Stream (like Serial or SoftwareSerial).

**Edit:** If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:

Tx:

```
#include <hamming.h>

Hamming hamming(&Serial);
char message[] = "Hello World!!";

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

void loop()
{
  hamming.write(message);
  delay(1000);
}

```

Rx:

```
#include <hamming.h>

Hamming hamming(&Serial);
char message[Hamming::SIZE];

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

void loop()
{
  if(hamming.isMessageReady())
  {
    hamming.read(message);
    Serial.println(message);
  }
}

```

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".

P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.

# Answer
> 1 votes
The SoftwareSerial can only transmit and receive EIA-232 formatted packets. That is what it is written to do, and that is what it does.

It cannot transfer any other format.

If you want to use other encoding techniques you will have to use a different method than SoftwareSerial.

That might involve writing your own bit-banging routines in your sketch or in your own library, or using SoftwareSerial as a basis to adapt into your own library.

Note that the SoftwareSerial library is written in such a way that EIA-232 packets are a requirement - the falling edge of the start bit triggers reception of one packet - any other encoding that doesn't have that kind of start bit arrangement would require some completely different method of arranging the reception.

---
Tags: arduino-uno, communication, softwareserial
---


# Question
Title: Switching LED on and off using microcontroller
I am new to microcontrollers and just become confused trying to solve the following problem:

An ATmega32 chip is connected to four on/off switches (SW0-SW3) and 4 LEDs (LED0-LED3). SWi is connected to PAi. LEDi is connected to PA(4+i).

How will I code in such a way that turning a switch on, turns the corresponding LED on? For example, turning SW1 on will turn LED1 on. **I am confused in the part that after taking input what will I send to port A**? Multiple switches can be switched on at the same time.

**For clarification:**

```
switch0 is connected to PA0
switch1 is connected to PA1
switch2 is connected to PA2
switch3 is connected to PA3

LED0 is connected to PA4
LED1 is connected to PA5
LED2 is connected to PA6
LED3 is connected to PA7

```

# Answer
> 1 votes
A common approach is, to read the input pin, check the read value and then write to the output pin. As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.

So in your arduino sketch you could write:

```
loop()
{
  uint8_t pin1=digitalRead(PA0);
  if (pin1==HIGH)
  {
     digitalWrite(PA4, HIGH);
  }
  uint8_t pin2=digitalRead(PA1);
  if (pin2==HIGH)
  {
     digitalWrite(PA5, HIGH);
  }
  // and so on
}

```

I assume you have already done the prerequisites in your setup() routine.

---
Tags: atmega328, avr
---


# Question
Title: AVR - How to know that there is collision between stack and heap or the memory has filled?
I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

# Answer
> 4 votes
> I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (\__malloc\_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.

If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.

Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.

# Answer
> 2 votes
In simple terms: if the stack and heap have collided then the program will most likely crash, and any countermeasures you may have in place are now null and void.

However, you can find out the current amount of free memory quite easily by looking at where the top of the heap is and creating a local variable on the stack and getting its address - subtract one from the other and you get the free memory size.

That's exactly what the MemoryFree Library does for you.

---
Tags: avr
---


title: Use MOSFET to Change Voltage With PWM

text:
# Question
Title: Use MOSFET to Change Voltage With PWM
Ok so forgive me for being an amateur but I'm having a situation that's driving me nuts.

I have a sensor that I have to cycle between +5VDC and +1.4VDC every 60 seconds. I'm using an ATTiny85 with the 8Mhz internal clock fuse set.

What I was hoping was to use a 2N7000 N-Channel MOSFET to control the cycling of the voltage. So my thought is to have +5VDC on the Drain and a PWM signal on the Gate with the + side of the sensor connected to the Source. I am thinking that using PWM and adjusting the duty cycle on the Gate will allow me to adjust the voltage that is seen at the Source but what I'm seeing is a variation of +1.4VDC @28% duty cycle and +3.6VDC at 100% duty cycle.

I can't figure out why +3.6VDC is the best I can do. The PWM is coming from PB1 on the ATTiny85 and the +5VDC is coming from the main voltage source that also feeds the ATTiny85. The current draw of the sensor is 140mA max.

Ok so I haven't had any luck using a BJT or a single component to perform this voltage change so I started on a different approach using two 1N7000, with one being in an inverter configuration. My though is the pin from the MCU will go high, which will turn on both FET's, with one supplying 5V and the other sinking to ground. When the MCU pin goes low, both FET's turn off, which stops the 5V flow and the sink to ground, which then will allow the path through a voltage divider into my sensor at 1.4V. The issue I am having is the second FET is smoking, and by that I mean the sucker heats up like crazy and one even let the smoke out! I cannot for the life of me figure out WTF I am missing in this configuration. Here is the new schematic and Q1 is the FET that is smokin.

# Answer
> 1 votes
Using a N-type transistor as a high-side switch is inefficient unless you have some way of driving the gate above the positive rail. The most you can reasonably expect at the source is the gate voltage minus the gate threshold voltage, VGS(th). The typical threshold voltage of the 2N7000 as given in the datasheet is 2.1V, which means that it is a bit remarkable that you are able to get a voltage as high as you have (5V - 2.1V = 2.9V).

The way to fix this is to switch to a P-type transistor (and flip it around) since its threshold voltage is negative.

---
Tags: sensors, transistor, mosfet
---


title: Reprogram CH341A chips VID PID etc

text:
# Question
Title: Reprogram CH341A chips VID PID etc
I know it's possible (in theory) to reprogram the VID PID details back into a chip. It is however way beyond me.

Recently I learned that Microsoft distributed a piece of malicious software as part of their Windows update service. This virus was written by the FTDI chip makers to brick any chips such as the CH341's found in many cheaper Arduinos et al.

The virus attacked my CH341A serial to USB chip by writing 0's to the VID PIC and probably other locations. This makes the hardware 'Unknown' and even if you have the correct driver software, the device is never associated with it.

Does anyone know a solution to get the zeroed information back into the CH341A?

# Answer
Here's the guide I used to correct the problem :-

## HOW TO FIX THE USB-FTDI PROBLEM

(on arduino nano, usb ttl, ft232, ...)

There must have been a production of faulty ftdi drivers (version 2.12.0.0 or later) on august 2014 that makes some arduino boards and other usb devices not readable from the computer. The problem is random, meaning that it is possible to program the arduino a couple of times and then it comes out the ftdi problem, at that point the board isn't accessible anymore.

Once you come up with this problem, upgrading/downgrading the drivers, the IDE or the bootloader is just a waste of time, as the ftdi driver installed leaves some wrong data. This guide followed step by step will completely fix the driver problem thus making your board working again.

### Step 1: check if you have a faulty ftdi chip driver

Not every ftdi chip has faulty drivers, so the first step is to check the chip's driver version. In order to check the version you need a software like usbview or usbdeview (both freeware and don't need any installation). Run the software and look for the "USB serial converter" device which is the one related to the ftdi driver, then read the vendor-id and the Product-id whose values should be 0x0403 for the vendor and 0x6001 for the product. The goal is to modify that 0x6001 value with 0x0000, and to do that we need some other software.

### Step 2: modify values

Unplug your arduino nano or usb device. In order to modify the driver values you need CDMUninstaller (no installation needed). Fill the vendor and product fields with the values found with usbview (0403 and 6001) and click 'add', finally click 'remove devices'.

### Step 3: download the 2.10.0.0 ftdi driver

Go to the ftdi website and download the 2.10.0.0 virtual driver choosing between 32 or 64 bit version, voiding the 'setup executable' file: just download the folder. After downloading the folder, we have to overwrite some files inside of it. Click FTDI.rar to download the files already modified, and place them inside the 2.10.0.0 folder overwriting the old ones.

### Step 4: connect your arduino board

connect your arduino board, and stop windows from looking for new drivers. Go to device manager and look for FT232 USB device, then right click on it, select Properties and click on update drivers. Manually select the place in which scan for the new drivers and choose the 2.10.0.0 driver folder with the modified files. Now windows will prompt you saying that it can't certificate the new drivers. Ignore the alert and proceed with the installation. Once installation has finished, windows should recognize the connected board as 'USB recuperacion'.

Close the window and go to device manager, and look for the COM ports device. The connected device is now showing up like USB recuperation by ElectroHobby.es

### Step 5: modify the chip eeprom

This is the last step and you need to restore the initial vendor and product values inside the ftdi chip eeprom. In order to do that you need to download and install Ftprog, click on the magnifing glass icon, select 'USB device descriptor' and again select 'custom pid'. Finally click on 'ftdi default'.

A new window shows up and you just need to check flag the device list and then click on 'program'.
> 2 votes

# Answer
What you call a “virus” is, more properly, malware. FTDI's driver that bricked fake FT232R chips was withdrawn from Windows Update in October of 2014. (See, for example, discussion at epanorama.net, sparkfun, and hackaday. The hackaday article, “Unbricking a counterfeit FTDI chip”, has links to an article about unbricking counterfeits.)

The CH341A is not a fake FT232; it is a cheaper alternative that requires a different driver. The driver is not automatically installed by Windows. Several web pages I've seen about it suggest downloading from Chinese-language web pages, which is a gamble if you don't understand what the page says. \[However, English-language driverscape.com seems to have a CH341A driver at the moment. I don't know if it works or whether it is free, and anyway have no Windows machine to test it on.\]
> 2 votes

---
Tags: serial, ftdi
---


# Question
Title: Should long wires be kept separated from each other, to reduce interference?
Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?

How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?

How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?

On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.

# Answer
A benefit of using CAT-5 is that the pairs are twisted. You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used. Telephone wire, however, can be a completely different story. You may find some that is twisted pair, but most if it is simply flat cable. Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it. This is very high loss and very vulnerable to RFI.
> 2 votes

# Answer
It depends on the frequency/frequencies you care about transmitting on your cables. One simple approach is to put on both ends a filter that lets pass only those frequencies you care about. You can also consider using some error detection/correction encoding or check if there is some existing library that suits your needs. This last approach will work if you do not get too many interferences and your application can tolerate that data is re-transmitted every now and then, making the communication timing not 100% deterministic.
> 1 votes

# Answer
CAT5 should work well with what you are trying to do, however stay away from power lines unless they are in a grounded conduit. The phone lines would most likely generate interference when the phone is ringing as there is a lot of voltage transients on the line at that time.

To get the full benefit of the twisted pairs send and receive your signals with differential transceivers, one transceiver per pair.

Personally I will not connect a microprocessor pin to the outside world without some type of buffering isolation etc. Those pins were not designed to drive long lines, although it may work eventually it will fail, that may be momentary to many years in the making but it will fail.

Lines connected directly to the microprocessor pins will all act as bidirectional antennas. They are not only are sustainable to interference they also generate it. Remember the wires are small inductors which can generate some huge voltages when the transition time is short.

I typically use Schmidt devices such as a 74C14, 74HC etc. as my input receivers for switches etc. I normally use an active low input signal, this help to keep noise out of the power supply. The input to the gate is pulled up to the 12VDC with a 10K resistor, this keeps a minimum of about 1 mA through the contact. The other end of the resistor is connected to a 100K resistor that in turn connects to the microprocessor input pin. You can add a cap to de-bounce at the gate if you want. The software is easier as it is looking for an active high which is a logic "1". This circuit has been replicated hundreds of thousands of times and is very stable and reliable.

What you are doing will work for dorm room, testing etc...
> 0 votes

---
Tags: wires
---