title: Why doesn't pin 9 blink?

text:
# Question
Title: Why doesn't pin 9 blink?
I use simple LED blinking code on an Arduino MEGA 2560. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?

My code:

```
// Set up the DATA direction
void setup()
{
  for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);
}

// The main program
void loop()
{
  for(int j=2; j<=10; j++)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }

  for(int j=9; j>=2; j--)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }
}

```

And the circuit is:

# Answer
> 4 votes
It looks like your main problem is the loop in `setup()`:

```
for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);

```

This will call `pinMode()` with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to **`i<=9`**.

However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely **must** have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.

---
Tags: arduino-mega, led
---


title: Why is resolution 20?

text:
# Question
Title: Why is resolution 20?
I am using an amazing code to send/read infrared pulses without any external library. The code is fine and I took about 1 hour to fully understand it. The only thing I didnt understand is the variable RESOLUTION. I believe it should be 0 not 20. I think it should be as low as possible.

You can see the code at:

https://learn.adafruit.com/ir-sensor/using-an-ir-sensor

or below:

```
/* Raw IR decoder sketch!
This sketch/program uses the Arduino and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// for MEGA use these!
//#define IRpin_PIN PINE
//#define IRpin 4

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse; // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

// while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH

     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);

     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses
* RESOLUTION, DEC);

    Serial.print(" usec, ");
    Serial.print(pulses[1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }

  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF (in 10's of microseconds)");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    Serial.print("\t"); // tab
    Serial.print(pulses[1] * RESOLUTION / 10, DEC);
    Serial.print(", ");
    Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
    Serial.println(",");
  }
  Serial.print("\t"); // tab
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC);
  Serial.print(", 0};");
}

```

# Answer
> 2 votes
Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0).

So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a `0` and 80 for a `1`. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send.

Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.

PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.

Hope that helps somewhat. Just let me know is anything is still unclear.

---
Tags: ir
---


title: How this smal infrared work

text:
# Question
Title: How this smal infrared work
I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:

```
for(int i=0;i<384;i++) {
  digitalWrite(IRledPin,HIGH);
  delayMicroseconds(13);
  digitalWrite(IRledPin,LOW);
  delayMicroseconds(13);
}

if (digitalRead(IRsensorPin) == LOW){
  digitalWrite(D13ledPin,HIGH);
} else {
  digitalWrite(D13ledPin,LOW);
}

```

My question is this: I first send the pulses, so when I reach the line `if (digitalRead(IRsensorPin) == LOW){` the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.

I have no idea why this code works. I would be glad to listen smarter people to help me understand this.

Thank you.

# Answer
> 0 votes
The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.

These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.

Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.

---
Tags: ir
---


# Question
Title: Arduino Nano no serial port for MacBook Air 2013
# Problem

I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.

Opening the Arduino software, pulling down the `Tools > Serial Port` menu does not show me a valid serial port. All I see is:

```
/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

```

## What I've tried and did not work

* I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file `FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg`. Restarted after installation.
* Tried connecting arduino to both USB ports on my Air.

## More Info

* Running Mac OSX 10.10 Yosemite
* Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.

If it helps, I can see the USB Serial in my `Apple Logo > About This Mac > System Report` under `Hardware > USB`

```
USB2.0-Serial:

  Product ID:               0x7523
  Vendor ID:                0x1a86
  Version:                  2.54
  Speed:                    Up to 12 Mb/sec
  Location ID:              0x14100000 / 8
  Current Available (mA):   500
  Current Required (mA):    Unknown (Device has not been configured)

```

I'm out of ideas and options. Any help would be greatly appreciated.

Thanks in advance :)

# Answer
> 13 votes
This solved it for me.

* Download this driver
* Install it
* Run `sudo nvram boot-args="kext-dev-mode=1"`
* Reboot

Serial ports now showed up in the Arduino IDE and also when I used `ls -1 /dev/tty*`

Hopes this helps someone.

Reference: This thread

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


# Question
Title: Combine Code Arduino GSM Shield and Adafruit GPS Shield
I have a problem to combine both code for Arduino GSM Shield and Adafruit Ultime GPS Shield. I already change my code to the basic one like examples. I think i found the problem. The problem is when i want to do get request to the url/web.

**Here is the link to the Adafruit Ultimate GPS Shield.** Adafruit Library Adafruit Ultimate GPS Shield Info

My code base on example of Arduino GSM Library (GSM Web Client) and Adafruit GPS Library (Parsing)

**This is the code that make my code not working. If i put the code i do not receive any data at serial.**

```
 // if you get a connection, report back via serial:
 if (client.connect(server, port))
 {
    Serial.println("connected");
   // Make a HTTP request:
   client.print("GET ");
   client.print(path);
   client.println(" HTTP/1.1");
   client.print("Host: ");
   client.println(server);
   client.println("Connection: close");
   client.println();
 }
 else
 {
  // if you didn't get a connection to the server:
  Serial.println("connection failed");
 }

```

**This is the basic code that working so far**

```
// ********************************************
//   GPS Library
// ********************************************
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <stdlib.h>

// ********************************************
//   GSM Library
// ********************************************
#include <GSM.h>

// ********************************************
//   Sim Card Pin Number if available
// ********************************************
#define PINNUMBER ""

// ********************************************
//   Set Up APN data for GPRS Connection
// ********************************************
#define GPRS_APN       "Maxis" // replace your GPRS APN
#define GPRS_LOGIN     "maxis"    // replace with your GPRS login
#define GPRS_PASSWORD  "wap" // replace with your GPRS password

// ********************************************
//   Initialize GSM Library
// ********************************************
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// ********************************************
//   Setup Arduino to browse URL/web through GPRS
//   The code below will setup path like:
//   http://arella.com.my/urltomysql.php?firstname=Muhammad&lastname=Faiz
//   When Arduino browse the web, it will submit firstname:Muhammad
//   and lastname:Faiz into database. I want to store GPS data into database       later
// ********************************************
char server[] = "arella.com.my";
char path[] = "/urltomysql.php?firstname=Muhammad&lastname=Faiz";
int port = 80; // port 80 is the default for HTTP

// ********************************************
//  Set Adafruit GPS to use software serial on pin
//  D9 & D10 on Arduino. Use Jumper Wire from D7,D8 to D9,D10
// ********************************************
SoftwareSerial mySerial(10, 9);
Adafruit_GPS GPS(&mySerial);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO  false

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

//***********************************************
// convert NMEA GPS Format to Google Map Format
//***********************************************
int degLatInt, degLongInt;
float minLatFloat, minLongFloat, googleMapsLat, googleMapsLong;
char* lat_str = new char[10];
char* long_str = new char[10];
char degLatString[5], degLongString[5];

void setup()
{
   Serial.begin(115200);
   gsmAccess.begin(PINNUMBER);
   gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);

   boolean notConnected = true;
   while(notConnected)
   {
      if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
         (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   // If i enable the code below, my code not working.
   /* if (client.connect(server, port))
      {
      Serial.println("connected");
      // Make a HTTP request:
      client.print("GET ");
      client.print(path);
      client.println(" HTTP/1.1");
      client.print("Host: ");
      client.println(server);
      client.println("Connection: close");
      client.println();
  } */

 //***********************************************
 // Setup Adafruit GPS Shield
 //***********************************************
 // connect at 115200 so we can read the GPS fast enough and echo without  dropping chars
 // also spit it out

 Serial.println("Adafruit GPS library basic test!");

 // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
 GPS.begin(9600);

 // uncomment this line to turn on RMC (recommended minimum) and GGA (fix     data) including altitude
 GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
 // uncomment this line to turn on only the "minimum recommended" data
 //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
 // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
 // the parser doesn't care about other sentences at this time

 // Set the update rate
 GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
 // For the parsing code to work nicely and have time to sort thru the data, and
 // print it out we don't suggest using anything higher than 1 Hz

 // Request updates on antenna status, comment out to keep quiet
 GPS.sendCommand(PGCMD_ANTENNA);

 // the nice thing about this code is you can have a timer0 interrupt go off
 // every 1 millisecond, and read data from the GPS for you. that makes the
 // loop code a heck of a lot easier!
 useInterrupt(true);

   delay(1000);
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
   char c = GPS.read();
   // if you want to debug, this is a good time to do it!
   #ifdef UDR0
   if (GPSECHO)
   if (c) UDR0 = c;
   // writing direct to UDR0 is much much faster than Serial.print
   // but only one character can be written at a time.
   #endif
}

void useInterrupt(boolean v) {
   if (v)
   {
      // Timer0 is already used for millis() - we'll just interrupt somewhere
      // in the middle and call the "Compare A" function above
      OCR0A = 0xAF;
      TIMSK0 |= _BV(OCIE0A);
      usingInterrupt = true;
   } else
   {
      // do not call the interrupt function COMPA anymore
      TIMSK0 &= ~_BV(OCIE0A);
      usingInterrupt = false;
   }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
   // if a sentence is received, we can check the checksum, parse it...
   if (GPS.newNMEAreceived()) {
   // a tricky thing here is if we print the NMEA sentence, or data
   // we end up not listening and catching other sentences!
   // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
   //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived()  flag to false

   if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag  to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
   }

   // if millis() or timer wraps around, we'll just reset it
   if (timer > millis())  timer = millis();
   // approximately every 2 seconds or so, print out the current stats
   if (millis() - timer > 5000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour+8, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
         /////////// Latitude /////////////
         // Convert NMEA Latitude to String
         dtostrf(GPS.latitude, 7, 4, lat_str); //convert GPS.latitude from float to String. 7 - means 8 characters long ; 4 - means 4 decimal point

         // Get Degree substring from latitude String
        strncpy(degLatString, lat_str, 1); // Get Degree from Full Latitude String. Example 311.7799 - Get 3

        // Get Minutes substring from latitude String
        char* minLatString = lat_str + 1; // Move pointer up 1 position. Example 311.7799 will move to 11.7799

        // Convert Deg String to int
        degLatInt = atoi(degLatString);

        // COnvert Min String to float
        minLatFloat = atof(minLatString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLat = degLatInt + (minLatFloat / 60);
        Serial.print("Google Map Latitude: ");
        Serial.println(googleMapsLat, 4);

        //////////// Longitude /////////////
        // Convert NMEA Longitude to String
        dtostrf(GPS.longitude, 8, 4, long_str); //convert GPS.latitude from float to String. 8 - means 9 characters long ; 4 - means 4 decimal point

        // Get Degree substring from latitude String
        strncpy(degLongString, long_str, 3); // Get Degree from Full Latitude String. Example 10141.91699 - Get 141

        // Get Minutes substring from latitude String
        char* minLongString = long_str + 3; // Move pointer up 3 position. Example 10141.9169 will move to 41.7799

        // Convert Deg String to int
        degLongInt = atoi(degLongString);

        // COnvert Min String to float
        minLongFloat = atof(minLongString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLong = degLongInt + (minLongFloat / 60);
        Serial.print("Google Map Longitude: ");
        Serial.println(googleMapsLong, 4);

        Serial.print("Speed (KM): "); Serial.println(GPS.speed * 1.85);
      }
   }
}

```

