# Question
Title: Erroneous sensor reading while connecting extra load
I'm making a **speedometer using arduino**. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also **using the same battery to use a horn**. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an **erroneous reading.** The only common thing between the arduino and the horn is the battery supply.

# Answer
If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off. Or, if it's a buzzer, it may generate voltage spikes all during its operation. Voltage spikes or other electrical noise are the most likely cause of the problem.

It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.

To find out which is the problem, take voltage readings with and without the horn in operation. If you have an oscilloscope, look for spikes on system power.

Try isolating and/or buffering the Arduino's power. If power glitches are the problem, that should fix the problem. If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.

To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's. Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground. If necessary add ferrite beads around the power leads.

A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V. Put the large electrolytic across the +7V if you use a buck converter.
> 1 votes

---
Tags: arduino-uno, sensors, power, interrupt, battery
---


# Question
Title: Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?
I am planning to buy a low cost and low weight laptop with an Atom Processor.

I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?

# Answer
The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.

If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.

The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Migrating from ATMega2560 to ARM based -- Teensy vs Due?
I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.

Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.

I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.

So my QUESTION is: Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.

Any other considerations/suggestions/advice will be appreciated.

Thank you.

# Answer
> 1 votes
If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.

That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.

There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.

---
Tags: arduino-mega, arduino-due, library, teensy
---


title: Issue with simple project

text:
# Question
Title: Issue with simple project
I'm new to Arduino and today I have a problem with this code:

```
int led_1 = 10;
int led_2 = 11;
int led_3 = 12;
int button = 3;
int time = 0;
byte val = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(led_1, OUTPUT);
  pinMode(led_2, OUTPUT);
  pinMode(led_3, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(button);

  if (val == HIGH){
    time = millis();
    while (digitalRead(button) == HIGH) {
      if (millis() - time < 1000) {digitalWrite(led_1, HIGH);}
      else if (millis() -time > 1000 && millis()-time <2000) {digitalWrite(led_2, HIGH);}
      else if (millis()-time >2000) {digitalWrite(led_3, HIGH);}
    }
  } else {
    time =0;
    digitalWrite(led_1, LOW);
    digitalWrite(led_2, LOW);
    digitalWrite(led_3, LOW);
    }
}

```

The code should work like this: If I press the button less than one second, `led_1` will turn on. If I press it between one and two seconds, `led_2` will turn on; and if I press the button more than 2 seconds, `led_3` will turn on. If I don't press a button, the LEDs remain off. The `time` variable is used to take the time when I start to press the button and then the control `millis()- time` should give how long I press the button.

It works for a while, then after a random time (I think) if I push the button, only the `led_3` turns on. Why?

# Answer
`time` should be an `unsigned int`. As soon as `millis` reaches 32768, it will be stored as -32768 in `time`, and your comparisons will not work. This happens after 32.768 seconds. Here's a short sketch to illustrate:

```
int time = 0;

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

void loop() {
    time = millis();
    if (time % 1000 == 0) {
      Serial.println( time );
      delay( 2 ); // let millis() increment
    }
}

```

To see the difference, just change the first line to

```
unsigned int time = 0;

```

Note how `time` rolls over to 0 after 65535 (well, only 65000 is printed).

I would recommend using unsigned constants by adding a "U" after the digits: `1000U`. In your `if` statements, you must cast the `millis` to the same (smaller) type: `(unsigned int)millis()`. Also, parentheses make the expression more clear:

```
      else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}

```
> 2 votes

# Answer
Your code seems inefficient and there is a `tempo` variable that doesn't appear elsewhere.

```
  if (val == HIGH) {
    time = millis();
    while (digitalRead(button) == HIGH) {
      int time0=millis();
      if (time0 - time < 1000) {
        digitalWrite(led_1, HIGH);
      } else if (time0 - time < 2000) {
        digitalWrite(led_2, HIGH);
      } else if (time0 - time > 2000) {
        digitalWrite(led_3, HIGH);
      }
    }
  }

```

Note that this code will turn on all LEDs, one by one. If you want to turn off the other, you'll have to had code for that in the tests.
> 2 votes

---
Tags: arduino-uno, led, time, millis
---


title: Looking for help with WiFi modules

text:
# Question
Title: Looking for help with WiFi modules
I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me. Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.

I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.

Before anyone asks, yes, it is critical for it to work over wifi. Has anyone done something like this? What gets the best results?

# Answer
I cant comment so I'm going to post as an answer. Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it. As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.
> 1 votes

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


title: Arduino GSM Shield not responding?

text:
# Question
Title: Arduino GSM Shield not responding?
I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.

Would greatly appreciate it if someone can tell me where I could have gone wrong.

EDIT : I'm currently using the Arduino Mega. The shield I'm using is the Arduino GSM Shield. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see Sending a SMS message. Attached is what is shown on the monitor.

I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.

# Answer
This is an old post, but for future people:

The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.
> 1 votes

---
Tags: gsm
---


# Question
Title: How many LED Strips can we connect to an Arduino Uno? Is there a way to connect 1-3 meters worth without needing extra parts (relays)?
I am looking at Adafruit to purchase some LED strips for a mod for my computer case, and want to power it with an Arduino.

I am looking at the Uno, but the Mega looks good too. I hear the Uno is good because if the chip fries, you can just replace it easier than the Mega's chip. I did hear that the Uno chip had issues, but that was a 2013 post.

Anyways, I am essentially looking to connect about a foot of 144 leds/m to the front of my case, and connect that to the Arduino. I will then be lining the inside of my case with about 12-15" per side (x4 sides) of 60 leds/m so I wanted to connect that to another part of the Arduino.

I read that each led takes something like 6mA or 60mA each, so that is what we should watch for. I was trying to search for this question that others asked, but people were looking to connect a lot of strips, and needed relays and whatnot, so I wanted to make sure the Arduino itself could power about 1.5 to 2 meters of Led strips in at least 2 different strip configs (or whatever you want to call them).

I also am curious if there will be an issue programming each strip setup or, if it just is a little more work to get it setup?

Since this is a computer cause led setup, I'm not sure if I should go USB power, or a wall charger? What is the recommended approach for something like this?

I will definitely be reading up more tutorials and all that important stuff, but I want to buy the stuff now since I realized there's a cyber Monday deal going on, so I don't want to miss out...

Any help is appreciated, thank you!

# Answer
> 5 votes
Yes, the current draw is the main factor here. That's not really an Arduino issue though, as I will enlighten you about later on when I talk power supplies.

**I assume, since you don't mention what the LEDs are, that you are talking about strips of WS2812 "NeoPixel" LEDs (the ones where you can control the colour of each and every individual LED).**

I would recommend keeping all the LEDs as one single strip. That doesn't mean you can cut the strip into segments, just join the ends to each other using wire in one chain. That way you just have one chain to deal with in the Arduino. Running multiple chains can be somewhat more resource hungry and I'm not even sure it's possible on an Arduino. So keep it all as one long chain split into chunks and re-joined with wire.

Now for power. Your computer has a big powerful power supply in it. That gives a very good regulated 5V supply with many many amps available. More than enough to run hundreds of LEDs. By all means run the Arduino from USB (makes for easy programming - inspect your motherboard, it may well have an internal USB connector that would be ideal (I know mine has). And then run the LEDs themselves off the +5V direct from the computer's power supply. A spare hard drive power connector could be good for that.

# Answer
> 1 votes
The important thing to understand here is that there are two things going on:

1. Powering the LEDs – that's the big power draw and it makes a ton of sense to do that off of the computer power supply.
2. Controlling the LEDs – that'a a very small load, using one (NeoPixel et al.) or two (DotStar et al.) pins on the Arduino. So there is no need to do anything fancy, you should have more than enough drive in the Arduino pin(s) to handle the LED control.

You might want to take a look at the FastLED library (or head directly to the GitHub repo) it explicitly support multiple strands of LEDs (and interchangeably supports a whole slew of LED type including NeoPixels and DotStars. I think, but haven't tried, you could support multiple strands of NeoPixels by creating several instances and giving each instance its own pin.

DotStars come (if you get a "finished" end) with a connector that has all four wires (Vcc, Gnd, data, and clock) as well as two additional wires for "bulk" power. But if you don't get a finished end you would just solder to the pads that are at each cut point. You probably want to power the strip(s) in parallel – feeding them from each end so that the LEDs at the end don't see too much of a voltage drop.

# Answer
> 0 votes
The other answers you have here cover the points well, just to offer my $0.02.

# Using a wall adapter

It's really not necessary to use a separate wall adapter and you'd be adding another layer of complexity unnecessarily. So don't bother. Also with a wall adapter you would have to consider grounding it to the computer's power supply, not necessarily an issue, but not required if you use internal power.

# Powering your LEDs

your computers power supply is more than capable of handling EVERYTHING you've mentioned (unless you're already maxing it out, which I doubt).

Just make sure that you're powering the LEDs directly from the computer's power supply, and not from the (arduino) board itself, since that 5v is limited to 500mA from the USB connector, and definitely don't drive the main power from a data pin (I'm sure you know that—but just in case :P)