# Answer
> 1 votes
I'm working on the same project (with the same hardware) and I have an identical problem. Seems like an HTTP request blows up your serial monitor, but is not true in my view. In fact, if you use the TinyGPS++ library will not have this problem anymore. Take as reference the GsmWebClient example, you can add a few lines of code.

This is all you need for parse with tinyGPS:

```
#include <AltSoftSerial.h>

#include <TinyGPS++.h>

TinyGPSPlus gps;

AltSoftSerial ss;

//Add this to your sketch, in loop() or setup()

ss.begin(9600);

while (ss.available() > 0)

    if (gps.encode(ss.read())) {
        gps.location.lat(); //return latitude as a double
        gps.location.lng(); //return longitude as a double
}

```

---
Tags: arduino-uno, shields, gsm
---


title: Lessons 2: Spaceship interface

text:
# Question
Title: Lessons 2: Spaceship interface
I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.

1. Why we need to add 10kOm resistors after wire to 2 pin?
2. Why we need to add resistors after LED?
3. And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

# Answer
> Why we need to add 10kOm resistors after wire to 2 pin?

Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left *floating*. When floating, the input isn't reliable.

To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.

The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.

> Why we need to add resistors after LED?

An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.

Because the LED has *some* resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.

> And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

If you look at an Arduino board, it will say `DIGITAL (PWM~)`. That `(PWM~)` means that any pins with the "~" symbol are *PWM* pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.

> *http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg*

More explanation for PWM here: Arduino docs, an answer \[of mine\]
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: How much current and voltage has my resistor + LED
I have a very simple circuit: 5v -\> LED (5mm, forward voltage of 2 V and max. current of 20mA) -\> 1k ohm resistor -\> GND.

I want to know how much current is flowing in my circuit. I am using this formula:

U = R x I

Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.

So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V.

Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).

Thank you helping me with this basic calculus.

# Answer
The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.

If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the µCurrent uses, and it's essentially the defacto gold standard for measuring current in small circuits.
> 0 votes

---
Tags: current, resistor
---


# Question
Title: Source power with 2 V and LED with forward voltage of 2 V
I have a source power with 2 V and 100mA. I have an LED that has a forward voltage of 2 V and a max current of 20mA.

Should I use a resistor to reduce the current? I see many formulas in the internet saying the the resistor value should be:

(Source Voltage - LED forwared voltage)/LED max current

This formula always worked fine for me, but now that I have a 2 V source power this formula tells me that the resistor should be 0 ohm. Of course this would damage my LED cause the 100mA provided by my source power is way above the 20mA current limit of the lED.

# Answer
No, it would not damage your led. The forward voltage of a led is, the voltage at which the led 'conducts' the maximum current it can handle. Since diodes have a (exponential) curve, the current though a diode depends on the voltage across it.

So if you give the led 2V, it will use only 20mA. However if the voltage goes to e.g. 2.1V the current might be 25mA (since the curve is exponential), which is a bit too high, and will reduce the leds lifespan.

So for safely I'd add some resistors. E.g. a 10Ohm resistor will limit the current to 20mA max, as long as the voltage doesn't go over 2.2V

PS note that led Christmas lights use the same method to limit current, without a single resistor. I have here a 24v string of leds, grouped into 10 leds connected in series. So the voltage across each led is 2.4V. They are white leds, so they probably have a forward voltage of around 3.2v. But since they only get 2.4v, they will probably use only 5mA or less.
> 2 votes

# Answer
You most likely will not be able to use that power supply with that LED properly. The resistance graph of an diode is quite peculiar.

As you can see, there isn't a "hard" forward voltage, but rather a smooth curve that changes depending on what current is passing through the diode. You can try to use a value of, say 1.95V for the LED, but then you won't pass the same amount of current that you used in your calculations.

Extended reading: Load line (Wikipedia)
> 1 votes

---
Tags: led, resistor
---


# Question
Title: Lighting 5 leds...the last one lit is always dim
I have a simple project with a close deadline.

I am trying to light up 5 LEDs as part of the project. The first 4 light up in sequence fine, and if I light up just the last one it lights up fine, but if all 5 are lit at once the very last LED is very dim. I swapped out cables, the pin on the Arduino, resistor, LED.

What would explain that? Input amperage? Too strong a resistor?

I have a 330 ohm resistor in between each LED and ground. I am using one of the neat resistors from SparkFun that packages up the 5 330 ohm resistors together, with a common ground wire. I bought two and tried swapping it out with no change.

https://i.stack.imgur.com/QZ4qU.jpg

Here is my code:

```
/* Blink without Delay
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

const int startButtonPin = 6;
const int reedSwitchPin = 7;
const int ledPins[] = {8,9,10,11,13};
const int numLeds = 5;
const long interval = 1000;           // interval at which to blink (milliseconds)
const int revolutionsPerStage = 15;

int debounceDelay = 500; // for switches--interval to ignore short button presses/reed switch open/close
long lastDebounce = 0;
int buttonState = LOW;
int mapStage = 0;

unsigned long previousMillis = 0;        // will store last time LED was updated

void setup() {
  // set pin modes
  for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }
  pinMode(startButtonPin, INPUT);
  pinMode(reedSwitchPin,INPUT);

  digitalWrite(reedSwitchPin,HIGH); // activate the pull-up resistor
}

// Main program loop
void loop()
{
  buttonState = digitalRead(startButtonPin);
  //digitalWrite(8,HIGH);

  // wait for button press to begin program proper. we won't get back to this state except on first boot or if program finishes
  if (buttonState == HIGH) {
      digitalWrite(8,HIGH);
      chasingLEDs();
      //trackProgress();
  }
}

void trackProgress() {
  int blinkState = LOW;
  unsigned long currentMillis = millis();
  unsigned int numRevolutions = 0;

  do {
    digitalWrite(ledPins[mapStage], HIGH);

    // blink the current goal LED at constant interval specified earlier
    if(currentMillis - previousMillis >= interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
      blinkState = !blinkState;
      digitalWrite(ledPins[mapStage], blinkState);
    }
  } while (mapStage < numLeds);
}

// perform a simple welcome sequence to indicate we are ready to start pedalling
void chasingLEDs() {
   // turn LEDs on in sequence, then back off
   for (int i = 0; i < numLeds; i++){
     digitalWrite(ledPins[i], HIGH);
     delay(333);
   }

   for (int j = numLeds; j > 0; j--) {
     digitalWrite(ledPins[j], LOW);
     delay(333);
   }

   // flash the LEDs twice
   for (int k = 0; k < 2; k++) {
     for (int l = 0; l < numLeds; l++) {
         digitalWrite(ledPins[l], HIGH);
     }
     delay(500);
     for (int m = 0; m < numLeds; m++) {
         digitalWrite(ledPins[m], LOW);
     }
   }
}

```

# Answer
> 0 votes
I found the problem, it was a bug in my code. I had found code to read the array size online but it was off by 1.

Instead of:

```
for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }

```

When I changed it to thisPin \< numLeds, it worked correctly. The last pin was simply set to be an input pin instead of an output pin.

---
Tags: arduino-uno, led, resistor
---


title: How does an analog input pin work?

text:
# Question
Title: How does an analog input pin work?
I have a potentiometer of 10k and I connected it this way:

5v -\> potentiometer -\> analog input pin of Arduino

When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:

U = 5000 x 0.0000001

U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.

I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?

# Answer
The potentiometer and the internal resistance form a voltage divider. The voltage created by this voltage divider is essentially indistinguishable from 5V regardless of what the pot is set to because the internal resistance is so high.

What you want to do is to create an *external* voltage divider that will cause the voltage to vary full scale between 5V and 0V. You do so by connecting one end of the pot to 5V and the other end to 0V, and drawing the voltage from the wiper.
> 1 votes

---
Tags: current
---


# Question
Title: Efficient algorithm/data structure to calculate moving averages
Currently I am developing a graphic LCD system to display temperatures, flows, voltages, power and energy in a heat pump system. The use of a graphic LCD means that half of my SRAM and ~75% of my flash have been used up by a screen buffer and strings.

I am currently displaying min/max/average figures for energy At midnight when the daily figure resets, the system checks if the consumption for the day is above or below the previous minimum or maximum, and stores the value. The average is calculated by dividing the cumulative energy consumption by the number of days.

I would like to display the daily average over the last week and month (4 weeks for simplicity) i.e. a rolling average. Currently this involves maintaining an array of values for the last 28 days and calculating an average over the whole array for monthly and last 7 days for weekly.

Initially I was doing this using an array of floats (as the energy is in the form "12.12kWh"), but this was using 28 * 4 bytes = 112 bytes (5.4% of SRAM). I don't mind having only a single decimal point of resolution, so I changed to using uint16\_t and multiplying the figure by 100. This means that 12.12 is represented as 1212, and I divide by 100 for display purposes.

The size of the array is now down to 56 bytes (much better!).

There is no trivial way to reduce the figure down to a uint8\_t that I can see. I could tolerate the loss of a decimal place ("12.1kWh" instead of "12.12kWh"), but consumption is frequently higher than 25.5kWh (255 being the highest value represented by a 8-bit unsigned integer). Consumption has never been below 10.0kWh or above 35.0kWh, so conceivably I could subtract 10 from the stored figures, but I know that one day we will exceed these limits.

I then tested code to pack 9-bit values into an array. This gives a range of 0-51.2kWh and uses 32 bytes in total. However, accessing an array like this is pretty slow, especially when you have to iterate over all values to calculate an average.

So my question is - is there a more efficient way of calculating a moving average with three windows - lifetime, 28 days and 7 days? Efficiency means smaller in terms of SRAM usage, but without the penalty of huge code. Can I avoid storing all values?

# Answer
If your data has low standard deviation, then one method would be to sum values over the window, and then keep subtracting the mean from the sum, while adding the new value.

This would work well if there are *no outliers*, thereby leading to the aggregate error tending to zero over time.

```
//Pseudocode

count=0
while new_reading and count<7:
    sum += new_reading        //Calculate the sum of first 7 values
    count++

while new_reading:            //Loop till new readings available
    avg = sum / 7             //Calculate average
    sum -= avg                //Subtract average from sum
    sum += new_reading        //Add next reading to sum
    print avg

```
> 3 votes

# Answer
you can use a different method, you keep the current average and then do

```
average = (weight1*average+weight2*new_value)/(weight1+weight2);

```

it's not a true rolling average and has different semantics, but it may fit your needs nonetheless

for a more efficient calculation method for your 9 bits per value solution you could keep the 8 highest bits of the values in an array and separate out the least significant bits:

```
uint8_t[28] highbits;
uint32_t lowbits;

```

to set a value you need to split it out

```
void getvalue(uint8_t index, uint16_t value){
    highbits[index] = value>>1;
    uint32_t flag = (value & 1)<<index;
    highbits|=flag;
    highbits&=~flag;
}

```

resulting in 2 shifts an AND and an OR and a not

to calculate the average you can use various bit tricks to speed it up:

```
uint16_t getAverage(){
    uint16_t sum=0;
    for(uint8_t i=0;i<28;i++){
        sum+=highbits[i];
    }
    sum<<=1;//multiply by 2 after the loop
    sum+=bitcount(lowbits);
    return sum/28;
}

```

you can use an efficient parallel bitcount for the `bitcount()`
> 2 votes

# Answer
How about only storing the difference from the previous value? In electronics there is a similar concept called Delta Sigma converter, which is used for DA/AD converters. It relies on the fact that the previous measurement is reasonably near the current one.
> 1 votes

# Answer
Why couldn't you just add the values together as soon as you obtain them. So what I mean is you get the value for day 1, you divide it by 1 and store it and the 1 somewhere. Then you multiply the 1 by the value and add it to the next value and divide them both by 2.

Doing this method would create a rolling average with two or three variable as I can think of. I would write some code but I am new to stackexchange so please bear with me.
> 0 votes

# Answer
> is there a more efficient way of calculating a moving average with ... 28 days and 7 days? ... needing to remember 27 days of history ... ?

You might get close enough storing 11 values rather than 28 values, perhaps something like:

```
// untested code
// static variables
uint16_t daily_energy[7]; // perhaps in units of 0.01 kWh ?
uint16_t weekly_energy[4]; // perhaps in units of 0.1 kWh ?

void print_week_status(){
    Serial.print( F("last week's total energy :") );
    Serial.println( weekly_energy[0] );
    int sum = 0;
    for( int i=0; i<4; i++ ){
        sum += weekly_energy[i];
    };
    Serial.print( F("Total energy over last 4 complete weeks :") );
    Serial.println( sum );
    int average_weekly_energy = sum/4;
    int average_daily_energy = average_weekly_energy/7;
    Serial.print( F("Average daily energy over last 4 weeks :") );
    Serial.println( average_daily_energy );
}
void print_day_status(){
    Serial.print( F("Yesterday's energy :") );
    Serial.println( daily_energy[0] );
    Serial.print( F("average daily energy over the last 7 complete days: ") );
    int sum = 0;
    for( int i=0; i<7; i++ ){
        sum += daily_energy[i];
    };
    int average = sum/7;
    Serial.println( average );
}

```

In other words, rather than storing every detail of every day for the last 27 days, (a) store 7 or so values of detailed daily information for the past 7 or so days, and also (b) store 4 or so "summarized" values of total or average information for each of the past 4 or so weeks.
> 0 votes

---
Tags: memory-usage, algorithm
---


title: Infrared led and sensor: how it work

text:
# Question
Title: Infrared led and sensor: how it work
I am having a difficult time to understand how an infrared sensor and led work. I have an infrared LED (like the ones you buy anywhere), does it mean that the infrared LED has the frequency os 38khz?

I know that infrared light has a wavelegnth, but does it also have a frequency?

# Answer
An infrared LED just emits its light (primarily) in the infrared range as described by this Wikipedia article. Any emitted radiated signal (including sound) has both a frequency and a wavelength. The frequency = the velocity of the signal through space divided by its wavelength (F = V / W), or vice-versa: (W = V / F). The natural frequency of light, infrared or visible is far, far higher than 38 KHz; around 4 x 10^14 Hz.

38 KHz is simply a convenient chopping frequency for switching the LED on and off so the sensor can distinguish between infrared in sunlight, for instance, which is relatively constant - from that emitted by the LED. Your circuitry would have to create the 38KHz chopping signal.
> 2 votes

---
Tags: current
---


title: Blue LED not switching off

text:
# Question
Title: Blue LED not switching off
I have a circuit with a blue led, 470ohm resistor and one IR led. I want the led to be switched off when the IR led has a digitalRead value of LOW(i move my hand over it). So I wrote the code:-

```
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); // this is the blue led
pinMode(10, INPUT);  // this is the IR sensor's O/P

}

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // first I give HIGH voltage to the blue LED

if(digitalRead(10) == LOW){  // when the voltage of the IR sensor decreases
digitalWrite(13, LOW); // the blue LED should switch off or have 0 Voltage
}

}

```

But the blue LED just dims and doesn't switch off. Thanks in advance

# Answer
> 7 votes
Every time through your loop, the LED is being set to HIGH voltage. This may or may not be followed by setting it to LOW voltage, but since the loop runs again immediately, it's immediately set back to high voltage. This happens so fast that the LED essentially "feels" half voltage and it will dim. Your code needs to be more like this...

```
void loop() {
  if(digitalRead(10) == LOW) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

```

OR... even like this...

```
void loop() {
  digitalWrite(13, digitalRead(10));
}

```

---
Tags: ir
---


# Question
Title: Infrared sensor has a frequency to activate it?
I am trying to understand 2 sensors that I have here. One says that is "infrared sensor of 38kHz" and the other is "infrared optical reflexive sensor -\> http://www.robosoftsystems.co.in/wikidocs/index.php?title=TCRT\_5000\_Reflective\_Optical\_Sensor"

I thought that infrared sensor would tell me if an infrared light is passing on it. Infrared light has a wavelenght, right? Can infrared light be emited in different frequencies? Or the frequency of infrared light is the same to all infrared lights?

# Answer
> 1 votes
The 38kHz sensor (such as the Vishay series e.g TSOP1838) are designed for use with IR remotes and IR barrier type applications. They are designed to work with IR emitters that oscillate the IR at 38Khz and additionally modulate that frequency with lower frequency pulses. The sensor (receiver) is designed to have high gain at 38Khz and demodulates the signal. The demodulated output signal pulses can be directly decoded by a microprocessor. The main benefit is reliable functioning even in disturbed ambient light thus protecting against uncontrolled output pulses.