If you do split the strip (running two strips shouldn't be a problem) be sure to provide power where ever you can, ie each end, even in the middle. It will aid in providing even power throughout the strip.

# Powering the Arduino

I'd be running the Arduino off it as well, either grab a header cable off the board that has an end you could plug into your arduino and mount it inside, or feed a USB cable through the back and use one of the extra external USB ports. A bonus of running it outside would be you could physically reset the board by unplugging it :) or simply turning it off by doing the same.

---
Tags: arduino-uno, arduino-mega, led, adafruit
---


# Question
Title: Best way to implement score board logic using Arduino and Shift Registers?
I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.

**Score - 888 (3 Digits)** \- I have implemented this logic using shift registers. Three pin used from Arduino Uno and this is working fine.

**Overs - 88 (2 Digits)** \- Need to find a best way to implement it

**Wickets - 8 (1 Digit)** \- Need to find a best way to implement it

Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

1. One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.
2. The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers. There are only few pins.

***Please Note: I need to print this design in PCB***

This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

# Answer
> 2 votes
There isn't really a *best* way (and such questions are usually discouraged as they can easily descend into argument).

Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.

From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.

# Answer
> 0 votes
You could use a 16x2 LCD to display the information; then you wouldn't need so many separate lines from the Arduino, the PCB would be simple and compact, etc.

However, if you need a big high-power display that is not multiplexed, you could use one 74HC595 per digit, assigning one bit per segment with 7-segment LED displays, with a driver transistor on each output.

The six '595s would be in series, which would use only two output lines from the Arduino: clock and data.

Another approach is to build your display from 84 or 126 WS2811 or WS2812B LEDs (2 or 3 per segment, and 7 segments times 6 digits). About $10 to $15 on Ebay. This would use one data pin from the Arduino to drive the whole display and would supply bright RGB light.

---
Tags: arduino-uno, serial, shift-register
---


title: arduino SD card saving to file

text:
# Question
Title: arduino SD card saving to file
Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield

I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me

My code is;

```
#define redled 10
#define greenled 11
#define echoPin 12
#define trigPin 13

unsigned long interval=60000; //interval = 60 seconds
unsigned long previoustime=0;
int minutes = 0; //global variables

void setup() {
  Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);
}

void loop() {
 //-----------------------------------------------------------
  unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
  if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
    previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
    minutes = minutes + 1; //Add 1 minute
  }
  unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
  //-----------------------------------------------------------
  long distance = ultra_sensor(); //call function that now returns the distance
  //-----------------------------------------------------------
  if (distance < 4) {            // If distance is less than 4cm
    digitalWrite(redled,HIGH);   // Turn on Red LED
    digitalWrite(greenled,LOW);  // Turn off Green LED
  }
  else {                          //If distance is greater than 4cm
    digitalWrite(redled,LOW);     // Turn off Red LED
    digitalWrite(greenled,HIGH);  // Turn on Green LED
  }
  //-----------------------------------------------------------
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.print("cm");
    Serial.print(" after ");
    Serial.print(minutes);              //Printing distance and time to serial monitor
    Serial.print(" minutes ");
    Serial.print("and ");
    Serial.print(time);
    Serial.println(" seconds");
  }
  //-----------------------------------------------------------
  delay(2000); //Get reading every 2 seconds
}

long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
  digitalWrite(trigPin, LOW);  //Set Trigger to idle
  delayMicroseconds(2); //Wait 2 microseconds
  digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
  delayMicroseconds(10); //Send the wave for 10 microseconds
  digitalWrite(trigPin, LOW); //Turn the trigger to idle
  long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
  long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
  return dis; //Send the distance to function call
}

```

# Answer
> 1 votes
Looks like your sketch (pin usage) is in conflict with the SD shield (SPI pins). Try using other pins.

---
Tags: sd-card
---


# Question
Title: glediator + PL9823 (WS2812B) + teensy = fail?
here is what I got:

* teensy++ 2.0 with code below
* Glediator configured for Glediator\_Protocol/Single\_Pixels/HL\_TL/RGB/B\_1000000
* led matrix with the PL9823 leds (80 of them)

I first off have to set the code to 160 on the teensy just to get it to at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.

Code

```
#include "FastLED.h"
#define NUM_LEDS 160
const int dataline = PIN_B4;
CRGB leds[NUM_LEDS];

void setup()
{
    digitalWrite(6,LOW);
    Serial.begin(1000000);
    LEDS.addLeds<WS2812B, dataline>(leds, NUM_LEDS);
    for (int p=0;p< NUM_LEDS;p++)
    {
        leds[p] = CRGB::Black;
        FastLED.show();
    }
}

int serialReadBlocking()
{
    while (!Serial.available())
    {
    }
    return Serial.read();
}

void loop()
{
    while (serialReadBlocking() != 1)
    {
    }
    for (long i=0; i < NUM_LEDS; i++)
    {
        leds[i].r = serialReadBlocking();
        leds[i].g = serialReadBlocking();
        leds[i].b = serialReadBlocking();
    }
    FastLED.show();
}

```

https://www.youtube.com/watch?v=H6OuMWKtbmo

# Answer
G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with `FastLED.h` but is the `serialReadBlocking` how it deals with the input data? Not that it's wrong, just not what I was expecting.

Two things to look at:

1. Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.
2. I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td\_uart.html
> 1 votes

---
Tags: teensy
---


# Question
Title: Using ATtiny85, NRF24L01+, DHT2: can't get data from DHT22
I am trying to make a sensor that gets temperature and humidity values from a DHT22 and send it through NRF24L01+ to a Raspberry Pi 2 Model B.

To connect NRF24L01+ to ATtiny85 and to free two pins for the DHT22, I used this link.

There is a scheme of my sensor:

There is a photo of the test board with the sensor (sorry, it is very untidy, because I remade it many times before to fix the problem):

I program the ATtiny85 with Arduino IDE (with 8 MHz clock).

I used this library and radio communication is working perfectly (it can't be an error during the radio transmission).

Here is the code of my ATtiny85:

```
#include <DHT.h>
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
DHT dht;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
  dht.setup(3); // Set up the sensor on PB3 pin
}

void loop() {
  // This DHT library can calculate the delay but it may be 2+ sec
  delay(dht.getMinimumSamplingPeriod());
  // Get values from DHT22
  data.temp = dht.getTemperature();
  data.hum = dht.getHumidity();
  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

```

But I can't the get temperature and humidity values from the DHT22. I used a lot of different libraries for DHT22 (for example, *github.com/ringerc/Arduino-DHT22, github.com/nethoncho/Arduino-DHT22, github.com/jscrane/DHT22*, etc.) and none of them works (they return zeros, NAN, or, generally, timeout error). And it seems that the connection with the DHT22 is correct (there were connection errors and I fixed them). I tried to use a lot of DHT22 modules, so the problem can't be a defective module.

Yes, I put a 2 second (and more) delay in between read requests. Yes, I added a 10k resistor between pin 1 and 2 of the DHT22.

Now I am thinking that the libraries work fine, but may be free pins (PB3 or PB4) of ATtiny85 can't receive data for some reason.

Tell me please where may be an error or a bug? Thank you in advance! And also many thanks to authors of all links and repositories that I have mentioned here!

**EDIT (in accordance with frarugi87's answer):**

At first I have grounded 3 and 4 pins of the DHT22.

When I program ATtiny at the **1 MHz**, values are sent every 2 seconds (as it should be), but when I program ATtiny at **8 MHz**, values are sent every 16 seconds (is it correct?).

I used the suggested code to check the radio library and it seems it works pretty well (values are being incremented and sent):

After that I used the suggested library (RobTillaart/Arduino v. 0.1.21) and at first time it returned some strange values (humidity and the status were 0 and temperature was MAX\_INT value), but when I have tried to get only status value as string, the library also has returned -2 (DHTLIB\_ERROR\_TIMEOUT). This time I program ATTiny at 8 MHz:

Also I tried to get values without NRF24L01+ through I2C connection between the ATtiny85 and the Raspberry Pi. Result was the same (DHTLIB\_ERROR\_TIMEOUT):

Maybe the problem is in timings of ATtiny85 or in the program process? I used these links (, , ) to set up Arduino IDE on Raspbian.

**Here is list of useful links for this project which I found to implement it (I hope the authors will not mind that I posted their links here)**:

Arduino/AVR DHT projects and libraries:

Arduino/AVR nRF24L01 projects and libraries:

Programming the ATtiny85 from Raspberry-Pi:

Arduino/AVR FR433 libraries:

Troubleshooting:

# Answer
> 1 votes
Thanks to Rob Tillaart, the autor of the Arduino DHT library suggested by @frarugi87 (also thank him), the problem has been solved (see **this issue** for more information).

In my case **to fix the problem** there is only needed to to set a specific value of `DHTLIB_TIMEOUT` by leaving the definition `#define DHTLIB_TIMEOUT 1000` in the `dht.h` file of this library and commenting other definitions written next to it:

```
// #ifndef F_CPU
#define DHTLIB_TIMEOUT 1000 // should be approx. clock/40000
// #else
// #define DHTLIB_TIMEOUT (F_CPU/40000)
// #endif

```

The ATtiny is programmed on 8 MHz. The DHT22 is working at a voltage of 3.3V with a **3K3** resistor.

The cause of the problem may be the way I program the ATtiny85 with old version of Arduino IDE installed in the Raspberry Pi (see comments to the @frarugi87's answer).

Libraries used:

Here is the final code of the ATtiny85 transmitter and the Raspberry Pi reseiver respectively (**I took the most part of the code from different examples of RF24 libraries and DHT libraries! Excuse me, if the code is not tidy.**).

**NRF24Transmitter.ino:**

```
#include <dht.h>
#include <RF24.h>

#define DHT22_PIN 3
#define LONG_DELAY_MS 900000

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  float temp;  // Temperature value
  float hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
dht DHT;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
}

void loop() {

  unsigned long startMillis = millis();
  while (millis() - startMillis < LONG_DELAY_MS);

  do {
    data.status = DHT.read22(DHT22_PIN);
    data.temp = DHT.temperature;
    data.hum = DHT.humidity;

    if (data.status != DHTLIB_OK) {
      delay(1000);
    }

  } while(data.status != DHTLIB_OK);

  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

```

**Receiver.cpp:**

```
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

uint8_t addresses[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node"};

// Struct for sending measured data
struct Data
{
    float temp;  // Temperature value
    float hum;   // Humidity value
    int status;     // DHT22 module status
} data;

RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

int main(int argc, char** argv)
{
    uint8_t currentPipe = 1;
    data.temp = -888;
    data.hum = -888;

    printf("BEGIN: %d\n", (int)radio.begin());

    radio.setAutoAck(1);
    radio.setRetries(15,15);
//  radio.setDataRate(RF24_1MBPS);
//  radio.setPALevel(RF24_PA_MAX);
//  radio.setCRCLength(RF24_CRC_16);

    radio.openReadingPipe(1, addresses[0]);
    radio.openReadingPipe(2, addresses[1]);
    radio.openReadingPipe(3, addresses[2]);
    radio.openReadingPipe(4, addresses[3]);
    radio.openReadingPipe(5, addresses[4]);

    radio.startListening();

    radio.printDetails();

    sleep(1);

    cout << "Start!" << endl;

    while(true)
    {
        cout << "Waiting for data..." << endl;

        while (radio.available(&currentPipe))
        {
            cout << "Reading: " << addresses[currentPipe - 1] << "..." << endl;

            radio.read(&data, sizeof(Data));

            cout << "Temp: " << data.temp << endl;
            cout << "Hum: " << data.hum << endl;
            cout << "Status: " << data.status << endl;
        }

        sleep(1);
    }

    return 0;
}

```

**Here is Makefile to compile the receiver.cpp:**

```
#############################################################################
#
# Makefile for librf24 examples on Raspberry Pi
#
# License: GPL (General Public License)
# Author:  gnulnulf <arco@appeltaart.mine.nu>
# Date:    2013/02/07 (version 1.0)
#
# Description:
# ------------
# use make all and make install to install the examples
# You can change the install directory by editing the prefix line
#
prefix := /usr/local

# Detect the Raspberry Pi by the existence of the bcm_host.h file
BCMLOC=/opt/vc/include/bcm_host.h

ifneq ("$(wildcard $(BCMLOC))","")
# The recommended compiler flags for the Raspberry Pi
CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s
endif

# define all programs
#PROGRAMS = scanner pingtest gettingstarted
PROGRAMS = receiver #gettingstarted gettingstarted_call_response transfer pingpair_dyn test
SOURCES = ${PROGRAMS:=.cpp}

all: ${PROGRAMS}

${PROGRAMS}: ${SOURCES}
    g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@

clean:
    rm -rf $(PROGRAMS)

install: all
    receiver -d $(prefix) || mkdir $(prefix)
    receiver -d $(prefix)/bin || mkdir $(prefix)/bin
    for prog in $(PROGRAMS); do \
      install -m 0755 $$prog $(prefix)/bin; \
    done

.PHONY: install

```

# Answer
> 0 votes
Ok, let's troubleshoot it.

Try with the following sketch:

```
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
    data.temp = 0;
    data.hum = 1;
    data.status = 2;
}

void loop() {
    data.temp++;
    data.hum++;
    data.status++;
    radio.write(&data, sizeof(Data));
    delay(2000);
}

```

You should see a bunch of data being sent to the raspberry every second (you should see `temp = 1, hum = 2, status = 3` then, after two seconds, `temp = 2, hum = 3, status = 4` and so on. Of course you need something to display the data.

If there is some problems then it's the radio library fault, otherwise let's integrate the DHT22.

So, AFTER having tried the previous sketch and confirming that everything is working, download the library from here, install it and then use this sketch:

```
#include <RF24.h>
#include <dht.h>

dht DHT;

const byte DHT22_Pin = 3;

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
}

void loop() {
    data.status = DHT.read22(DHT22_Pin);
    data.temp = (int)DHT.humidity;
    data.hum = (int)DHT.temperature;

    radio.write(&data, sizeof(Data));

    delay(2000);
}

```

Now, instead of displaying increasing numbers, it should say the temperature, the humidity and, most important, the status:

```
 0 -> OK
-1 -> ERROR_CHECKSUM
-2 -> ERROR_TIMEOUT
-3 -> ERROR_CONNECT
-4 -> ERROR_ACK_L
-5 -> ERROR_ACK_H

```

Check if this works.

**IMPORTANT NOTE**: I read somewhere that sometimes the ground pin on the DHT is 3 instead of 4. Try grounding both pins if something does not work.

---
Tags: attiny, nrf24l01+, temperature-sensor
---


# Question
Title: Connecting and Programming LinkSprite Camera to Arduino
I recently bought the LinkSprite color jpeg camera: https://www.sparkfun.com/products/12804 And the Arduino Wireless SD Shield: https://www.arduino.cc/en/Main/ArduinoWirelessShield

I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.

# Answer
> 0 votes
Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on wiki.

Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc.

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


# Question
Title: Script stops functioning after calling irsend() function in irlibrary!
I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.

```
/*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

IRsend irsend;

decode_results results;

int intValue;
String strValue;
String str3;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    intValue = results.value;

    Serial.print("Integer value : ");
    Serial.println(intValue);

    strValue = String(intValue);
    Serial.print("String str : ");
    Serial.println(strValue);

    Serial.print("Length : ");
    Serial.print(strValue.length());
    Serial.println();

    if(strValue.length() <= 1){
      str3 += strValue;
      Serial.println(str3);
       // Receive the next value
   }

    delay(200);
    irrecv.resume();
  }
  //Serial.println(str3);
  if(str3.endsWith("770")){
    powerOff();
    str3 = "";
  }
  else if(str3.endsWith("769")){
    powerOff();
    str3 = "";
  }

  else{}
  //powerOff();
}

void powerOff(){
    irsend.sendRC6( 0xC0000C, 24);
    irrecv.resume(); // Receive the next value
}

```

# Answer
Apparently you should be calling `irrecv.enableIRIn()` after sending, not `irrecv.resume()`. Sorry for suggesting the wrong thing on IRC before :-)
> 3 votes

---
Tags: arduino-uno, serial, ir, remote-control
---


title: MG2639 & Arduino Uno not GPS-ing?

text:
# Question
Title: MG2639 & Arduino Uno not GPS-ing?
is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.

# Answer
Try sending a command that sets the GPS baud rate to something a little lower:

```
altss.write( F("$PMTK251,38400*27\r\n") );
altss.end();
altss.begin( 38400 ); // change to match above command

```

Are you sure you're having trouble *reading*, because there are many other things you may be doing in your sketch that cause input buffer *overflow*. Please post your code and some sample output for us to examine. It may be failing for a different reason.

For example, you may just be losing data because you're trying to do too many things in `loop()`. Please take a look here.

To solve this kind of problem, I have posted a modified version of `AltSoftSerial` on github, here, that let you process GPS data in the background (i.e., during interrupts). When coupled with NeoGPS, it can save you quite a bit of program space, RAM and execution time. There is an interrupt-driven example here. Just change which include is uncommented on lines 30-31:

```
#else
  // Only one serial port is available, uncomment one of the following:
  #include <NeoICSerial.h>
  //#include <NeoSWSerial.h>
#endif
#include "GPSport.h"

```

...and the baud rate below, on line 140:

```
  // Start the UART for the GPS device
  gps_port.attachInterrupt( GPSisr );
  gps_port.begin( 115200 );
}

```
> 1 votes

---
Tags: gps
---


title: minIMU 9 and Arduino reading Gyro angle

text:
# Question
Title: minIMU 9 and Arduino reading Gyro angle
I'm using minIMU-9 https://www.pololu.com/product/1268 and I want to read pitch, roll and yaw angles. I applied this library https://github.com/pololu/minimu-9-ahrs-arduino but there is a slope when sensor is not moving or vibrating. How can i fix or compensate this. The y axis is angle in degree and x axis is time in seconds

Pitch

Roll

Yaw

# Answer
> 1 votes
I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.

What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.

Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.

Below the L3GD20's mechanical characteristics

---
Tags: sensors
---


# Question
Title: Where can I get a high-quality ADC (audio digitizer) for Arduino?
Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?

Does anybody know where I can find the best options for this?

# Answer
> 2 votes
You are going to need a bigger board.

(96000000 samples/second) * (32 bits / sample) ~= 3 Gigabits/second

A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.

While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.

The highest quality audio recording shield for Arduino I've seen is a modified Wav Shield that can record 8-bit mono files at 44,100 samples per second using the waverp library.

# Answer
> 1 votes
think 96000kps was most likely a typo. 96ksps or 96000sps is more likely since the title specifies audio. Still a little too much for an Arduino though. You need a chip with I2S and a CODEC chip.

I am working on a project at the moment interfacing a PIC32 to a CODEC for CD quality audio reproduction. The codec I am using (PCM1774) is DAC only, but you can get CODECs in many combinations of ADC and DAC with different numbers of channels in each.

I2S is very similar to SPI but needs some extra facilities that not all chips can provide. Things like:

* High speed flexible base clock at (for example) 256x the sample frequency
* Left/Right framing clock derived from base clock
* DMA for smooth transfer of data

I don't know what offerings Atmel have, but for PIC32 you need one of the more modern chips, such as the PIC32MX1xx/2xx family, PIC32MX470, or for high end work the 200MHz PIC32MZ chips.

The MX1xx/2xx and MZ chips are available in a Arduino-like system called chipKIT which might suit your needs better than small Atmel chips.

The Arduino Due might also be able to do I2C but I won't be able to help you with that since I have relegated my Due to the bittom of my junk pile.

---
Tags: audio
---


# Question
Title: Supply arduino through Vin pin with a battery
1. is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?
2. is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?
3. in case i don't connect GND arduino pin with -12v , does arduino works?
4. in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?

# Answer
Voltages, being a *potential difference* are always measured relative to another voltage. Normally that reference voltage is referred to as *ground*, though may not always be.

The + and - on the battery refers to the *polarity of the battery* not the *polarity of the voltage*.

For instance, *relative to the - terminal* the positive terminal is 12 volts higher, or +12V. *Relative to the + terminal* the negative terminal is 12V lower, so -12V.

When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V. So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V *with respect to ground*. The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V *with respect to ground*.

If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V *lower* than ground, so would be -12V *with respect to ground*. The + terminal would be 0V *with respect to ground*.
> 1 votes

---
Tags: arduino-mega, battery
---


# Question
Title: connecting RTC DS1307 to ethernet shield
What is the easiest way to mount DS1307 to ethernet shield?

I tried to do this: https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up

but my program just freezes when I try to read data from RTC. Is there any other ways to do it?

Code looks like this:

```
const int RTCpin2 = 2;
const int RTCpin3 = 3;

void setup() {
    pinMode(RTCpin2, OUTPUT);
    pinMode(RTCpin3, OUTPUT);

    analogWrite(RTCpin2, LOW);
    analogWrite(RTCpin3, HIGH);
}

void loop() {
     // process RTC time
}

```

# Answer
> 1 votes
I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module. Well, there's two fundamental flaws with it:

1. Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
2. analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

1. Use pins A2 and A3 instead of 2 and 3
2. Use digitalWrite() instead of analogWrite().

---
Tags: arduino-uno, shields, ethernet, rtc
---


# Question
Title: How to simulate delay() to debounce mechanical button using millis()?
Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in. However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.

Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:

```
int but = 12;
int led0 = 7;
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;

int ledCase = 0;
int butState = 0;
int oldButState = 0;

void setup()   {
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(but, INPUT_PULLUP);
}

void loop()    {

   oldButState = digitalRead(but);
   delay(10);
   butState = digitalRead(but);

   if (butState != oldButState && butState == LOW) {
     ledCase += 1;
     oldButState = butState;
   }

   if (ledCase > 4) {
    ledCase = 0;
   }

   Serial.println(ledCase);

switch (ledCase) {
case 0:
digitalWrite(led0, HIGH);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 1:
digitalWrite(led0, LOW);
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 2:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 3:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
break;
case 4:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
break;
}
}

```

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:

```
unsigned long onTime;
unsigned long delayTime;

void setup() {
delayTime = millis() + 10;
}

void loop()    {
oldButState = digitalRead(but);
onTime = millis();
if (onTime >= delayTime) {
butState = digitalRead(but);
delayTime = millis() + 10;
}
}

```

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

# Answer
To better understand how you can do this it is good to understand first just what goes on when a button bounces.

It is, literally, bouncing - just like a ball when you drop it. Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal. It's either connected to ground, or it's not connected to ground. And we're only really interested in when it's connected to ground.

More importantly we're interested in *how long* it's been connected to ground for.

By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground. By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.

Take the following diagram for instance:

The blue line is the state of the button. As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.

The red line is the difference between a timestamp that is set to be equal to `millis()` at the moment the button transitions from HIGH to LOW and the current `millis()` value, and is ignored when the button is HIGH. As you can see the difference between that timestamp and the current `millis()` value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.

When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing. Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.

To translate that into some code, you may end up with something like this (untested):

```
// Two variables to store remembered state information - the time
// of the last HIGH-LOW transition and the previous state of the
//  button.
static uint32_t debounceTime = 0;
static uint8_t buttonState = HIGH;

// Check to see if the button has changed state
if (digitalRead(buttonPin) != buttonState) {
    // Remember the new state
    buttonState = digitalRead(buttonPin);
    // If the new state is LOW ...
    if (buttonState == LOW) {
        // ... then record the time stamp
        debounceTime = millis();
    } else {
        // ... otherwise set the time stamp to 0 for "don't care".
        debounceTime = 0;
    }
}

// If the time stamp is more than 0 and the difference between now and
// then is greater than 10ms ...
if (debounceTime > 0 && (millis() - debounceTime > 10)) {
    // ... set the time stamp to 0 to say we have finished debouncing
    debounceTime = 0;
    // and do whatever it is you need to do.
    digitalWrite(ledPin, HIGH);
}

```

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the *results* of the debouncing that you react to, not the button state itself.
> 3 votes

# Answer
Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch). If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch. If you use a digital switch, the rise is much sharper without significant bounce.

A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch. The cap will drop to GND quickly as the switch drains the charge stored in the cap. But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down). (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities. I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.

The main advantage is, of course, you use absolutely no computing time to debounce any number of switches.

Potential disadvantages:

* Added hardware cost for each switch, making this technique less desirable in production scenarios
* 0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit.
* Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND. As the switch ages, I've seen this delay exceed 50 mSec.
* Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch). Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.
> 2 votes

---
Tags: button, teensy, millis, midi, debounce
---


title: Trouble with Timer 0

text:
# Question
Title: Trouble with Timer 0
I'm taking my first wobbly steps outside the Arduino IDE and I'm not having much success with timers / interrupts. I can set a pin to output and light an LED with registers fine but I cannot for the life of me get it to blink using a timer. I have tried numerous tutorials and followed the Atmel ATmega328 datasheet very closely.

Using an Arduino Uno R3 & Atmel ICE (ISP.) My dev system is Raspbian (Debian) with the GNU AVR toolchain (avr-gcc, avr-objcopy, avrdude.) Apart from not having a bootloader it's a bog standard board (including fuses.)

Here's my current code:

```
#include <avr/io.h>
#include <avr/interrupt.h>

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= (1 << PB5); // Toggle Arduino Pin #13
}

int main (void)
{
    DDRB = (1 << DDB5); // Arduino Pin #13 is Output

    cli(); // Clear Interrupts

    OCR0A = (unsigned char)0xFF; // Compare Register A = 255
    TIMSK0 = (1 << OCIE0A); // Enable Interrupt for Comp. Reg. A
    TCCR0A = (1 << WGM01); // CTC Mode

    sei(); // Set Interrupts
    TCCR0B = (1 << CS02) | (1 << CS00); // Divide by 1024 Prescaler (GO!)

    return 0;
}

```

I don't know if I'm just not seeing something or if I've set registers in the wrong order but it's driving me crazy.

# Answer
> 4 votes
`return 0` resets the device. Use `while(1);` instead, to make it wait indefinitely.

# Answer
> 4 votes
Returning from `main` does not reset the device (it would start up again and do it all over in that case). It calls `exit` which turns interrupts off and loops indefinitely.

```
00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61
  74:   0e 94 52 00     call    0xa4    ; 0xa4 <main>
  78:   0c 94 61 00     jmp 0xc2    ; 0xc2 <_exit>

...

000000a4 <main>:
  a4:   80 e2           ldi r24, 0x20   ; 32
  a6:   84 b9           out 0x04, r24   ; 4
  a8:   f8 94           cli
  aa:   8f ef           ldi r24, 0xFF   ; 255
  ac:   87 bd           out 0x27, r24   ; 39
  ae:   82 e0           ldi r24, 0x02   ; 2
  b0:   80 93 6e 00     sts 0x006E, r24
  b4:   84 bd           out 0x24, r24   ; 36
  b6:   78 94           sei
  b8:   85 e0           ldi r24, 0x05   ; 5
  ba:   85 bd           out 0x25, r24   ; 37
  bc:   80 e0           ldi r24, 0x00   ; 0
  be:   90 e0           ldi r25, 0x00   ; 0
  c0:   08 95           ret

000000c2 <_exit>:
  c2:   f8 94           cli

000000c4 <__stop_program>:
  c4:   ff cf           rjmp    .-2         ; 0xc4 <__stop_program>

```

You can see at address 0x74 it calls main, and then jumps to exit. `exit` turns off interrupts.

With interrupts off your ISR will not toggle pin 13.

---
Tags: interrupt, atmega328, timers, avrdude, avr-gcc
---


title: Serial Error Correction

text:
# Question
Title: Serial Error Correction
I currently have a setup where I take serial output from Arduino 1 and push it through a transmitter to the receiver of Arduino 2 where it is fed back into the serial input and further processed. I want to ensure that there is as little error as possible and recover the data wherever possible.

I have come across the syndrome decoding technique which seems to be the ideal one for me, but I am confused as to how I would go about implementing it.

I know that the Arduino Serial transfers data byte by byte, each being 8 bits, but do not know how this data is sent over the serial connection (i.e. how the start & stop bits & parity is implemented).

I would assume that a solution to this could either involve modifying the data in the buffer or reading it from the buffer and then operating upon it. I could also use adjacent bytes of data for error correction, but this seems wasteful.

How should I proceed with this?

# Answer
Welcome to the wide world of Communications. You are asking about "Error Detection and Correction". This is different from "framing", which allows you to determine when a message starts and ends.

With "error detection", you know there was an error, but you can't necessarily recover from it. With "correction", you know there was an error and you *can* determine what was originally sent.

This *always* requires extra bytes. There are many schemes, but the Fletcher checksum for Error Detection is easy to implement, fast, and only requires 2 extra bytes in the message (4 if hex digits).

The generic approach is to use a finite-state machine. In complicated message protocols, there would be nested state machines: the inner-most would probably determine framing, the next one out might looks at addressing, etc. Any or all of those layers could use Error Detection and/or Correction.

For your simple "protocol", a single state machine is probably sufficient. The states might be IDLE, RX\_PAYLOAD and RX\_CS. As characters are received, they are processed according to the current state and occasionally change the state variable.

```
while (Serial.available()) {
  uint8_t c = Serial.read();
  switch (state) {
    case IDLE:
      if (c == MSG_START)
        state = RX_PAYLOAD;
      break;
    case RX_PAYLOAD:
      if (c == MSG_END) {
        state = RX_CS;
        cs = 0;
        csCount = 0;
      } else if (length < MAX_LENGTH-1) {
        msg[ length++ ] = c;
      }
      break;
    case RX_CS:
      //  Add in the next hex CS digit
      cs = cs * 16 + fromHex(c);
      if (++csCount == 2) {
        // both digits received, see if the CS matches
        if (cs == csOfMsg( msg, length )) {
          // Handle the message
          msg[ length ] = '\0';
          Serial.println( msg );
        } else {
          Serial.println( F("Bad message!") );
        }
        state = IDLE;
      }
      break;
  } // end switch
} // end while

```

There are entire books written on protocols and their design. This is just a made-up example to give you an idea of how it should be structured: a finite state machine, driven by received character "events".

Sometimes you can compute the checksum as the characters are received, like Fletcher. Here, it waits until the entire message plus 2 CS bytes are received.
> 2 votes

# Answer
In my case i used a buffer and a delimiter. Specificaly: The reading is placed on the byte array untill the delimiter is reached.

## For example

From the arduino IDE serial monitor im sending this: `CAT;`

Each letter will be placed inside the byte array and this will stop when the `;` sign is entered. This migh be usefull because you can send the bytes whenever you can and they will remain in the array.

```
void loop(){
if(Serial.available() > 0) {

 char rec = Serial.read();

 if(rec == '.'){
    Serial.print("Here: ");
    for(int i = 0; i < sizeof(attitude); i++){
       Serial.print(attitude[i]); //print
       attitude[i] = (char)0;
    }
    attitudePointer = 0;
    Serial.println();

 }else{
   if(attitudePointer <= sizeof(attitude)){
      attitude[attitudePointer] = rec;
      attitudePointer++;
    }
  }

 }
}

```
> 0 votes

---
Tags: arduino-uno, serial, communication
---


# Question
Title: I'd like to make RC car and remote controller via bluetooth (HC06)
At first, I tried to make whole code for an RC car and remote controller, but I realized that it's difficult for me since I have few ideas about C++. So, I changed a few things like turning on the LEDs with switches and servomotors with potentiometer. Here are my code.

**Remote controller**

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(2,3);
int sw1=13;
int sw2=12;

void setup() {
  BTSerial.begin(9600);
  Serial.begin(9600);
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
}

void loop() {
  int a = analogRead(A0);
  int map_a=map(a,0,1023,0,255);
  int state1=digitalRead(sw1);
  int state2=digitalRead(sw2);

  BTSerial.print('S');
  BTSerial.print(map_a);
  BTSerial.print(',');
  BTSerial.print(state1);
  BTSerial.print(',');
  BTSerial.print(state2);
  BTSerial.print('E');
  delay(100);
}

```

\< RC CAR \>

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(2,3);

byte buffer[255];
int bufferPosition;

void setup() {
 BTSerial.begin(9600);
 Serial.begin(9600);
 bufferPosition=0;

}

void loop() {
  {
    if(BTSerial.available()>0){
    unsigned char data = (unsigned char)BTSerial.read();
    buffer[bufferPosition++]=data;
    Serial.println(data);
    delay(100);
    }
}
}

```

When I checked the result from `Serial.println(data)` from RC car code, it was trash...

Can you instruct me what's wrong with this code?

# Answer
There are some fundamental problems in the code - `bufferPosition` never stops increasing (until it reaches 32768) and so `buffer` will overflow. However, neither of these two problems are causing the 'trash', as you are outputting the result of reading the serial, not anything from the buffer.

The problem lies in the casting of the result from `BTSerial.read()` to `unsigned char`.

`Serial.print()` does not like this. Actually it doesn't care, but it won't give you what you expect. It just prints out the value stored - so 'a', which is 97, will come out as '97' on the serial monitor. `Serial.print()` only outputs ASCII characters when you give it a `char` or `char[]`.
> 1 votes

---
Tags: bluetooth
---


title: Low power + Logging motion detection

text:
# Question
Title: Low power + Logging motion detection
Scenario: I would like to monitor my closet's door as I highly suspect a family member is opening and using my items without permission. To respect privacy and also because my closet is nowhere near a power mains, I don't need video nor audio recording. I also do not need indicator lights etc because I intend to turn it on when I go to work and check the logs on the SD card when I return home. A typical day would require the device to run for 12 hours minimally.

Aim: Is it possible for Arduino to achieve the following,

1. Run on batteries for at least 1 month
2. Detect motion
3. Logging the detection motion onto a text file in a SD card

Or do I have to look elsewhere for this functionality?

Current understanding: I am aware Arduino can run on batteries though I've never been able to get it to last more than 3 hours. Probably has to do with me not using the low power mode or something and that my batteries were being stepped up. I also know that Arduino has some PIR motion sensors though I don't quite remember how power hungry these sensors are. I have NEVER tried logging onto an SD card using Arduino. This sums up my experience with Arduino.

Any advice would be much appreciated. Thank you.

# Answer
> 1 votes
It is possible to modify an Arduino Pro Mini (clone or original) to less than 1 mA and give at least a month on standard batteries (1000 mAh). Basically you need to remove the Power indicator LED and use low power mode in the sketch.

You could start simple by just lighting a LED when motion is detected and add the SD log later.

There are several techniques to detect motion. Advanced accelerometers such as ADXL345 but also simple wire sensing. The standby power requirements for these have a large variation.

# Answer
> 1 votes
For low-power, just some tips (link references)

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

claim the below results,

```
LED off, without the JeeLib library: 6.7 mA
LED on, without the JeeLib library: 8.8 mA
LED off, with the JeeLib library: 43 uA (!)
LED on, with the JeeLib library: 2.2mA

```

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

Detailed step by step tutorial.

For sensing PIR will depend on exact components; using SMD low-leakage components will do the trick but cost would increase. There are very-low-power RTC on the market and maybe SD logging will be more difficult as can consume up to 200 mA per reading/writing operations.

# Answer
> 1 votes
You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state. Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.

An SDcard is neither necessary, nor a good idea. If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card. They will also be simpler to support in software. Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.

Your main power consumption win however will be sensors. If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption. Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened. Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.

# Answer
> 0 votes
The PIR sensors are actually pretty cheap: http://www.ebay.com/itm/like/171338717482?ul\_noapp=true&chn=ps&lpid=82

---
Tags: sensors, power, sd-card, datalogging
---


# Question
Title: What does the 'arduino' avrdude programmer do?
The command line that my toolchain (CLion \+ PlatformIO) uses to program my Arduino (Uno) includes includes

```
avrdude ... -c arduino ...

```

but the documentation for this programmer simply reads

> -c programmer-id
> ...
> arduino Arduino
> ...

What does the `arduino` programmer do. Does it just correspond to using the bootloader?

# Answer
Yes, the -c option specifies the methods of interacting with the device's loader.

The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup

Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno. Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.
> 2 votes

---
Tags: avrdude, programmer
---


# Question
Title: I would like to retrieve data from a MySQL database using PHP using HTTP requests, on my Arduino
Please help me find a way to do it.

I have looked at the following for sending data Arduino to MySql

But can't seem to find visa-versa.

# Answer
> 2 votes
There are two things you have to set up for this: 1. Retrieving/parsing websites from your Arduino. 2. Making a dynamic website using PHP (and MySql).

* Try to set up your Arduino as a WebClient, check if you can retrieve a website like google.com or a minimalistic website.
* Try to get your arduino to interpret a string or retrieve values from that website. (I.E: retrieve the day/time from the HTTP message)

IF your arduino can retrieve webpages, you're halfway there (somewhat). And your project is running out of the scope of this arduino.stackexchange.

Now you're going to have to create a dynamic website. You can let PHP reach for values from your MySql database (you should just use a text file first) and display them on your site (in HTML). Your Arduino can now poll your website, to get the HTML content and parse it to the values.

# Answer
> 2 votes
You could develop a REST based service, to make Arduino consume web service using the aRest library.

Following is a tutorial of how to use the aRest API with Arduino: A REST API for Arduino & the CC3000 WiFi Chip.

---
Tags: arduino-uno
---


title: Taking off the chip from Arduino

text:
# Question
Title: Taking off the chip from Arduino
I just uploaded a sketch of a song to my Arduino and it works well. Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.

# Answer
Yes and no.

To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to *another* Arduino board or other device with the appropriate support hardware, then it should work just fine.

However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).
> 2 votes

# Answer
Easy part first: You CAN put another chip on arduino PROVIDED that chip already has a bootloader on it. If it's a raw chip, burn the bootloader on it first. This guide will help.

You CAN connect the programmed chip to speaker PROVIDED you add the minimal circuit components required for an arduino to run. These include - a 16 MHz crystal, two 22 pf capacitors and a 10K resistor. Use the schematic in the bootloader guide. That will work.

Besides this, you will require a 5V power source. You can alternatively use 3xAA cells (4.5V will work perfectly). Alternatively use a wall adapter of 7V or higher and use a linear regulator (7805) to generate a perfect 5V supply for your arduino. You will need this pin mapping diagram to connect the speaker to arduino once you take it out from the board:
> 0 votes

---
Tags: atmega328
---


title: Arduino Serial Queue

text:
# Question
Title: Arduino Serial Queue
So I am programming an LED Music Visualizer that uses a combination of Processing and Arduino. I have it all working as I want to but there is a small problem. If I were to stop the music, then the Arduino will keep displaying the visualization for a few seconds. I believe that this issue would be caused by it "catching up" on new serial data from Processing like a queue. So my question is: When arduino uses the Serial.read() function, is it using the most recent value or is it using the next value received after the last one that it used, like a queue of values.

**Example**: Processing sends the values 1,2,3,4,5,6,7,8,9 over serial in 10 millisecond intervals. Arduino only performs Serial.read at 20 millisecond intervals. Would the arduino read the values 1,3,5,7,9 in or would it read the values 1-9 but in twice the time?

Sorry for the confusing question, hopefully somebody could shed some light. At the core, it is a question on how serial works, you can ignore the part about the music visualizer.

# Answer
It sounds like you figured most of your question out already.

(Someone correct me here if I'm wrong). The Atmega 328p uC, I believe, has an 8 byte hardware buffer for RX serial data. In software, the Arduino core code defines a maximum ring buffer of 64 bytes that acts as a FIFO queue.

So, what does his mean? Let's just focus on the hardware buffer since it's fairly easy. Say you send your data 1,2,...,10 at 10ms intervals, and you read your data at 100ms intervals (for illustration purposes). The problem is that you send 10 bytes of data but only have room for 8 bytes. So, your first two values (1,2) are pushed out of the buffer and lost. This idea also illustrates a FIFO queue, first in first out.

The same idea can be extended to a ring buffer.

Anyway, like you said, this could explain your problem. If you have 64 bytes, which will obviously be full since your inevitably losing data (20ms read with a 10ms write), you'll be seeing the effects for 64 * 20ms = 1.28s. There's probably some processing delay too which will extend this delay, but it's more than likely minimal if it's efficient code.
> 1 votes

# Answer
> Arduino only performs Serial.read at 20 millisecond intervals.

It sounds like you're using `delay` to pace the reads. But why? You'll start to lose data after reading just 3 or 4 characters (60ms to 80ms). Serial at 9600 can send 1 character per millisecond, 20 times faster than you are reading them.

If you edit your post to include your code, we might be able to make a suggestion to eliminate that delay.
> 1 votes

---
Tags: serial, programming, processing-lang
---


# Question
Title: Why won't processing not communicate with Arduino uno?
I downloaded the Processing language and ran the "Hello World" program to test it. The message appears in the Serial console but not on the Processing console. It prints "null" only. I am using the code supplied by Sparkfun. Other people have had this problem. I am looking for clear explanation and solution.

# Answer
> 1 votes
I apologize for presenting a vague question. I was unable to successfully run the simple code to learn "serial communication" presented by Sparkfun on: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing.

Step 1. Run Arduino to produce "Hello, World" on the Serial Port. Step 2. Run Progressing 3.0.1 to produce "Hello, World" on its console.

The code from the website are copied and pasted onto my iMac running El Capitan. I received an error message for Step 2 stating the "port is busy."

Once I closed the Arduino (Step 1) and compiled and ran Step 2, it worked!

Several other people found different solutions. My solution is simple. Run one program at a time.

---
Tags: arduino-uno, serial
---


title: Where is the Aref pin for Attitny88

text:
# Question
Title: Where is the Aref pin for Attitny88
I would like to use the external analog refence voltage in an Attiny88 project I am working on that will be powered with batteries.

However, the datasheet for this processor does not show an Aref pin like other versions of the attiny, like attiny85 and attiny84, where it is usually the pin PA0 or PB0. Does anyone know where is the pin for the external voltage reference in attiny88 (e.i. Aref pin)? Does this chip has the functionality for an external analog reference voltage?

# Answer
> 5 votes
As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.

---
Tags: voltage-level, attiny
---


title: How to connect Arduino and Beaglebone

text:
# Question
Title: How to connect Arduino and Beaglebone
I am newbie, I am afraid of doing harm and getting a burned-out Beagle Bone Black. I have soldered this SparkFun Logic Level Converter - Bi-Directional.

I have several questions:

1. How can I check if my converter works correctly without connecting it to any board or at least only to an Arduino?
2. How should I connect all my schematic from bbb to converter and then to an Arduino. I have a bi-directional converter, BTW. Can someone draw a simple picture of how to connect?

I would be grateful for any help.

# Answer
> 1 votes
The simplest method of connection is just to plug the Arduino into the BBB's USB socket. That way there's no level conversion or anything needed - you can just open the serial port and communicate through that - what could be simpler?

You can even install avrdude on the BBB itself and upload code (HEX files) direct from the BBB, and the BBB supplies all the power.

# Answer
> 1 votes
In addition to the other methods listed, which will both work, you could also use an Arduino that uses 3.3V logic and connect the serial/UART.

The Trinket: https://www.adafruit.com/products/1500?gclid=COGOxqq-z8kCFcYRHwodpL8P2A Pro 328: https://www.sparkfun.com/products/10914

# Answer
> 0 votes
Your main concern for frying something would be when sending data from the Arduino(which uses 5V) to the Beagle (Which uses 3.3).

The Arduino *receiving* data on the Arduino RX line wouldn't be anything to worry about since you would be sending data at 3.3V from the Beagle to 5V on the Arduino( Remember that unlike RS-232, TTL serial has no carrier voltage, so current only travels over the lines when data is actually sent )

You could always hook up the Arduino side (HV/5V), program the Arduino to do

```
Serial.println("HELLO WORLD");

```

inside `void loop()`

and look for voltage being send over the RX pin on the LV side. You would still have to connect 3.3V to LV and GND to GND.

---
Tags: serial
---


# Question
Title: What is the correct way to wire a piezzo buzzer with a potentiometer and a button?
I'm working on a morse transmitter (kind-a), this how it looks like now:

It's working, but is it correct? My piezo buzzer is 3-24V. I use the potentiometer as a volume control. The button is for transmitting morse code.

I've seen a way of wiring like this, not using any resistors, it feels wrong, is it correct? https://cdn.sparkfun.com/assets/learn\_tutorials/3/1/0/Arduino\_circuit\_11\_01.png

# Answer
> 1 votes
You are using the Arduino basically as a power supply (in your wiring). The linked wiring is for PWM (analogWrite). This allows pulse output to generate tone (and volume). Here is a good reference.

---
Tags: arduino-uno, button, potentiometer, piezo
---


# Question
Title: Connecting via serial with Arduino comand line
Since inotool is dead, I'm trying to transition over to Arduino's built-in command line tool.

It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running `ino serial` would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.

How is this accomplished with the current Arduino command line tool?

# Answer
> 0 votes
I ended up simply switching to ano.

# Answer
> 2 votes
If you are using linux, as I guess, you can look at this archwiki page. Even if is a wiki relative to archlinux OS some informations explained are LinuxOS independendent.

For your needs, you can use screen command. Here is an example: remember to substitute the serial port with the one wich arduino is connected (usually /dev/ttyACM\* or /dev/ttyUSB\*) and to specify the right baud rate.

```
screen /dev/ttyACM0 9600

```

---
Tags: serial, command-line, ino
---


title: HDMI EDID emulator

text:
# Question
Title: HDMI EDID emulator
I am working on a project where i emulate the EDID of a screen to force a source into sending data on a certain resolution.

I read the original EDID code of a screen and change the timings into the resolution I want to force the source in, i send this changed EDID code to the source with an Arduino uno when the source gives a read on address 0x50 (where the EDID located, see handshake). We have an HDMI in/out with the data lines connected thru and the DDC lines (source) connected to the Arduino that we can send the changed EDID to the source (i²c protocol).

I can change the resolution successfully on some sources, and on some it doesn’t change. The attached screen doesn’t find a source. I use the same code for both scenarios.

```
#include <DTWI.h>
#include <Wire.h>         //BUFFER_LENGTH = 256

uint8_t edid[256] = {
 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x4C, 0x2D, 0xF4, 0x0C, 0x45, 0x52, 0x46, 0x31, 0x15, 0x19, 0x01, 0x03, 0x80, 0x3C, 0x22, 0x78, 0x2A, 0x52, 0x95, 0xA5, 0x56, 0x54, 0x9D, 0x25, 0x0E, 0x50, 0x54, 0xBF, 0xEF, 0x80, 0x71, 0x4F, 0x81, 0xC0, 0x81, 0x00, 0x81, 0x80, 0x95, 0x00, 0xA9, 0xC0, 0xB3, 0x00, 0x01, 0x01, 0x02, 0x3A, 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40, 0x58, 0x2C, 0x45, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x01, 0x1D, 0x00, 0x72, 0x51, 0xD0, 0x1E, 0x20, 0x6E, 0x28, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x32, 0x4B, 0x1E, 0x51, 0x11, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x53, 0x32, 0x37, 0x45, 0x33, 0x37, 0x30, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x62, 0x02, 0x03, 0x1B, 0xF1, 0x46, 0x90, 0x04, 0x1F, 0x13, 0x03, 0x12, 0x67, 0x03, 0x0C, 0x00, 0x10, 0x00, 0x80, 0x22, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00, 0x01, 0x1D, 0x00, 0xBC, 0x52, 0xD0, 0x1E, 0x20, 0xB8, 0x28, 0x55, 0x40, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x8C, 0x0A, 0xD0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0C, 0x40, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x8C, 0x0A, 0xD0, 0x8A, 0x20, 0xE0, 0x2D, 0x10, 0x10, 0x3E, 0x96, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D
};

void receiveEvent(int receivedByte)
{
    if (receivedByte == 1)          //If there is 1 byte received
    {
      int receivedValue = Wire.read() << 1;
      receivedValue |= Wire.read();
      Serial.print("Read byte: ");
      Serial.print(receivedValue);
      Serial.println();
    }
    else
    {
        Serial.println("Not the amount of bytes that was expected: ");
        Serial.print(receivedByte);
    }

    while(Wire.available())
    {
        Wire.read();
    }
    return;
}

void requestEvent()
{
      Serial.println();

     for (int i = 0; i < 256; i++){
            Wire.write(edid[i]);               //Write EDID
            Serial.print(edid[i], HEX);      //Print EDID
            Serial.print(",");
     }

    Serial.println();
    Serial.println("Finished");      //Write is complete

}

void setup()
{
  Serial.begin(9600);
  Serial.println("**** HDMI ****");
  pinMode(2, OUTPUT);          //Hot plug detection
  Wire.begin(0x50);
  digitalWrite(2, LOW);
  delay(20);
  digitalWrite(2, HIGH);         //Source knows that a screen is attached and want to read the edid of the screen

  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

void loop()
{

}

```

The following attached pictures are the EDID handshakes without the Arduino involved.

Handshake 1: This is an HDMI 1.4 device

Handshake 2: This is another HDMI 1.4 device

You can see that the handshakes are the same. My code only works on handshake 1.

Does anyone have an idea why it doesn't work on the other devices ?

Does it has to do with the Start/Restart ?

Regards !

# Answer
> 1 votes
I'm not an expert in HDMI/DDC, but I have some theories to remove potential problems:

1. "Wire.onRequest/Wire.onReceive" could be before "digitalWrite(2, HIGH)", to really represent "OK, you can send me data now" (Arduino isn't the fastest HW, and Arduino libs add extra overhead - lots of condition races can occur);
2. You could use "Write.write(did, 256)", instead of writing one byte to I2C then another via serial (again, racing conditions, specially since serial writing is slow);
3. If I'm not misunderstanding, the byte received from HDMI means the byte you should start transmitting EDID (ex: for "0", do a "Wire.write(edid, 128)", for "0x80", do a "Wire.write(edid + 0x80)"). This is a common approach for reading from PROM chips. HDMI have a 5V pin to allow PROM reading from turned-off devices, and byte 127 from EDID means "I may have more 128 bytes for you".
4. Are you doing simple tests, with unmodified data? Ex: read EDID from device X, test that same EDID, then test with modified data?

---
Tags: arduino-uno
---


# Question
Title: MPPT using preassembled 'adjustable' buck/boost IC
This is more of a thought experiment, as I don't know if I'll have the time to work on it.

Items:

Idea:

Looking at the Instructable, that seems like a fairly interesting and robust circuit, originally developed by one Tim Nolan whose website no longer seems to exist.

I'm somewhat lazy/fearful of messing things up when building from scratch, so I like to get preassembled modules and tinker instead. So, my thought is simple (ish). Looking at the LM2596 module, the output voltage is determined by the setting of the multiturn pot. I'd like to replace that pot with, say, a PWM controlled voltage from an Arduino, which I can then adjust using Tim Nolan's code to achieve MPPT.

So to be very specific, the question is: can I safely remove that pot and use a PWM'd voltage in its place, in order to control the output for MPPT?

# Answer
No.

The switching frequency of the LM2596 is 150kHz, but the sampling frequency of the Arduino is only 10kHz (on a good day). You won't be able to adjust the PWM quickly enough to fine-tune the LM2596 output voltage. The LM2596 uses the 1.23V feedback voltage to change what it's doing. But the feedback voltage will only change as fast as the Arduino can change the PWM feeding it (and that the RC smoother will allow).

It will be like pushing a shopping cart backwards, blindfolded. By the time you feel the directional change in the cart, it will have steered off course by quite a bit. Then you have to compensate wildly to bring it back on course.

The same would probably happen here: the LM2596 would begin adjusting the output voltage to make the feedback voltage come back towards 1.23V. But the Arduino doesn't respond in time. The Arduino has to do an ADC conversion, do some calculations, change the PWM, which eventually changes the RC output voltage, which is the feedback voltage. So the LM2596 changes some more... and even more. Eventually the feedback voltage does change, but by this time the output voltage has changed significantly.

Another way to look at is that the LM2596 is like another "processor", trying to optimize its own function, output voltage instead of MPPT. It's running much faster than the Arduino, so there's no way the Arduino can trick the LM2596 into doing what it *really* wants, MPPT.
> 1 votes

# Answer
The pot is actually part of the feedback mechanism, so you can just feed it a fixed voltage (based on PWM duty cycle). See the second diagram on page 9 of the datasheet

You could however replace it with a digital pot (not necessarily 10k).
> 1 votes

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


title: FastLED fade WS2812B

text:
# Question
Title: FastLED fade WS2812B
Learning how to program with Arduino, but the learning curve is out of my league.

I have this

```
    #include <FastLED.h>
    #define NUM_LEDS 4
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop() {
      // Turn the first led red for 1 second
      leds[0] = CRGB::Green;
      leds[1] = CRGB::Red;
      leds[2] = CRGB::Green;
      leds[3] = CRGB::Red;
      FastLED.show( 99 );
      delay(1000);

      // Set the first led back to black for 1 second
      leds[0] = CRGB::Red;
      leds[1] = CRGB::Green;
      leds[2] = CRGB::Red;
      leds[3] = CRGB::Green;
      FastLED.show( 99 );
      delay(1000);
    }

```

So, I want them to fade from green to red. led 1 is green, and led 2 is red I should probably program this in a different way, but I don't know how. Any ideas are welcome!

# Answer
At the moment you have become used to working with pre-defined named colours, like CRGB::Red and CRGB::Green. Those are just symbolic names for combinations of numeric values for red, green and blue.

So by using numeric values and varying them slightly over time you can create fade effects. I am not personally familiar with that library or class, so I cannot tell you how to do it, but reading the documentation should show you how you can use variables to specify each of the colour components as a single colour.

As for how to fade from red to green - since they are two completely separate colours (they use separate colour channels in the LEDs) there are two main ways of doing it:

1. Start with red on full and green off. Slowly increase green to get yellow. Then slowly decrease red to get green.
2. Start with red on full and green off. Slowly increase green while slowly decrease red. At 50% they will cross over.
> 1 votes

# Answer
```
//start with full red
leds[0].red = 255;

//slowly add green
for( int i=0; i<256; i++ )
{
  leds[0].green = i;
  delay(10);
}

// slowly subtract red
for( int i=255; i>=0; i-- )
{
  leds[0].red = i;
  delay(10);
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Sending IR (NEC)-Signals with Arduino

text:
# Question
Title: Sending IR (NEC)-Signals with Arduino
I have an **Arduino Micro** where I want to control a display with IR commands. So the Arduino should send the IR commands to the display.

I have found a library "Arduino-IRremote", which I am using to transmit Commands to the display. The display works perfectly with its remote control, however I can't get it accept signals from my Arduino.

Now the special part about my setup is, that I do not use a "classic" IR transmitter. Instead i uset an IR cable, which is connected to "IR-In" of the display. So no LED - only a wired connection. The IR-cable consists of 3 wires. 2 for power supply (VIN and GND) and one is for the data connection. The wire with the data connection is connected with the Arduino PWM pin 3 (like it is said on the example in the linked library), but I tried all other pins anyway.

```
#include <IRremote.h>
IRsend irsend;

void loop() {

  for (int i = 0; i < 2; i++) {
    digitalWrite(RXLED, HIGH);
    irsend.sendNEC(0x004eff71, 32);
    Serial.println( "sendNEC 00 4E FF 71" );
    digitalWrite(RXLED, LOW);
    delay(40);

  }
  delay(1000);
}

```

`004eff71` is a NEC-Command from the original remote control

Now can somebody tell me, what I'm doing wrong? The program compiles and the LED lights up, everytime it should send the NEC-command. But still the display receives nothing. What is wrong?

# Answer
> 3 votes
It isn't working probably because the output of the Arduino isn't simply an on/off signal.

That library uses a pulse width modulated output on the Arduino to drive an LED. **When the LED is "on" the signal driving it is actually pulsing at a very high rate.**

I don't know what all you'd have to change to make that work with a direct wired connection.

Another thing that might becausing problems is that without checking, you can't be sure that the signal level you are sending matches the levels that the IR receiver would normally produce.

# Answer
> 0 votes
It would help to know the specifications of the IR input on the device you're trying to control but after a bit of googling it looks like most of them are just expecting a connection to an IR receiver. I found a link to what appears to be a common one, TSOP22.., TSOP24.., TSOP48.., TSOP44.. and here's a link to the data sheet (http://www.vishay.com/docs/82459/tsop48.pdf). If you check the Vo on page 2 it shows 0-5V. You didn't mention if you're using a 5V or 3V Arduino so that could be an issue.

The PWM outputs do in fact generate square wave signals so at first glance this does not look like a hardware issue (assuming it is wired correctly for the IR input on your equipment).

I'd start taking a look at the data you're trying to send. I haven't looked into the library you mentioned and hopefully it contains a sample to show how to properly initialize the library and send data. Maybe instead of first byte first it needs to be sent first byte last or requires a fixed number of bytes to send...

Providing more details about your project you might get a better answer.

---
Tags: hardware
---


# Question
Title: Wire over 1ft does not work with sensors SRF02
Im using an SRf02 ultrasonic sensor, and I need to make the wires long to elevate the sensor. They turn on and blink and are able to transmit a signal, yet they are not able to receive a signal. What is the error?

# Answer
Using the internal pullup resistors for I2C is not recommended. Arduino are very wrong in providing those as the default option and basically "hiding" the fact that I2C needs decent pullup resistors from you.

The internal pullup resistors, because they are so weak (i.e., a high resistance, typically \> 50KΩ), do not pull the clock and data lines up adequately, and as such are only suitable for very short connections (in the order of a few inches). Anything longer and the induced noise and inductance and capacitance of the wires will corrupt the I2C waveform.

I2C requires pullup resistors in the range of 2.2KΩ to 4.7KΩ. As you can see that is more than 10x the pullup strength of the internal resistors.

For off-board connections (i.e., wires) you want the lower end of that range. So add a 2.2KΩ resistor between SCL and +5V and another between SDA and +5V and you should find it works much better.
> 1 votes

---
Tags: sensors
---


# Question
Title: Seeking to measure back EMF of an electric motor via Arduino
Is it possible to measure the back EMF of a motor, using just the Arduino and no sensors?

Or what type of sensor do I need? One that measures current?

# Answer
There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see Back EMF.

This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.

Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.
> 4 votes

# Answer
You will need at least an external current sensor, the arduino has no way of measuring current built in. You will also need to measure the winding resistance of the motor beforehand. look to this answer for a good explanation: https://electronics.stackexchange.com/questions/54997/how-can-i-measure-back-emf-to-infer-the-speed-of-a-dc-motor

DC current sensors compatible with arduino should not be hard to find; just search one of the standard hobby electronics components sites.
> 1 votes

# Answer
Take a look at this website: http://www.vwlowen.co.uk/arduino/current/current.html

It shows how to make a create a simple current sensor with just a few resistors.
> 0 votes

---
Tags: motor
---


# Question
Title: Reading Analog values of bluetooth module HC 05
I am working on a project which requires signal strength of a bluetooth TX and RX. what i assume is that in bluetooth module like hc05, there is an antenna receiver which reads the analog signal and then passes it to its ADC to get data in terms of 0's and 1's. But is there any way i can read the analog signal strength of the reveiver antenna directly? Please help

# Answer
> 1 votes
Try looking up the datasheet to see if there is a command for signal strength. It's impossible to **directly** read the the analog value since the signal strength is way too low in amplitude.

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