# Answer
> 0 votes
38Khz is not the frequency of the IR light but the frequency it is pulsed on and off at, the receiver is designed to accept that frequency and reject others so as to avoid interference from sunlight etc. I see you have asked the question again in a slightly different way and received a similar answer. Infrared led and sensor: how it work

---
Tags: led
---


title: ATmega32u4 bootloader

text:
# Question
Title: ATmega32u4 bootloader
Hey all this would be my first encounter needing to burn the Arduino IDE bootloader onto a blank ATMega32u4 that I bought from Digikey.

What all do I need to buy in order to program the bootloader for that chip? In the manual for the 32u4 it says it comes with a bootloader but I'm guessing its not the arduino bootloader?

Is the pinout for the ISP all that I would need in order to upload the Arduino bootloader?

I've seen this post:

but I wont be using the through-hole design.. its going to be the surface mount SMD kind so i wouldn't be able to put that on a breadboard.

So would it be as simple as breaking out the ISP pins on the 32u4 and just hooking those up to a Arduino Duemilanove board even if its not the same ATmega chip (As in copying the atmega32u4 arduino to the Duemilanove and then transferring that to the 32u4?)?

# Answer
> 2 votes
The ATmega32U4 already comes programmed with a bootloader that allows programming via USB; once you've added the basic hardware for a USB connection you should be able to use AVRDUDE, FLIP, etc. to upload firmware to the device.

Having said that, putting an ISP connection as per AVR042 is highly recommended regardless.

---
Tags: avr, bootloader
---


# Question
Title: serial char read first letter if it is ";" print char without fists letter
I'm working on a project and I need to print serial to a LCD but only if the first letter of the serial is ":"

I have the serial being stored in a char and a if statement reading the first letter of the char to see if it is ":" From there I can't get it to print to the LCD without the first letter. I also don't know how to clear the char.

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

char inData[20];
char inChar;
byte index = 0;

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

void loop()
{
  while(Serial.available() > 0)
  {
      if(index < 19)
      {
      inChar = Serial.read();
      inData[index] = inChar;
      index++;
      inData[index] = '\0';
  }
 if(inData[0] == ':') {
   lcd.print(inData);
   }

  }
 }

```

# Answer
Tell it to print starting from the second character.

```
lcd.print(inData + 1);

```
> 1 votes

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


# Question
Title: Arduino server to read from multiple clients
Socket programming question here.

My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).

My Android client class works when 1 user connects and sends commands to my Arduino server class.

I want to make my program friendly to many users at the same time. My server will only read in values from 1 connected client at a time.

After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.

The Arduino library that I've decided to use for this specific issue is `protothreads`. Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands. Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.

Now for my question,

> How exactly can I allow my Arduino server to constantly listen for incoming messages from more than 1 client device?

Or is there something I can do on the client side that would make this communication possible?

A lot of work is handled by my Wifly Module. I was able to telnet in and set my ipaddress/port#/etc.. Anything sent over IP goes straight through my Module and straight to my arduino.

My Client Code:

My Server:

```
WiFlySerial wifi(rxPin ,txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  //Serial.println("I'm in the LOOP!!");
  androidLed();
  serialLed();

}

void androidLed()
{
  if(wifi.available() > 0){
    data = wifi.read();
    Serial.println(wifi.getDeviceStatus());
    Serial.println(data);
}
}

```

# Answer
*Without knowing your exact implementation details...*

You should be OK as long as you don't have *multiple* clients connected at the same time. You may think that there are multiple clients connected to your server, but the connection is closed after the resource is obtained by the client over a protocol.\*

The standard flow of a server on Arduino:

1. A client connects to the Arduino.
2. The Arduino code realizes this connection and reads the data provided by the client.
3. The Arduino then sends some data back to the client.
4. The Arduino closes the connection and waits for another client to connect.

This happens relatively fast so multiple people can connect.

If you call a function like `.close();` after you send data to your client, you should be okay. **If you don't, redesign your code to have this element** (avoid loops and blocking functions) and make sure to have your client reconnect every time it sends a command.

I wouldn't mess with this and Protothreads because I'm not sure that the Arduino hardware is designed to be able to handle multiple connections at the same time. <sup>*\[Citation needed\]*</sup>
> 6 votes

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


# Question
Title: Trouble reading from multiple analog ports
So I'm trying to read 4 different analog values and store each one to a variable. I imagine doing this by first initializing the ADC registers and each time it enters the ADC ISR checking which port it read from and saving it to the corresponding variable. Then setting the ADMUX to the next ADC port and repeating the whole process. Unfortunately something goes wonky and I just can't figure out what it is. If I get rid of the switch case and just read from one port it all works fine, but if I put the switch case back in and try to cycle through them it stops working. Please ignore the rest of code as this is not complete. I just included everything I could. Eventually this will take in 4 values. Then use them for error checking and a PID loop.

Thanks for any help!

```
/*
 * Throttle_by_Wire.c
 *
 * Basic throttle by wire controller
 * for the 2015 Formula Hybrid car
 *
 *  Created on: Nov 24, 2014
 *  Author: Austin R. Bartz
 *
 *  Pin Connections:
 *      PB2 - Motor Speed (Enable pin) (PWM)
 *      PB4 - Direction control (Counter-Clockwise)
 *      PB5 - Direction control (Clockwise)
 *      PC0 - Throttle Pedal Sensor A (TPA) (Shallower Slope)
 *      PC1 - Throttle Pedal Sensor B (TPB) (Steeper Slope)
 *      PC2 - Throttle Valve Sensor A (TPSA) (Negative Slope)
 *      PC3 - Throttle Valve Sensor B (TPSB) (Positive Slope)
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include <stdlib.h>

uint16_t TPA = 0;
uint16_t TPB = 0;
uint16_t TPSA = 0;
uint16_t TPSB = 0;
uint16_t analogpin = 0;

long map(long x, long in_min, long in_max, long out_min, long out_max);

int main(void)
{
    //Configure ADC for single shot conversion
    ADMUX |= (1<<REFS0);
    ADCSRA = (1<<ADEN)|(1<<ADSC)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
    DIDR0 = (1<<ADC4D)|(1<<ADC3D)|(1<<ADC2D)|(1<<ADC1D)|(1<<ADC0D);
    //Configure timer/counter1 for FastPWM
    TCCR1A = (1<<COM1B1)|(1<<WGM11)|(1<<WGM10);
    TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS10);
    OCR1A = 800;    //20kHz
    //Set motor control pins as outputs
    DDRB = (1<<PB2)|(1<<PB4)|(1<<PB5);
    PORTB |= (1<<PB5);
    //Enable global variables and interrupts
    sei();

    while(1)
    {
        //Control PWM % to motor
        OCR1B = map(TPA, 0, 1023, 0, OCR1A);
    }
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

ISR(ADC_vect)
{
    //Save current conversion's ADC value
    analogpin = ADMUX & 0b00001111;
    switch (analogpin)
    {
    case 0:
        TPA = ADCW;
        //Increment ADC port to ADC1
        ADMUX |= (1<<MUX0);
        break;
    case 1:
        TPB = ADCW;
        //Increment ADC port ADC2
        ADMUX &= ~0b00001111;
        ADMUX |= (1<<MUX1);
        break;
    case 2:
        TPSA = ADCW;
        //Increment ADC port to ADC3
        ADMUX &= 0b00001111;
        ADMUX = (1<<MUX0)|(1<<MUX1);
        break;
    case 3:
        TPSB = ADCW;
        //Reset ADC Port to ADC0
        ADMUX &= ~0b00001111;
        break;
    }
    //Start next conversion
    ADCSRA |= (1<<ADSC);
}

```

# Answer
> 1 votes
Case 2 is missing the ~ and does not clear off the low 4 bits

> ADMUX &= 0b00001111;

should be this to clear off the MUX selection bits:

```
ADMUX &= ~0b00001111;

```

Also, you have no default case. I would agree that by design the bits can only contain the values 0-3, but what happens if it ends up 4?

The bit manipulation is hard to follow. I would implement like this:

```
ISR(ADC_vect) {
  uint8_t nextMux;

  //Save current conversion's ADC value
  analogpin = ADMUX & 0b00001111;
  switch (analogpin) {
    case 0:
      TPA = ADCW;
      nextMux = (1<<MUX0);
      break;
    case 1:
      TPB = ADCW;
      nextMux = (1<<MUX1);
      break;
    case 2:
      TPSA = ADCW;
      nextMux = (1<<MUX0)|(1<<MUX1);
      break;
    case 3:
      TPSB = ADCW;
    default:
      nextMux = 0;
  }
  // set mux for next conversion
  ADMUX &= 0b11110000;
  ADMUX |= nextMux;

  //Start next conversion
  ADCSRA |= (1<<ADSC);

  return;
}

```

I like the consistent pattern of this because it makes errors easy to see. With respect to code space, a few bytes should be saved. Execution time wise, it adds one |= to the case 3.

---
Tags: motor, analogread, arduino-uno-smd, eclipse, pid
---


# Question
Title: Arduino Mega 2560 RFID Serial Communication
I have an RFID reader: http://img.tradeindia.com/fp/1/641/264.jpg

Something like above along with ITEAD TFT shield & GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.

Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.

Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:

```
#define __AVR__
#include <UTFT.h>

// Declare which fonts we will be using
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
UTFT myGLCD(ITDB24,59,58,57,56);
String myString = "";

void setup() {
   Serial3.begin(9600);
   myGLCD.InitLCD();
   myGLCD.clrScr();
}

void loop() {
  myGLCD.setFont(BigFont);
  if (Serial3.available()) {
    int inByte = Serial3.read();
     myString += String(inByte);
    }
    if(myString.length() == 10)
      myGLCD.print(myString, CENTER, 0);
}

```

TFT Screen output:

1310494848

Serial Monitor Output: non printable junk character.

The value is incorrect, I am pretty sure, what am I doing wrong?

I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.

BTW what is the functionality of http://arduino.cc/en/Tutorial/SoftwareSerialExample?

How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?

# Answer
First of all, try testing 1 functionality at a time to isolate the issue. Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.

When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.

This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega
> 1 votes

# Answer
i think the RFID is a other baud rate e.g 115200.. i dont know the device, i dont know if this is the problem, but test it :)
> -1 votes

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


# Question
Title: Can a DC motor use more current than its datasheet?
I am using small dc motors connected to the 5V of the arduino which is known to provide 200mA without damaging it.

The motor I am using is a very common one found in toys -\> https://www.sparkfun.com/datasheets/Robotics/ROB-09608.jpg

As I see the maximum current of this motor is 170mA. Does it mean that the motor will not drain more current than that or it means that I need to use a resistor in series with my 5V in order to make sure the current will not pass 170mA?

# Answer
YES (typically resulting in melting the coils). The current used by standard or brushless motors is related to the voltage applied and the load applied. As you approach the load limit, current rises over the limit. There are many ways to control this but controlling the load is the easiest way. DO NOT run the motor through the Arduino even if you think it will be under the 200mA limit. Motors produce a lot of spikes and back-flow.

Here's a tutorial on safely running a motor and controlling the speed: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview
> 1 votes

---
Tags: motor
---


title: Arduino Mega2560 Hardware ID

text:
# Question
Title: Arduino Mega2560 Hardware ID
Do all Arduino Mega2560's have the same VID/PID identification numbers when seen by a PC as a device? I am planning on designing I specific driver to work with the 2560 and wondering if I will be able to use the same driver for multiple Arduino. Can anyone confirm this? Thanks!

# Answer
VIP/PID is realized by Atmega16u2 driver which implements USB device driver. Probably all revisions of \*Arduino Atmega2560\*s has implicitely the same VID/PID. Each piece has unique serial number. But you can upload own firmware into 16u2 to modify USB as you wish (ideally using LUFA library). It's clean solution for production hardware because you cannot use Arduino VID because of USB rules.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Extremely cheap "Arduino" for single tasks?
I have been thinking of a million things to do with my Arduino, but those things are extremely simple and it would leave my Arduino as a $25 waste.

For example, programming Arduino to control my living room lights with my smartphone ... I was thinking of connecting the Arduino in the wall, onto the light switch wires. I am looking for a "permanent" solution, but I figure this would leave me with a $25 waste of circuitry inside my wall.

Are there any "Arduino" types of electronics that perhaps have many less ports, JUST enough to get a single task done?

# Answer
Digispark comes to mind, or any of the ATTiny breakout boards at Tindie. Or, make your own PCBs, I just now finished soldering a few ATMega328p circuits to boards I designed. Microcontroller is $1.50, PCBs range from $2 to $8 each, time is "free."

Also consider "compatible with" designs; while you're not directly supporting the ecosystem, if you've already paid full price once and your conscience is clear, eBay has plenty.
> 6 votes

# Answer
You can embed a bootloaded ATMega328 (or any of the other compatible ATMega processors) http://arduino.cc/en/pmwiki.php?n=Main/Standalone in your project. That way, you will only need the processor and a couple of components, setting you back only a couple of dollars *and* saving quite a lot of space:

http://arduino.cc/en/pmwiki.php?n=Main/Standalone

If that is one bridge to far, you can have a look at the Arduino Pro or Arduino Pro Mini. Those boards are complete boards, only smaller and cheaper, and specifically designed for a more definitive use in projects.

If you need even more space and cost reduction, you can switch to a stand-alone ATTiny processor. The better models of those can also contain an Arduino program. *Instructables* has this great tutorial that shows you how to use an ATTiny85 or ATTiny45 as a lightweight 'Arduino'.

Recently, I have tried to use an ATTiny13A for a project, but that one only has 1KB of flash memory, which leaves you with hardly any space for the Arduino bootloader, let alone your program, so therefor I chose to program it directly using AVR Studio, at which point I think you cannot in any way call it an Arduino project anymore. :) Still, it's not that different. You only miss out on some of the library functions, and the implied application loop.
> 3 votes

# Answer
This is a typical scenario for an Arduino Uno board: you buy one and use it for prototyping your project. Once done, you design your own PCB, as small as possible, connecting only the required wires to the ATMega328p.

For the next project, you buy another ATMega328p (just the MCU), plug it on the Uno and start again.
> 2 votes

# Answer
I've had the same exact problem.

Since I like developing using the Arduino IDE I've created an how to assemble a board using just Thru Hole Components to replace the Official board.

Please visit the following link for further information http://jpralves.net/cseduino All the components will cost about 5 USD.
> 2 votes

# Answer
There are good instructions here:

http://arduino.cc/en/Main/Standalone

and here:

http://arduino.cc/en/Tutorial/ArduinoToBreadboard

Alternatively you can go for an *Arduino mini* http://arduino.cc/en/Main/ArduinoBoardMini or a corresponding Chinese clone.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Saving data in a globally declared float array
I'm trying to send 60 float values via serial. Numbers are provided by an accelerometer and saved in a 240 bytes-long array. The array is sent to a function and these values are then copied in a structure.

**The problem** The content of the array is still correct when the function is called. Then, when I copy it in the structure, something wrong happens and data are modified after the 26th float.

Where does the modification of an array of floats take place?

```
void sendBuffAcc(float a[])
{
  int stepCont = 1;

  // Prints the content of the globally defined array buffXAccToSend
  Serial.println();
  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("    ");
    Serial.println(buffXAccToSend[i]);
  }
  Serial.println();

  MyShortCommand * pMyCmdShort = (MyShortCommand *)(&bufferAcc[sizeof(MyControlHdr)]);

  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("| Global Array:");
    Serial.println(buffXAccToSend[i]);

    numFilterValuesToSend++;

    pMyCmdShort->cmd = accValuesID;
    pMyCmdShort->param1 = a[i];
    pMyCmdShort->param2 = 0;
    pMyCmdShort->param3 = 0;
    pMyCmdShort->param4 = 0;

    Serial.print("|   Param: ");
    Serial.print(pMyCmdShort->param1);
    Serial.print("|   Array:");
    Serial.println(a[i]);

    // Move the pointer to save data in next positions
    pMyCmdShort++;
  }
  stepCont++;
 }
 storeAccData = false;
 contBuffAcc=1;
}

```

First, the content of the global array `buffXAccToSend` is printed via serial, then the i-th elements of a\[i\] and the value assigned to the pMyCmdShort-\>param1. This is the output:

```
val: 0    -0.00
val: 1    -0.00
val: 2    0.01
val: 3    -0.01
val: 4    0.04
val: 5    0.00
val: 6    0.01
val: 7    0.03
val: 8    0.01
val: 9    -0.00
val: 10    0.00
val: 11    -0.01
val: 12    -0.00
val: 13    0.01
val: 14    -0.02
val: 15    0.03
val: 16    0.00
val: 17    0.02
val: 18    -0.01
val: 19    0.00
val: 20    0.00
val: 21    -0.00
val: 22    -0.01
val: 23    -0.01
val: 24    0.01
val: 25    0.01
val: 26    -0.00
val: 27    0.03
val: 28    -0.01
val: 29    -0.00
val: 30    0.04
val: 31    -0.01
val: 32    0.01

val: 0| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 1| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 2| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 3| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 4| Global Array: 0.02|  Param: 0.02|  Array: 0.02
val: 5| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 6| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 7| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 8| Global Array: 0.04|  Param: 0.04|  Array: 0.04
val: 9| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 10| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 11| Global Array: -0.00|  Param: -0.00|  Array: -0.00
val: 12| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 13| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 14| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 15| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 16| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 17| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 18| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 19| Global Array: 0.03|  Param: 0.03|  Array: 0.03
val: 20| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 21| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 22| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 23| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 24| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 25| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 26| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 27| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 28| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 29| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 30| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 31| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 32| Global Array: 0.00|  Param: 0.00|  Array: 0.00

```

This is the output of avr-size:

```
   text    data     bss     dec     hex
  55828    3906    2978   62712    f4f8

```

Is it a memory related problem?

# Answer
The ATmega328P has 2kiB of SRAM. Your program uses almost 3kiB. Move strings and constant values into flash.
> 2 votes

---
Tags: serial, arduino-mega, float
---


title: lcd.print and 2D arrays

text:
# Question
Title: lcd.print and 2D arrays
Click here to see my program running

I have created a 2D array (see my full code below), and each row contains one state of a battery here is a schematic :

```
row [0] : "▯▢▢▷" // this row represents an empty AAA battery
row [1] : "▮▩▢▷"
row [2] : "▮▩▩▷"
row [3] : "▮▩▩ ▶"  // this row represents a Full AAA battery

```

Each "▩" character is a custom made character with this function:

```
lcd.createChar(0, customLcdfont_squareONE);

```

As you saw in my video it works at the end, but it's absolutely not the way I want it to work. The code that works is a mess!

**I think the problem is that the Raw n°1 (\[0\]) starts with a 0, (try it out it's very strange). If we replace**

```
char batteryFonts [10][5] = {
  { 0, 1, 1, 2 }, // you see { this "0", 1, 1, 2 }, is a problem I think
  { 3, 1, 1, 2 },
  {etc}, }
lcd.print( batteryFonts[0]);  // this sentence does not work

```

**with**

```
"char batteryFonts [10][5]={{ 4, 1, 1, 2 }, // 4 or what ever you want
  {etc},
  {etc}, }
 lcd.print( batteryFonts[0]);  // this sentence behind does work, but only with a row that does not start with a 0. Why?

```

It works!

Here is my full code. Just connect the pins 12, 13, 7, 4, 3, 2 to the LCD.

```
//This is a simple program that charges alkaline batteries
//Copyleft
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 13, 7, 4, 3, 2); // why pin 13 and not 12 ? because I love the led attached to it <3

// the empty battery - end
byte customLcdfont_A [8] = { // B stand for "Binary" and then the pixel ...
B01111,
B11000,
B10101,
B10100,
B10100,
B10100,
B11000,
B01111

// the empty battery body with fancy graphics enabled

};
byte customLcdfont_B [8] = { // B stand for "Binary" and then the pixel ...
B11111,
B00000,
B11001,
B00000,
B00000,
B00000,
B00000,
B11111
};

// the empty battery + end

byte customLcdfont_C [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B00100,
B10111,
B00101,
B00111,
B00111,
B00100,
B11100
};

// the full battery - end

byte customLcdfont_D [8] = { // B stand for "Binary" and then the pixel ...
B1111,
B11111,
B10110,
B10111,
B10111,
B10111,
B11111,
B1111
};

// the FULL battery + end
byte customLcdfont_E [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B11100,
B01111,
B11101,
B11111,
B11111,
B11100,
B11100
};

// the full battery  body

byte customLcdfont_F [8] = {
B11111,
B11111,
B00110,
B11111,
B11111,
B11111,
B11111,
B11111
};

// the 1/3 battery body

byte customLcdfont_G [8] = {
B11111,
B11000,
B00001,
B11000,
B11000,
B11000,
B11000,
B11111
};
// the 2/3 battery body

byte customLcdfont_H [8] = {
B11111,
B11110,
B00111,
B11110,
B11110,
B11110,
B11110,
B11111
};

/**************************************************************************/
void setup() {
  int i = 0 ;
  // initialize serial communications at 9600 bps:
  lcd.createChar(0, customLcdfont_A);
  lcd.createChar(1, customLcdfont_B);
  lcd.createChar(2, customLcdfont_C);
  lcd.createChar(3, customLcdfont_D);
  lcd.createChar(4, customLcdfont_E);
  lcd.createChar(5, customLcdfont_F);
  lcd.createChar(6, customLcdfont_G);
  lcd.createChar(7, customLcdfont_H);

  lcd.begin(16, 2);

// WATCH HERE IS THE PROBLEM !!!!

//the char table behind creates my different battery states as shown in the video ;)

 char batteryFonts [10][5]={

 { 0, 1, 1, 2 }, // this is an empty one  f%*# this does not work !!!
 { 3, 1, 1, 2 },
 { 3, 6, 1, 2 },
 { 3, 7, 1, 2 },// this is a 50 % full charged battery !

 { 3, 5, 1, 2 },
 { 3, 5, 6, 2 },
 { 3, 5, 7, 2 },
 { 3, 5, 5, 2 },
 { 3, 5, 5, 4 },// this is nice full one
 };

 // this sentence behind does not work !!! but only with the raw [0]

 lcd.print( batteryFonts[0]);    // I F***ing want this to display the first raw !!!!
 lcd.setCursor(0,1 );

  lcd.print(" not working ");
 lcd.setCursor(0,0 );

        delay(9300); // this make a short pause  for us so that we can see the result
lcd.setCursor(0,1 );

  lcd.print("    working      ");
 lcd.setCursor(0,0 );
      for (i=0; i=10 ; i+=1 ){
       delay(300);

  lcd.setCursor(6,0 );

  lcd.write(byte(0));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(700); //  batterry 0/8 empty aka discharged

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(1000); //batterry 1 /8

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(6)); lcd.write(byte(1)); lcd.write(byte(2));
   delay(1000);//batterry 2 /8

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(7)); lcd.write(byte(1)); lcd.write(byte(2)); //batery 3 /8

  delay(1000);

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(5)); lcd.write(byte(1)); lcd.write(byte(2));
  delay(1000); //batery 4 /8

  lcd.setCursor(6,0 );
        lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(6));   lcd.write(byte(2));
  delay(1000); //batery 5 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(7));  lcd.write(byte(2));
        delay(1000); //batery 6 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(5));  lcd.write(byte(2));
      delay(1000); //batery 7 /8

  lcd.setCursor(6,0 );
    lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(5));    lcd.write(byte(4)); //batery 8 /8

    delay(1000);

      }

    lcd.setCursor(15, 1);

    delay(115000);

}

/**************************************************************************/
void loop() {

//This is not interesting here
  lcd.print(" ~ The end of the code ... thank you for reading ;) ~ ");

}

```

# Answer
> 2 votes
You are correct; in C a NUL (0x00) is used to indicate the end of a `char*`. You will need to use `LiquidCrystal::write()` in order to send the character data byte by byte instead of depending on `LiquidCrystal::print()` to handle it.

Also, consider moving all of that static data into flash; you're going to need to handle it manually so you may as well do it right in the first place.

---
Tags: arduino-uno, programming, library, lcd
---


# Question
Title: How to prepare data structures and classes?
How can I port these structures to arduino ide, I also get error when I define pointers

```
// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';
  delete bar;
  delete[] baz;
  return 0;
}

```

In CPP shell it works

I try to put it like this

```
class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };

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

}

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

}

```

I get an error

```
sketch_nov27a.ino:10:3: error: 'foo' does not name a type
sketch_nov27a.ino:11:3: error: 'bar' does not name a type
sketch_nov27a.ino:12:3: error: 'baz' does not name a type
Error compiling.

```

# Answer
> 2 votes
The problem is that the lines saying `foo = ...` etc. are assignment operations. C++ lets you declare and immediately initialise variables at global scope, but after that you can only assign to them inside a function. In your original program, all your declarations/assignments were inside `main()`, which is why it worked there.

For your Arduino program, you could change the assignments to initialisations instead (in global scope):

```
Rectangle obj (3, 4);
Rectangle * foo = &obj;
Rectangle * bar = new Rectangle (5, 6);
Rectangle * baz = new Rectangle[2] { {2,5}, {3,6} };

```

Alternatively, you could leave the declarations in global scope and move the assignments into `setup()`:

```
Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;

void setup() {
    foo = &obj;
    bar = new Rectangle (5, 6);
    baz = new Rectangle[2] { {2,5}, {3,6} };
}

```

# Answer
> 0 votes
You put a bunch of code in a place where you can't have it. Move the assignments into a function body.

---
Tags: c++, arduino-ide, class
---


# Question
Title: Determine difference between 3.3V and 5V shields
How do you determine if an Arduino shield uses 3.3V or 5V on their pins?

Previously, I thought all Arduino shields used 5V, since that's what most Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.

The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?

# Answer
> 1 votes
You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.

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


# Question
Title: Why is my transistor getting very hot when controlling a 12V peristalic pump?
I have followed this tutorial:

http://www.instructables.com/id/Automatically-water-your-small-indoor-plant-using-/?ALLSTEPS

Every time i try to run my circuit, My transistor gets very hot and breaks.

I have exactly the same parts as the tutorial. I have also tested the circuit with 3.3V Power supply and a diode instead of an engine, this works.

I am super thankfull for any answers.

# Answer
Measure the Current through the motor, the PN2222 can pass a maximum of 600mA. I would guess that just over half an amp would be enough for the motor but you can check what you motor is trying to pull by connecting it to 12 V direct and measure the supply current. The only thing that will make the transistor hot is excess current
> 0 votes

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


# Question
Title: Why does it say "Servo" does not name a type
```
#define pingTrig 6
#define pingEcho 7

#include

Servo myservo;

void setup()
{
pinMode(pingTrig, OUTPUT);
pinMode(pingEcho, INPUT);
myservo.attach(9);
}

void loop()
{
long duration, inches, cm;

digitalWrite(pingTrig, LOW);
digitalWrite(pingTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pingTrig, LOW);

duration = pulseIn(pingEcho, HIGH);

cm = duration / 29 / 2;

if(cm < 10 ){
myservo.write(90);
delay(100);
}else{
myservo.write(0);
}
delay(2000);
}

```

# Answer
Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:

```
#include "Servo.h"

```

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".
> 3 votes

---
Tags: servo
---


# Question
Title: Cannot communicate with Serial Monitor - Arduino Yun
I connect Arduino Yun to my Computer with WiFi. I was able to get the IP address of my Arduino Yun. However, when I try to print something. It seems to not work at all. The following code is the one that I try:

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

void loop() {
 // print labels
 Serial.print("NO FORMAT");
 delay(100);
}

```

I did not get any kind of error. However, when I open the Serial Monitor, it shows nothing at all. I try to use the same code with Arduino Uno. It works fine.

# Answer
> 3 votes
When using the Yun over wifi, you cannot user Serial, you need to use Bridge Console object. Serial is bound to the usb cable.

Give a spin to ConsoleRead example.

---
Tags: serial, arduino-yun
---


# Question
Title: Identifying a counterfeit or authentic Arduino
I would like to know how I can identify a fake or counterfeit Arduino board. For example this product, which is shown below.

I am concerned that it is cheap (about $12 when converted) and I was wondering if it is like a 'legal cheap version' or is it an unauthentic one? If it is not authentic, would it be legal to purchase it?

# Answer
It looks like an R3 Uno, but then pictures can be misleading.

However:

* Arduino is open source - anyone can make one
* Because of that there are many many "clones" of the Arduino
* A clone, as long as it's got the right circuitry (and an Arduino is incredibly simple) is as good as the "real thing".

The only problem Arduino have with clones is the use of the Arduino name and logo. IIRC they don't mind you claiming "Arduino Compatible", but trying to *be* an Arduino they don't much like.

If it's just their reference designs re-printed (which you can download for free from the Arduino Uno web page) and no further design work has been done, then although it isn't made in Italy by Arduino, it's still an Arduino.

That's the beauty / curse of open source - anyone can make one.

However, that specific one looks like it fits into the "claiming to be an Arduino" category. It uses Arduino artwork and logos, and tries to make it look like it's an Arduino made by Arduino in Italy, when in fact it isn't. Legally speaking, they are ripping off the Arduino brand. Practically speaking, since it's all open source, the actual device (assuming the components aren't counterfeit) should be perfectly fine.

If they were to change the artwork, so it didn't look quite so much like an Arduino, and had something like "Arduino Uno Compatible" on it, then it would be categorized as a clone, and would be fine - you'd know where you were standing. As it is though, the artwork on it is breaking copyright laws.

The image shown is too low quality to give much information about it, but the two big pointers that it's not made by Arduino are:

* The PCB is too blue (real Arduinos are teal)
* The polyfuse is the wrong colour (green instead of grey/gold)
> 7 votes

# Answer
No, it's a counterfeit. See here - particularly the 'components' section:
http://arduino.cc/en/Products/Counterfeit

Also, as far as I'm aware, Arduino boards are not produced in China but in Italy.
> 2 votes

---
Tags: counterfeit
---


# Question
Title: Issue with adding a library: No such file or directory
I downloaded a Library called "Morse" which I got from the Arduino website:

http://arduino.cc/en/Hacking/LibraryTutorial

(all the way at the bottom of the page there is a link called Morse.zip) And basically added the library. Then when I import the library, it is included to the sketch. However when I try verifying it, the following error message appears:

*to see the image clearer you can right click it and click on "Open image in new tab"*

Basically it says:

In file included from sketch\_nov28a.ino:1: C:\Users\Marko\Documents\Arduino\libraries\Morse/Morse.h:10:22: error: WProgram.h: No such file or directory

Now I tried reinstalling the Arduino IDE, I tried adding the library again as well as using the manual method that was stated in that first link above, and the error persists.

What I did notice was that in that second line of the error message, something caught my eye: "...\Morse/Morse.h:10:22:..." There is a forward slash!(/) Now it seems weird to me that with would happen, especially given that all the other examples I saw of this error online have a backslash (\\). This could be the problem.... but even if it is, how do I fix it? I tried going to preferences... does anyone know?

# Answer
That library is for the older version of the Arduino ide. To fix this you need to open `Morse.h` and change `WProgram.h` to `Arduino.h`.
> 1 votes

---
Tags: library, ide, debugging
---


# Question
Title: How to make Arduino communicate with MySQL?
I am trying to send data from my Arduino to my database but it seems that the process is not successfully beginning. Here is my code for Arduino:

```
#include <Process.h>
#include <Bridge.h>
int temperature;
void setup() {
  Bridge.begin();  // Initialize Bridge
}
void loop() {
  int temperature = random(0, 100);
  Process p;
  p.begin("143.248.181.36/db.php");// 143.248.181.36 address of localhost.
  p.addParameter(String(temperature));
  p.run();
  delay(5000);
}

```

I am using xampp and I put db.php inside the htcocs folder. Can anyone point out why it does not work?

# Answer
I'm not familiar with those libraries, but a quick look gives me the impression that Bridge and Process are used together to make system calls over serial connection on the host system. Based on that..

First, looking at Arduino Process Tutorial Process.begin() should call the process that you want to call. Maybe something like this:

```
p.begin("curl"); // Assuming you have curl installed on your host system
p.addParameter("http://143.248.181.36/db.php?temperature=SOMEVALUE");

```

Second, your PHP script is broken.

```
/ check connection

```

^ That comment is missing a second slash /

You should definitely get the PHP/MySQL part working standalone before attempting to integrate Arduino in the process. I'm a bit doubtful that $argv gets populated unless you're running the script from command line. If you're making a GET HTTP request (as you would with curl) you might wanna try instead

```
$temperature = $_GET['temperature'];

```

If the above works as a workaround, you should get an entry into your MySQL table if you visit the URL below with your browser.

```
"http://143.248.181.36/db.php?temperature=100"

```

In any case, get the PHP script working first in your browser. One step at a time.
> 1 votes

---
Tags: programming, arduino-yun
---


# Question
Title: Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?
Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?

# Answer
> 1 votes
Zero, Mega and Tre all have the same basic pinout layout as Uno, which provides at least physical compatibility for the pins. Sparkfun has a breakout board for the Intel Edison.

Mini, Micro & Nano obviously have a different pin layout. I would consider them mainly for projects that have challenging space requirements, since their main advantage is their small size. The Micro should be the easiest to plug'n'play (native USB COM serial). Nano is still stuck with FTDI drivers, so it's going to require separate drivers from the Uno/Mega family. And finally Mini doesn't have USB at all.

Maybe take a look at Wikipedia list of Arduino boards and compatible systems to evaluate better what suits your needs best.

---
Tags: arduino-galileo
---


title: Is there a pullup on I2C?

text:
# Question
Title: Is there a pullup on I2C?
I am using an Arduino Uno R3.

It is not clear on the schematic whether there are pullups on the A4 and A5 I2C pins.

Are there hardwired pullups or do I have to add them myself?

# Answer
There are very weak internal pullups, but they are not strong enough to be considered compliant with I2C specs. Supply your own external 2.2k-10kohm pullup resistors.
> 5 votes

# Answer
No. There are potential internal pullups, but not AFIK activated.

You can quite safely connect I²C to Raspberry P1 (3.3V).
> 0 votes

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


# Question
Title: USB mouse/keyboard passthrough feasible?
I'm looking to achieve the following:

```
USB HID Mouse (or Keyboard) -> [ Arduino device ] -> PC
                                       |
                                        `-> Internet

```

Basically, I want to connect a keyboard or mouse to an Arduino device, do some processing, send some data over the internet and then pass-through the USB data to the PC as if the Arduino wasn't even there.

My question is twofold: what hardware should I use? Right now I'm looking at the following peripherals:

Since I'm a complete neophyte when it comes to Arduino, I wanted to double-check and make sure my parts will fit together as well as work towards my goal. I was also contemplating the Arduino Leonardo (since it seems to provide mouse/keyboard out-of-the-box without reflashing the firmware), but I'm not sure I understand what that decision might entail.

Which brings me to my second question: is this feasible software-wise? I found this blog which has some information about pass-through connections, but the mouse library seems to be unfinished. I'd hate to invest 150+ dollars into a project that is doomed from the start.

Thank you!

# Answer
> 2 votes
To connect an external USB device to AVR you need **USB Host** supported on AVR side. Overhelming majority of AVR chips supports **USB device only**. There is e.g. AT90USB1287 chip exception. It even exists an **AVR USB Key 2** device which can be used instead of normal Arduino unless you want make own PCBs.

**Arduino UNO Mouse HID** emulates USB mouse internally in Arduino. Implementing is easy when you have USB device AVR chip using LUFA library. But it's not case using external mouse. On the other side you can use legacy serial mouse or PS/2 keyboard as workaround.

---
Tags: ethernet, usb, arduino-uno-smd
---


# Question
Title: Arduino to Arduino Communication using HC05
I have been working on a project for work ( I'm a waiter :/ ) I was tasked to build a food wait time display that receives input from the kitchen and echoes the time via bluetooth to another display. So that we are all on the same page I will describe what I have built and where I am stuck.

**Before I do, I would like to state that I have:**

* been planning and prototyping this thing for over a month
* googled/crawled all over the web looking for answers
* read the entire manual on the HC05 module
* Bound both of the bluetooth modules via AT commands One as Master the other as Slave

Now with that out out the way here is what I have so far:

* 2x Arduino uno R3
* 2x 16x2 LCD Display
* 2x HC05 Bluetooth Modules (1 set as Master the other as Slave & bound using AT Commands)
* 2x 10K Potentiometers for adjusting the contrast
* 3x Momentary push Button switches on Master with pull-up resistors (timeUp, timeDown, sendButton)

Here is where I am stuck. **UPDATE**

I was able to get the master and slave to communicate. RX and TX on master were crossed... SMH! However now the issue is that the slave is *writing* both digits it receives on top of itself. First writing one digit then clearing it and then the second digit...

Enough with the prologue here is the a code:

**Master**

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //sets up LCD pins
int waitTime = 10; //if food comes quicker than there is no need for a display ;)
const int timeUp = 6;
const int timeDown = 7;
const int sendButton = 8;
int timeUpState = 0;
int timeDownState = 0;
int sendButtonState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(timeUp, INPUT);
  pinMode(timeDown, INPUT);
  pinMode(sendButton, INPUT);
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's"); //Splash screen on start up
  lcd.setCursor(0,1);
  lcd.print("      Diner"); //Splash Screen
  delay(2000);        // Delay intended to allow the device to pair prior to use.
  lcd.clear();
  lcd.print("Essen Dauert:"); //German for "Food takes":
  lcd.setCursor(0,1);
  lcd.print("   Minuten"); // xx minutes
  }

void loop(){
  lcd.setCursor(0,1);
  timeUpState = digitalRead(timeUp);
  timeDownState = digitalRead(timeDown);
  sendButtonState = digitalRead(sendButton);
  if (timeUpState == LOW) {
  waitTime += 5;
  delay(500);  //debounce button
  lcd.print(waitTime);
  }

  if(waitTime > 90){ // Max limit for wait time
    waitTime = 10;   //default wait time
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

 if (timeDownState == LOW){
  waitTime -= 5;
  delay(500);
  lcd.print(waitTime);
  }

  if(waitTime < 10){ //Min value waiting time
    waitTime = 10;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

  if(Serial.available()){  // **This is where I am stuck**
   if(sendButtonState == LOW){
   Serial.write(waitTime);
   delay(500);
  }
 }
}

```

**Slave**

```
#include <LiquidCrystal.h>

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

void setup() {
  Serial.begin(9600);
  Serial.flush();
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's");
  lcd.setCursor(0,1);
  lcd.print("      Diner");
  }

void loop(){

  if (Serial.available()) {
   int waitTime = Serial.read();
    delay(200);
    lcd.clear();
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.write(waitTime);
    lcd.print(" Minuten");
     }
  }

```

Thanks in advance, Jonathan

# Answer
The problem was how I was reading the incoming serial data.

After changing `int waitTime = Serial.read()`

to `int waitTime = Serial.parseInt()` the code works.

**Thanks to everyone for all your help and tips!**
> 0 votes

# Answer
```
lcd.write(waitTime);

```

This line prints a single byte, whose (ASCII) value is the number in waitTime. You probably should write:

```
lcd.print(waitTime);

```

instead, which prints the number in waitTime using one ore more digits as needed.

This doesn't 100% explain the "both digits end up in the same place" symptom, since I'd expect random junk to be printed instead. But I'm pretty certain this is a problem, perhaps there's more problems :-)
> 0 votes

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


title: Arduino UNO R3 possibility

text:
# Question
Title: Arduino UNO R3 possibility
Can I use an ultrasonic sensor, ir sensor, serial communication with MATLAB on computer and i2c communication with a D6T MEMS thermal sensor simultaneously in Arduino UNO ?

# Answer
> 1 votes
Yes, it is possible for the arduino handle communicating over serial and I2C in real time, I've done it frequently. The IR sensor should not pose a problem either.

The ultrasonic sensor might use a timed pulse to send its information that can take a relatively long time, and the basic ultrasound code will just wait for it to finish without doing anything else. The delay itself will not cause you problems but if a lot of data is being sent to the arduino very quickly over serial it might miss some. These delays can be worked around with interrupts/some clever coding but I doubt it will ever be a problem.

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


# Question
Title: Flash "sketch" hex over ISP, without bootloader - possible?
I'm wondering if it's possible to flash the arduino sketch into a AVR, without using a bootloader - over ISP. I'd use the BSD programmer, which is basically parallel port with some resistors.

Let's say I use the Arduino IDE, try to upload with "verbose" (no actual arduino is attached) - it shows path to the hex in the verbose output, and I "steal" the file.

Now I'd flash it using avrdude onto a blank 328 via ISP - would that work?

I assume there needs to be a 16Mhz crystal, is that it? Any other pitfalls I have to be careful about?

# Answer
> 1 votes
You don't need the arduino bootloader on the chip, if you are programming it using ISP.

It looks like BSD is no longer supported by avrdude.

In the Arduino 1.5 IDE you can add programmers, so you can do the uploading right from the IDE, instead of 'stealing' the hex file and manually uploading from the command line.

If the chips are blank you probably need to change the fuses first.

You don't need a 16mhz crystal. The atmega328 has an internal 8mHz oscillator inside.

---
Tags: bootloader, avrdude, isp
---


# Question
Title: SD Card shield and TCRT5000 sensor aren't working together on arduino uno
I need to work with SD card and `TCRT5000 sensor` (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select `Arduino Uno` and added to it a SD card shield(from LC STUDIO) and a `TCRT5000 sensor` but it isn't working. My circuit and code is here:

```
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while(true);
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("test.txt", FILE_WRITE);
  dataFile.close();
  dataFile = SD.open("test.txt", FILE_WRITE);
  if(dataFile){
    dataFile.println("Start:");
  }else{
    Serial.println("Error in creating file.");
    while(true);
  }
}

void loop() {
  float value = analogRead(A3);
  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(value);
    Serial.println(value);
    dataFile.close();
  }else{
    Serial.println("Error in opening file.");
  }
  delay(5);
}

```

When `TCRT5000` isn't connected SD card working without any problem. I think it is related to current and supply current. Any idea?

# Answer
> 1 votes
Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.

---
Tags: arduino-uno, sensors, sd-card, current
---


# Question
Title: Are the Arduino Micro, Mini, etc plug'n play?
Also, what about the micro/nano/mini arduinos? Are they easily plug'n'play like the uno? (This is an edit from another of my questions)

# Answer
> 2 votes
The ones that have a USB connector are plug-and-play with a USB host. The ones that don't need a USB-to-UART bridge.

---
Tags: arduino-micro
---


title: How to continuously calibrate sensor

text:
# Question
Title: How to continuously calibrate sensor
I have a problem in calibration an LDR sensor. I want to let the sensor goes all day long and I'm using the LDR sensor as a presence sensor. The calibration values (min and max) changes all the day, and I need to detect only the peaks, or continuously change the min and the max values. Are there some defined pattern or algorithms to use?

# Answer
> 2 votes
In this situation, it may be useful to look at the differential of the signal.

One way to do this is to store the value, wait some time and read another value. You can then do:

`dv = current_value - last_value`

Or if you have some time metric (Perhaps clock ticks, or a rtc):

`dv = (current_value - last_value) / (current_time - last_time)`

You would then want to only count significantly large changes in `dv`. As the day progresses the light value will only change at a small rate but if someone were to block the light then there will be a large difference between `current_value` and `last_value`, causing `dv` to be largely negative (Indicating a loss of a lot of light) and when they no longer block the light you will get the opposite, indicating there is no longer an obstruction. (Or rather, less of an obstruction.)

---
Tags: sensors
---


# Question
Title: atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v
I'm having trouble getting the atmega328p chip to upload sketches using my ftdi. It always comes up with an error saying not in sync.

I have an 8Mhz crystal with 22pf capacitors. The weird thing is I could flash the bootloader using my avrispmkII @ 3.3v. AFAIK this tells me the chip is running. I have an led connected to pin7. It doesn't flash when turn the power on. However it does flash when powered from 5v and everything is working fine. I could upload sketches using the ftdi.

I have the ftdi on a breakout to pin headers. I have the reset pin wired up to the DTR via a 100nf capacitor. The reset has a 10k pull up. CTS pin is grounded. The usart is as follows tx (atmega) ---\> rx(ftdi) and rx(atmega) to tx(ftdi). I have also switch between 3.3v and 5v logic using the vccio pin on the ftdi. I.e. vccio = 5v if atmega is 5v.

I know the programmer need to know what voltage am using, how critical is it, since I don't have a 3.3v regulator to hand. I used a lm338 and it's coming out as around 3.2

I selected arduino pro/mini @ 8mhz 3.3v atmega328p when I flashed the bootloader

```
##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=57600

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x05
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

##############################################################

```

output from avrdude

```
avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

```

# Answer
> 1 votes
I would suspect that the 328P's fuses were not programmed as defined in the boards.txt This needs to be explicitly done.

```
uno.bootloader.low_fuses=0xff
uno.bootloader.high_fuses=0xde
uno.bootloader.extended_fuses=0x05
uno.bootloader.path=optiboot
uno.bootloader.file=optiboot_atmega328.hex
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F

```

if not done. several things can go wrong.

1. oscillator won't start on external crystal
2. oscillator will be at wrong speed code
3. wont start at bootloader

---
Tags: atmega328, ftdi
---