message:
How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?

I am working on project that my team need to detect the presence of the people. At first, we tried with motion sensor but it wasn't the way that we want it to work. We want to detect presence of the people even they don't move.

We decide to go with Omron Thermal Sensor D6T-44-L06. However, there lacking of tutorial or simple code online that actually show how to connect that Omron thermal sensor with Arduino. How can I interface this with Arduino?

body:
Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need.
http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf


sender: user

message:
Garbage value Serial Monitor

I am building my own arduino.Here is my code Below. I found code working for Digital Ios like blink example ; analog reading, Problem i am facing in Serial Monitor.Whenever i open Serial monitor i get trash values.I have choose proper crystal & proper values.  Please let me know possibility for getting trash values![Serial Out][1]

    int led = 2;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
    Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      Serial.println("Welcome:");
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(100);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(100);               // wait for a second
    }

  [1]: https://i.stack.imgur.com/WnnrQ.jpg

sender: assistant

body:
One of my projects does this too. I leave it connected to a USB port for power so it can control a room fan. Every 4 seconds it writes a line of data to the serial output. When I open a serial terminal on the computer, I immediately see a short stream of garbage, followed by the next, and all subsequent log outputs, properly displayed. It looks as if the serial-to-USB chip has some data buffered in it which it delivers, but out of sync, as soon as the terminal connection is made, but this is just a guess.

Have you tried resetting your chip while the terminal is connected? When I do this, there are no sync issues and the displayed data is all valid.

Update:
If you only ever get garbage from your terminal, then it's likely the terminal and the Arduino aren't matched for one or both of baud-rate or frame-size.

Arduino serial hardware uses an 8N1 frame: 8 data bits, No parity bit, 1 stop bit. Your serial monitor must be set to match this (and it probably is, since this is the most common convention, but worth checking.

Second, the baud rates must match. You've set the Arduino for 9600 baud and your serial monitor program must be also (from your screenshot, it looks like it is).

You said you are using a crystal so it quite unlikely that Arduino's 9600 baud is inaccurate, but this could happen if you were using its internal clock source.

Finally, in the lower left corner of your serial monitor screen shot, it looks like you have selected "No line endings". Serial.println() ends every line with CR/LF. See if that is an available line-ending setting. It is sometimes named "OD OA" (the hex values for Carriage-Return and Line-Feed). Try that setting if it is available.

The serial protocol is one of the oldest communication protocols but it has many variations. (Did someone say "standard"? :-)  Everyone gets bitten by it, eventually.


body:
Opening a Serial connection will reset your arduino and restart the whole program.
I learned this the hard way when coding a windows serial com-monitor for triggering systemcalls from arduino


message:
datalogging sampling frequency bottleneck

My datalogging system which consits of the Flora, RTC, SD card breakout board, LSM9DS0 sensor is shown in the picture below;

https://www.dropbox.com/s/d8pwcn59nq11lzs/2014-11-25 12.26.56.jpg?dl=0

The sampling rate/s is capped at 30 when writing into the sd card. If I disable the sensor and only save the time it goes up to 65. Writing into the serial interface rather than the sd card makes the rate goes up even higher at 127. for my application I need at least 100 samples/s. I am thinking the sd card is the problem after making the tests mentioned. The flora clock at 16Mhz is surely able to provide a higher sampling frequency. After checking the sensor datasheet and library I haven't found any limitation either. any input on this issue?

body:
First, based on my experience with similar hardware, something about the sd card I/O stinks: it should be plenty fast enough. Using a class 4 (cheapo) sd card I've seen a 16mhz AVR do a FAT filesystem open for appending, write a new record of maybe 70 characters and close the file, all a few hundred times per second. This was with the Arduino "SD" library apparently written by Sparkfun in 2010 and improved by Adafruit sometime later.

Maybe the I/O library you're using is dog slow? Another possibility is that your SD card has a lot of files on it and something about directory (folder) traversal during an open is the bottleneck? (my experience is with just a few files on a given sd card)

But you could try buffering N samples so each sd card write records N samples.

If you do this, don't forget to "flush" any remaining samples when you go from "sampling" to "not sampling" modes, if that's possible. That is, if something is telling the thing 'start', then 'stop', part of the response to 'stop' is to get the N-m buffered samples written out to the sd card.


body: I have used Sparkfun's OpenLog as I have also found the SD library slow when writing many small samples.  It lets you log directly from the Serial connection, so you should be able to get at least the 127 samples per second.  You may also try increasing the baud rate, especially if you are using outputting to Serial.


message:
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!

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


message:
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?

body:
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

![enter image description here][1]

  [1]: https://i.stack.imgur.com/z7O3z.png


message:
USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader

Is it possible to use **RXC Interrupt vector** with the factory programmed **bootloader** still **existing** in the **arduino pro mini**?

I've written a simple echo program using RXC interrupt vector, the program prints "*READY*" on startup but as soon the chip receives the first character it goes into a **repetitive reset loop** i.e. I keep receiving `READY READY READY..` so on.

I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?

Thanks in advance.

body:
Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does **not affect** the way the sketch runs.

---

> I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.


message:
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?

body: The ATmega328P has 2kiB of SRAM. Your program uses almost 3kiB. Move strings and constant values into flash.


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

body:
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


message:
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

body:
    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 :-)


body:
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!**


message:
Splitting the power source between an arduino and a servo

I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?

Do I have to take some safety for the Aduino in concern or could I just split the wire?

body:
If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.

If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).


body:
There is a page with information about the [current limits of Arduino][1] pins.  There's also a question on the Electrical Engineering SE site that addresses the [current limits of the board overall][2].

From the accepted answer on that question:

> The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

So that's more than the 100 mA you mentioned in your question.  (But go read the [whole answer][3]; there's more good info there.)

The easiest way to split the power is to use a separate, regulated power supply.

Except for simple tests (e.g., a single small unloaded servo), I use the digital i/o pins only for very low current signals:  buttons, status LEDs, sensors, serial communication, etc.

For example, to control an IR LED that can handle up to 50 mA, I'll supply power to the LED from the Arduino board's Vcc pin and control it with a transistor attached to a digital output pin.  Drawing 50 mA from the board's supply is well under the limit, and the digital output pin draws practically nothing.

For more than one servo, I use a peripheral PWM controller that takes power separately.  That peripheral is powered by a separate 5V 2A power adapter, which supplies the current to actually turn the motors.  I send commands to the controller using I2C from the Arduino, which is running from its own power supply.

[1]: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
[2]: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins
[3]: https://electronics.stackexchange.com/a/67094/64804


message:
lcd.print and 2D arrays

[Click here to see my program running][2]

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 ;) ~ ");

    }

  [2]: https://www.dropbox.com/sc/ur5f8b10ifdtuhz/AADK7fM8EeLWgxXQ0I42VrGoa

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


message:
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][1] 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.

  [1]: http://www.cplusplus.com/doc/tutorial/classes/

body: You put a bunch of code in a place where you can't have it. Move the assignments into a function body.


body:
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):

<!-- lang-all:cpp -->

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


message:
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?

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


message:
Wiring 5V ultrasonic sensor to Arduino Due

Is it possible to use the [2760342 ultrasonic range sensor][1] with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?

I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

  [1]: http://www.radioshack.com/radioshack-ultrasonic-range-sensor/2760342.html

body:
Is this too clunky?

https://www.adafruit.com/products/735

Breadboard Friendly 8-bit Logic Level Shifter, $1.50.


body:
If your question is "Why isn't everything standardized on 5v?", see this good SO answer:
https://electronics.stackexchange.com/questions/135841/voltage-standards-like-3-3v-5v-etc

Bottom line is that the voltage drops as the electronics' technology advances (12v to 5v to 3.3v).

Concretely to your problem, I honestly do not think that a level shifter is somewhat "clunky" solution to your problem, as suggested by mikeY (and as rejected by you). This is the way things are done in the electronics world - when a hardware mismatch arises, there is a hardware adapter to rescue.


message:
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);
    }

body:
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".


message:
Example code and documentation on using Firmata communication in native Java

I have been trying for some time to get documentation on using Java and a Firmata client library for the communication between a PC and an Arduino. Please note I want to use Java only, i.e., not Processing.

Up to now I used the excellent Haskell library [hArduino][1] for Firmata communication with Arduino boards.

Now I am teaching a Java course at the university as a PhD student. Therefore I need to use Java. However, compared to Haskell there are no centralized libraries, packages, documentation as with Haskell.

So I used Google to find more information on using Firmata client libraries for Java. Unfortunately, the search results are polluted with irrelevant results about Processing and Javascript. Therefore I ask here.

According to the Firmata [client library page][2], there are two Java client libraries. However, only [4ntoine][3] seems to be up to date, while the [Javarduino][4] project seems abandoned.

So I guess the standard way is to use the ["4ntoine"][5] Java client library. Or are there other options?

(I am not interested in Processing or Javascript.)

*Question: Where do I find up-to-date documentation and example code on using Firmata client libraries for Java?*

  [1]: https://hackage.Haskell.org/package/hArduino
  [2]: https://github.com/Firmata/Arduino
  [3]: https://github.com/4ntoine/Firmata
  [4]: https://github.com/shigeodayo/Javarduino
  [5]: https://github.com/4ntoine/Firmata

body:
Maybe [JArduino][1] can give you some useful information.
Check the native code in jardunio.core.

  [1]: https://github.com/SINTEF-9012/JArduino


body:
Maybe this can work for you.
Some months ago i used RXTXcomm library [1] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

- I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
- Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

[1] http://rxtx.qbang.org/wiki/index.php/Main_Page


message:
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:

<!-- language: lang-cpp -->

    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.

body:
When using the Yun over wifi, you cannot user Serial, you need to use Bridge [Console][1] object. Serial is bound to the usb cable.

Give a spin to [ConsoleRead][2] example.

  [1]: http://arduino.cc/en/Reference/YunConsoleConstructor
  [2]: http://arduino.cc/en/Tutorial/ConsoleRead


message:
Arduino Fio and BC127 communication

I am using an ArduinoFio and a BC127 ([datasheet][1]). I'm having troubles getting the serial connection working properly from the Arduino to the BC127 and viceversa. I wasn't able to communicate with the BC127 and I don't know if is because isn't correctly powered on or something else.

**I've connected pin 0 of the BC127 to GND, pin 33 to 3V3 and pin 41,42 (RX, TX) to the TX, RX arduino's pins.**

I've tested with the tester that all wires are connected, but the BC127 seems dead.

Any help is appreciated :|

  [1]: http://bluecreation.com/userfiles/DataSheet-BC127-latest4.pdf

body:
There's a couple of things I would try.

First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use [SoftwareSerial][1] instead in start a separate serial connection.

Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.

Third: [Flow control][2].

If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.

Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.

  [1]: http://arduino.cc/en/Reference/softwareSerial
  [2]: http://www.moxa.com/resource_file/509820091121333.pdf


body:
use this method for dealing with voltage translation. Also we have IC's which does the level shifting. Works great with higher frequencies as well.

[![Voltage Translation using nMos][1]][1]

  [1]: https://i.stack.imgur.com/9TaXn.jpg


message:
Arduino UNO serial send and receive issue

I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?

body: You need a common ground between the Arduino and the PIC. Connect both grounds one to each other.


body: Is the Arduino running at all when on battery?  You could be trying to pull too much current from the battery and killing the circuit.  Another cause is that some programmers pull the reset pin to low when unplugged; took me a while to figure out that one.


message:
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][1], which is shown below.

![enter image description here][2]

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?

  [1]: https://www.techshopbd.com/product-categories/boards/1253/arduino-uno-r3-china-techshop-bangladesh
  [2]: https://i.stack.imgur.com/euLjh.jpg

body:
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)


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


message:
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:

![enter image description here][1]

  [1]: https://i.stack.imgur.com/FnDKq.png

*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?

body: 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`.


message:
Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41

I've stumbled upon what I've later found it's quite common error, but there seems not to be simple troubleshooting way and solution (people often try various things, sometimes they succeed, sometimes not).

I am using [DAGU mini driver][1], I was able to load sketch as described [here][2] - chose Arduino NG ATMega8 as board, connect to my PC via USB (with the driver listed on the [product page][1]).

Later on I've plugged RedBot wheel encoders sensor and write some simplistic program to check whether it works at all. I've summarized the steps in a github [issue][3], so that it's easy to reference it.

When I tried to upload the sketch I've receiced `stk500_initialize(): (a) protocol error, expect=0x14, resp=0x42`, `stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41`. The full log is included in comment on that github issue.

The D13 diode is making series of 3-blink bursts - 8 bursts after start. More diagnostic I did in the github issue as well.

My question (apart from obvious 'how to fix it!?!' ;) ) is whether there is some kind of documentation for this protocol? On the various topics I've found people seem to have somewhat different problems (the numbers and messages were different). I just want to know why the first few messages are exchanged OK (avrdude receives some basic info from the chip), but later ones (namely `Send: A [41] . [81]   [20] `) are producing protocol errors.

  [1]: http://www.dawnrobotics.co.uk/dagu-arduino-mini-driver-board/
  [2]: http://blog.dawnrobotics.co.uk/2013/11/getting-started-with-the-dagu-arduino-mini-driver-board/
  [3]: https://github.com/BartAdv/rowboat/issues/1

body:
AVR programmer helped.

Meaning the bootloader somewhat got corrupted and I had to burn new one.


message:
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?

body:
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][1] 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]: http://arduino.cc/en/Tutorial/Process


message:
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?

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


body:
No. There are potential internal pullups, but not AFIK activated.

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


message:
Serial Communication over Desktop to Arduino

I have a USB 2 Serial adapter and the device is working fine. I see the device perfectly configured in my System.

I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter. Below is my Arduino code:

    int i = 0;
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      for(i=0;i<6;i++)
      {
      Serial.write('H');
      delay(100);
      }
    }

But when I try to read thru terminal software of data received at my COM port I see some junk character incoming. I am pretty sure that I am using same baud rate / flow setting both side. Why am I facing this issue - do I need to connect any other pins also as I just need to receive data at system side?

body:
>I have a USB 2 Serial adapter...I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter.

You **must not** connect Arduino pins directly to a D-SUB connector of a USB-Serial adapter, as those connectors traditionally carry higher voltage, opposite sense RS232 signals.

- The voltage is too high, and likely to cause damage to your Arduino's processor
- The signal is inverted in sense from the logic-level signaling used by your Arduino's processor.

If you actually needed to make this connection, you would need to either use a "logic level" USB serial adapter (sometimes informally called a USB-TTL adapter).  These terminate in various types of connections such as bare wires or header pins/sockets - but basically *never* in an D-SUB connector.  Or you can use an inverting line driver and receiver such as the MAX2232 type devices, or even an old 1488/1489 pair.

But it's not clear that you should be doing this at all - **an Arduino Mega already has a USB-serial converter onboard** - that is the interface you use to program it, and it would ordinarily be simplest to use that for runtime communication as well.


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

body:
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][1].

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][2] to evaluate better what suits your needs best.

  [1]: https://www.sparkfun.com/products/13097
  [2]: http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems


message:
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:

 - [Arduino Uno R3 SMD][1]
 - [Arduino Ethernet Shield][2]
 - [SparkFun USB Host Shield][3]

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][4] 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!

  [1]: https://www.sparkfun.com/products/11224
  [2]: https://www.sparkfun.com/products/9026
  [3]: https://www.sparkfun.com/products/9947
  [4]: http://hunt.net.nz/users/darran/blog/?tag=mouse

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


message:
Multiple timers with different frequencies

I have to use multiple timers (for example, to blink different LEDs) with different frequency (for example, 7.3 Hz). Cannot you tell me, what is the preferred way to implement it?

Just now I use one simple TimerOne timer and just check what LEDs should be inverted and what are not, but I don't think it's a good idea.

    #include <TimerOne.h>

    #define PIN_RED 52
    #define PIN_GREEN 50
    #define PIN_BLUE 48
    #define PIN_YELLOW 46

    #define N_LEDS 4

    float freqs[N_LEDS] = {1, 2, 3, 4};
    int pins[N_LEDS] = {PIN_RED, PIN_GREEN, PIN_BLUE, PIN_YELLOW};

    long int usec_to_invert[N_LEDS];
    long int full_usec_to_invert[N_LEDS];

    boolean led_states[N_LEDS];

    int who_is_next()
    {
      int next_to_invert = 0;
      for(int i = 0; i < N_LEDS; i++)
      {
        if(usec_to_invert[i] < usec_to_invert[next_to_invert])
        {
          next_to_invert = i;
        }
      }
      return next_to_invert;
    }

    void process_timer()
    {
      int to_invert_now = who_is_next(); // Смотрим, кого надо инвертировать на этот раз
      long int time_past = usec_to_invert[to_invert_now];

      for(int i = 0; i < N_LEDS; i++)
      {
        usec_to_invert[i] -= time_past;
      }
      led_states[to_invert_now] = !led_states[to_invert_now];
      digitalWrite(pins[to_invert_now], led_states[to_invert_now]);
      usec_to_invert[to_invert_now] = full_usec_to_invert[to_invert_now];

      int next_to_invert = who_is_next();
      long int time_to_pass = usec_to_invert[next_to_invert];
      if(time_to_pass <= 200)
      {  // The interrupt processor should finish work
        Timer1.setPeriod(200);
      }
      else
      {
        Timer1.setPeriod(time_to_pass);
      }
    }

    void setup()
    {
      Serial.begin(115200);
      for(int i = 0; i < N_LEDS; i++)
      {
        pinMode(pins[i], OUTPUT);
        led_states[i] = false;
        full_usec_to_invert[i] = (long int)(1000000. / freqs[i] / 2.);
        usec_to_invert[i] = full_usec_to_invert[i];
      }

      int next_to_invert = who_is_next();
      Timer1.initialize(usec_to_invert[next_to_invert]);
      Timer1.attachInterrupt(process_timer);
    }

    void loop()
    {
       delay(1000);
    }

body:
My suggestions would be:

- Implement a class that handles the queue and timer settings and uses callbacks.
- If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
- digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
- DO NOT wait in the ISR "process_timer()", since you might lose other interrupts! (for the Serial communication, for example)
- is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or

use a total overkill system for this situation, such as my multitasking-library [arduOS][1] that also covers a some other things.

  [1]: https://launchpad.net/arduos


message:
Arduino Uno PWM

My scheme is very basic: I use RGB LED with Arduino Uno. 5v is connected to anode, and pins 9-11 are connected to cathodes.

When using following sketch, my LED is producing white colour, which red, green and blue components are on:

    int redPin = 9;
    int greenPin = 10;
    int bluePin = 11;

    void setup(){}

    void loop(){
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }

But when I refer to [docs][1] for PWM:

    A call to analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on)

When I write `0` to all pins, I expect led to be off. What am I missing?

  [1]: http://arduino.cc/en/Tutorial/PWM

body:
Your LEDs are connected to the supply voltage. The output must be low to allow the LED to shine.

`Output 0 ==> LED on`


body: Since you've connected to the cathodes the pins are *sinking* current. As such the LEDS are active *low* with 0 being almost fully on and 255 being fully off.


body:
With your LEDs connected to +5V (AKA "Common Anode"), the PWM signal is reversed.

* When the output is "on", the voltage on the pin is 5v.
* When the output is "off", the voltage on the pin is 0V.

The difference in voltage between +5V and the pin for those two different states is:

* "On" = 5V - 5V = 0V
* "Off" = 5V - 0V = 5V

So you can see than when the output is off the LED will on because it causes a difference in voltage from one side of the LED to the other, so current can flow.  When the output is on the voltages either side of the LED are the same, so no current will flow.


body: When you set the pin value to 0 you are making that pin act as ground. Since the LED had a single anode that receives 5V. When the difference between the anode and cathode is high (Anode - 5V & Cathode - 0V) the LED turns on. When the difference between the anode and cathode is low (Anode - 5V & Cathode - 5V) the LED is off. The larger the difference between the two the brighter the LED. In your code use `analogWrite(redPin, ~0);` then everything should work. Change 0 above to whatever value you want, less than 255, and it should work. Also do the same for the green and plus pins too.


message:
Atmega168 breaking out of ISR

I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART_receive() on the atmel gets stuck at: `while ( !(UCSR0A & (1<<RXC0)) );`

Is there any way I can break out of this? The code is posted below:

    unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
    {
    unsigned char i = 0;

    if (size == 0) return 0;            // return 0 if no space

    while (i < size - 1) {              // check space is available (including additional null char at end)
        unsigned char c;
        while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
        c = UDR0;
        if (c == '\0') break;           // break on NULL character
        x[i] = c;                       // write into the supplied buffer
        i++;
    }
    x[i] = 0;                           // ensure string is null terminated

    return i + 1;                       // return number of characters written
    }

The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.

    ISR(USART_RX_vect)
    {
     len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0"
        UART_flag = 1;
    }

The the buffer is set up in main()

    unsigned char uart_string[20];

body:
I think I may have a very simple solution. Completely overlooked this while I was messing with the timers. I took the hint from a I2C routine in some threads in the the forum here.

This works with empty strings as well as large strings with garbage values. It doesn't seem to hold the system anymore, so it works for my purpose.

Anything I should add here?

    int count_for_break = 0;
    while ( !(UCSR0A & (1<<RXC0)) )  // wait for another char - Waits for 200 cycles.
      {
       count_for_break++;
       if(count_for_break > 200)
        break;
      }
    //then reset the counter upon break or char receive.


body:
As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.

The interrupt fires when *a character* has been received, so that is all your program should count on finding.  You can if you really want to *poll* the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened **and you definitely should not be *waiting* for it in the ISR**.  Rather, if the ultimate consuming code needs multiple characters, then *that* should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.

Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.


body:
First of all, you shouldn't share a _simple_ variable between ISRs and the main loop: `unsigned char uart_string[20];` should be `volatile unsigned char uart_string[20];`. Moreover, you must define it out of any scope.

Also, using possibly blocking loop in an ISR is strongly not recommended. In fact, whenever your microcontroller enter an ISR, everything else is stopped: thus, an ISR should last as short as possible. Plus, the `USART_RX_vect` triggers whenever a _single_ character is received: this means that you'll have to wait for the next one. Thus, you mustn't use ISR like that: I would just use a global volatile variable to monitor the amount of received characters. Then, in the main loop, I would analyze the input characters whenever this counter is greater or equal than 2
.
Finally, in your ISR, you try to read four input characters: '/0' is only one character, in the ASCII table it's called NULL, so you should only read up to three characters.


body:
I would suggest using code like this:

    //Above your program, global variable.
    char uartRXbuffer[100];//Adjust size!
    int  uartRXbufferIndex = 0;
    //bool uartRXmessage = false;

    ISR(USART_RXC_vect){
       uartRXbuffer[uartRXbufferIndex++] = UDR;//read UART register into buffer. And increase index by 1.
       if(uartRXbufferIndex > sizeof(uartRXbuffer){
          //uartRXmessage = true;
          uartRXbufferIndex = 0;
       }//else if(uartRXbuffer[uartRXbufferIndex-1] == "\n"){
       //   uartRXmessage = true;
       //}
    }

    void loop(){
       HandleBuffer();
    }

    void HandleBuffer(){
       //Do something with your buffer values.
       //if(uartRXmessage){
          if(strstr(uartRXbuffer,"Command1")){
            //Code for when "Command1" is found in your buffer.
          }
       //}
    //uartRXmessage = false;
    }

I havent tested this code, but the idea is correct I believe.
You can un-comment the uartRXmessage stuff if you only want to handle the buffer when there is an end-of-line character or when the buffer is full.
Alternatively you can implement a ring buffer.


message:
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 ?

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


message:
Burn Arduino Bootloader - Atmega8L

I am making an RGB LED project right now using the Arduino UNO board.

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

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

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

Thanks!

body:
You can program the 8u2 by either using a ISP programmer such as [Pocket AVR Programmer](https://www.sparkfun.com/products/9825) or directly over USB using the FLIPS software as [documented](http://arduino.cc/en/Hacking/DFUProgramming8U2)

In reference to:

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

I would recommend getting [Tiny AVR Programmer](https://www.sparkfun.com/products/11801) or alike to program ATtiny's and at use the ATtiny's directly for small specific tasks. Hence you can avoid the cost of the whole UNO if not needed. You can even emulate limited USB connection as done with the [DigiSpark](http://digistump.com/category/1). They even support internal oscillator. So they often need now external parts. They can be often applied without PCB.


body:
### The Bootlader ###
If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the `USBasp`. Or, you can simply use the _Arduino_  itself to do this.

 - Open the `ArduinoISP` sketch from _File_ > _Examples_.
 - Upload it.
 - Push `reset` on the Arduino.

### Wire it up ###

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

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

### Burning the Bootloader ###

Then select `Arduino as ISP` as the programmer.

 - Goto _Tools_ > _Programmer_.
 - Select _Arduino as ISP_.

Now click on _Tools_ > _Burn Bootloader_.

### Verifying it all works ###

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

### Notes: ###

 - __Remember__ that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the [ATMega8 to Arduino pin mapping][2].

 - Don't forget to connect the ground lines of the AVR and the Arduino.

 - This worked for me using an ATMega8A-PU. It should work with the 8L too.

 - Post here if you have any problems. Glad to help `:)`

  [1]: http://arduino.cc/en/Tutorial/ArduinoISP
  [2]: http://arduino.cc/en/Hacking/PinMapping


body:
Problem with Atmega8A-pu

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

All the best


message:
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?

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


message:
C# and Arduino problem with serial port

I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.

Actually my code is:

C#

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO.Ports;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace InterfaceArduinoWindowsFOrm {
      public partial class Form1 : Form {
        public Form1() {
          InitializeComponent();
          serialPort1.PortName = "COM3";
          serialPort1.BaudRate = 9600;
          serialPort1.Open();
        }

        private void pictureBox1_Click(object sender, EventArgs e) {
        }

        private void tabPage2_Click(object sender, EventArgs e) {
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e) {
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
          Console.WriteLine("test");
        }

        private void button1_Click_1(object sender, EventArgs e) {
          serialPort1.Write("5");
          Console.WriteLine(serialPort1.IsOpen);
        }
      }
    }

Arduino:

    /* Sweep
      by BARRAGAN <http://barraganstudio.com>
      This example code is in the public domain.
      modified 8 Nov 2013
      by Scott Fitzgerald
      http://arduino.cc/en/Tutorial/Sweep
    */

    #include <Servo.h>

    Servo myservo;  // Create servo object to control a servo.
    // Twelve servo objects can be created on most boards.
    int pos = 0;
    int message = 0; // This will hold one byte of the serial message
                     // variable to store the servo position.

    void setup() {
      Serial.begin(9600);
      myservo.attach(9);  // Attaches the servo on pin 9 to the servo object
    }

    void loop() {
      if (Serial.available()) {

        // Check to see if there is a new message
        message = Serial.read();

        // Put the serial input into the message
        Serial.print(message);

        if (message == '5') {
          Serial.print("test");
          for(pos = 0; pos <= 180; pos += 1) {
            // Goes from 0 degrees to 180 degrees
            // in steps of 1 degree

            myservo.write(pos);
            // Tell servo to go to position in variable 'pos'

            delay(15);
            // Waits 15 ms for the servo to reach the position
          }

          for(pos = 180; pos>=0; pos-=1) {
            // Goes from 180 degrees to 0 degrees

            myservo.write(pos);
            // Tell servo to go to position in variable 'pos'

            delay(15);
            // Waits 15 ms for the servo to reach the position
          }
        }
      }
    }

The problem is, when I click my button, nothing happens, but obviously if I remove the `if` statement, the servo motor code works.

body:
Since you are sending from the Arduino the received serial data back to the C# application (`Serial.print(message);`), I would advise to check what you receive on the C# side.
Register to the DataReceived event of the SerialPort as so:

    serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

And add an event handler:

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort port = (SerialPort)sender;
        string data= port.ReadExisting();
        // check here what data you received, if any
    }

This way you could confirm that the Arduino gets the data properly from the C# side to begin with. Next step would be to understand if this **if** statement treats the data properly:

    if (message == '5')

But starting from examination of what you get from the C# side will help you decide where exactly is the problem.


message:
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?

body:
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.)


message:
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)

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


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

body:
I would suspect that the 328P's fuses were not programmed as defined in the [boards.txt](https://github.com/arduino/Arduino/blob/master/hardware/arduino/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


message:
Arduino: The program exited the loop early and execute setup() repeatedly

I'm working with Arduino Uno, Adafruit PN532 NFC/RFID Shield and along with other modules. I'm posting this test program because I found there's conflict with the serial output while writing code to integrate all the modules together. I tried troubleshooting by running this code. The result wasn't what I'd expected.

In Arduino, as far as I know, setup() only runs once after starting the program and then loop() will be executed repeatedly. I ran the example sketch called *readMiFare* provided by Adafruit alone and it was fine. This code can be found at https://github.com/adafruit/Adafruit_NFCShield_I2C/blob/master/examples/readMifare/readMifare.pde. However, when I did the following in main,

    void setup()
    {
      Serial.begin(115200);
      nfctestsetup();
    }

    void loop(void)
    {
      nfctestloop();
    }

the following conflict showed up. When happened was that whenever I scanned a card to the reader it executed the loop() partially and exited the loop. Even worse, it executed the setup() again and again whenever I scanned a card.

![Serial output][1]

In nfctestsetup(), I just commented out    `Serial.begin(115200);` from readMiFare.

My hardware setup was a no brainer since I'm using I2C.
![Uno and PN532 Shield][2]

Appreciate the help.

After spending a good amount of hours on troubleshooting, I found something interesting. When I commented out all other files except NFC and main, it worked like a charm. So I suspect there could be redefinitions on the pins that the NFC shield uses on other files. I suspect the following code in the other file gave me the problem because I commented out the rest of the code in this file and ran this block of code together with NFC and main. In fact, it's the last line of code in this block that gave me the problem.

Also, I probed on the RESET pin (see the readMiFare link above). It generated a high-low-high pulse whenever I scanned a card. Is this related to the problem?

    #include <SPI.h>
    #include "Adafruit_BLE_UART.h"

    // Connect CLK/MISO/MOSI to hardware SPI
    // e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
    #define ADAFRUITBLE_REQ 10
    #define ADAFRUITBLE_RDY 3     // This should be an interrupt pin, on Uno thats #2 or #3
    #define ADAFRUITBLE_RST 9

    Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

Any thought is appreciated.

  [1]: https://i.stack.imgur.com/lIVAG.png
  [2]: https://i.stack.imgur.com/KS2jd.jpg

body: This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.


message:
Arduino Digital Input Causing Output Problems

I am working on a simple project using an Arduino Mega 2560 that involves reading a 12-bit binary encoder signal and which is used to cycle a digital pin high and low (depending on the angular location of the encoder).

My problem is that when the digital output pin is told to go low, it only goes down to about 4V. I also noticed that it would occasionally dip down to ground, instead of just 4V. Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V. When I turned off power to my encoder which is connected up the the Arduino through 12 digital input pins, the output pin dropped down to 0V. When I turn the encoder back on it goes back up to about 4V.

I have tried connecting the output pin to ground and obviously the voltage goes to 0, but as soon as I remove the connection to ground the voltage springs back up to around 4V. It appears as though somehow the voltage being fed to the digital input pins (in the form of a ~5V digital input signal) is preventing the digital output pin from going to ground. I have no idea why this is the case, I have searched all over and could not find any similar complaints. My code is posted below, any help is greatly appreciated!

    unsigned long CamAngle = 0;       // Variable to store encoder value
    unsigned long PrevCamAngle = 0;   // Variable to store previous encoder value
    int i = 0;                        // Cycle index
    int BDC[] = {683,2048,3413};      // BDC angle (12-bit encoder value)
    int TDC[] = {0,1365,2731};        // TDC angle (12-bit encoder value)

    boolean TDCycle = false;          // TDC Cycle
    boolean BDCycle = false;          // BDC Cycle
    boolean Cycle = true;             // Encoder rollover cycle (replaces TDC cycle 0)

    void setup()
    {
      pinMode(37, INPUT);           // Encoder bit 0 (PORTC-0)
      pinMode(36, INPUT);           // Encoder bit 1 (PORTC-1)
      pinMode(35, INPUT);           // Encoder bit 2 (PORTC-2)
      pinMode(34, INPUT);           // Encoder bit 3 (PORTC-3)
      pinMode(22, INPUT);           // Encoder bit 4 (PORTA-0)
      pinMode(23, INPUT);           // Encoder bit 5 (PORTA-1)
      pinMode(24, INPUT);           // Encoder bit 6 (PORTA-2)
      pinMode(25, INPUT);           // Encoder bit 7 (PORTA-3)
      pinMode(26, INPUT);           // Encoder bit 8 (PORTA-4)
      pinMode(27, INPUT);           // Encoder bit 9 (PORTA-5)
      pinMode(28, INPUT);           // Encoder bit 10 (PORTA-6)
      pinMode(29, INPUT);           // Encoder bit 11 (PORTA-7)

      pinMode(30, OUTPUT);          // Set PORTC pin 8 to output (stop pin float)
      pinMode(31, OUTPUT);          // Set PORTC pin 7 to output (stop pin float)
      pinMode(32, OUTPUT);          // Set PORTC pin 6 to output (stop pin float)
      pinMode(33, OUTPUT);          // Set PORTC pin 5 to output (stop pin float)

      digitalWrite(30, LOW);        // Set PORTC pin 8 low (stop pin float)
      digitalWrite(31, LOW);        // Set PORTC pin 7 low (stop pin float)
      digitalWrite(32, LOW);        // Set PORTC pin 6 low (stop pin float)
      digitalWrite(33, LOW);        // Set PORTC pin 5 low (stop pin float)

      pinMode(53, OUTPUT);          // Set pin 53 (PORTB-0) as digital output
      digitalWrite(53, LOW);        // Set pin 53 (PORTB-0) LOW

    }

    void loop()
    {

      // Cam Angle Update
      PrevCamAngle = CamAngle;      // Set variable to previous encoder value
      CamAngle = (PINA << 4) + PINC;    // Read encoder, set variable to value

      if (TDCycle == true && CamAngle >= TDC[i])  // Wait for encoder to reach angle if cycle active
      {
        PORTB = 0;                                  // Set digital pin 53 LOW
        TDCycle = false;
        BDCycle = true;
      }

      if (BDCycle == true && CamAngle >= BDC[i])  // Wait for encoder to reach angle if cycle active
      {
        PORTB = 1;                                  // Set digital pin 53 HIGH
        TDCycle = false;
        BDCycle = true;
        i++;
        if (i > 2)                                  // Reset every 3 cycles (3 cycles per revolution)
        {
          i = 0;
          BDCycle = false;
          Cycle = true;
        }
      }

      if (Cycle == true && CamAngle < (PrevCamAngle + 1))  // Wait for encoder to cycle back to 0
      {
        PORTB = 0;                                  // Set digital pin 53 LOW
        BDCycle = true;
        Cycle = false;
      }

    }

As you can see I am utilizing direct port manipulation, however I have the same issues when I use the Arduino library commands as well.  I'm fairly certain this is some sort of hardware issue, however I could be wrong.

body:
I think you have two issues here.

First:

> Much to my surprise, when I unplug the Arduino, the digital output pin is still reading 4V.

With a powered device connected to the input pins, the overvoltage protection diodes power your 5V line with what is called "parasitic power". Those diodes are supposed to clamp an input pin to not exceed 5V, but if the power is off, they actually **supply** 5V (assuming at least some of the pins are high), hence powering up the processor. It is not designed to do this, and you should not power off the processor in this way.

---

Second:

> My problem is that when the digital output pin is told to go low, it only goes down to about 4V.

I tried out your code, but without the encoder to hand, I just comment out the three "if" tests:

    //  if (TDCycle == true && CamAngle >= TDC[i])
    ...
    //  if (BDCycle == true && CamAngle >= BDC[i])
    ...
    //  if (Cycle == true && CamAngle < (PrevCamAngle + 1))

A multimeter on pin 53 reads 0.98V, however this is because the pin is being turned on and off quickly. I can't work out for sure whether some or all of these conditions would be satisfied in sequence (they don't seem directly related). One thing you could do, since you seem to want pin 53 either on or off is use "else", eg.

    if (TDCycle == true && CamAngle >= TDC[i])
    {
    ...
    } else if (BDCycle == true && CamAngle >= BDC[i])
    {
    ...
    }
    else if (Cycle == true && CamAngle < (PrevCamAngle + 1))
    {
    ...
    }

Now you won't have multiple attempts to turn the pin on **and** off through one turn through the loop.


message:
Simple IR sensor

I had an infrared 38khz sensor that I used to read my TV remote control commands. It worked fine but I burned it. I had not another 38khz IR sensor so I tried to use my infrared reflective optic sensor like the one below:

![enter image description here][1]

I press my TV remote control button and when I try to read the HIGHs and LOWs it does not work. The sensor shows in my Serial that it received the infrared light but it does not sense the lows/high.

As far as I know, this sensor is not 38khz, it listens in all frequencies that are infrared. So why it does not work? It should work cause it listens in all frequencies. Why it can detect the HIGHs/LOWs that the remote control sends?

  [1]: https://i.stack.imgur.com/HnGi6.jpg

body:
You didn't post the code that used to work with the standard 38Khz IR sensor, but I believe you used **digitalRead** to determine a HIGH or LOW value, by thus determine if there is an IR emitting in place.

The reflective optic sensor works differently, the output is analog, and changes according to the amount of IR light it sens. In addition, it has a built-in IR led next to the IR sensor, so if you want to use this as the IR detection sensor you had, first you need to disable the IR led to prevent interference.

The second step would be to use **analogRead**, and compare the result to a pre-defined threshold. For example, since analogRead returns result in the range of 0...1023, you can treat everything from, say, 512 and above as logic 'HIGH'. If you are working with libraries that detects the IR signal, you will need to alter them accordingly.


message:
ATtiny85 minimum setup to blink led

What would be the (very) minimum *schematic* to make a ATtiny85 blink a led?

Restrictions are:

* There must be a C program compiled and uploaded to it, just like an Arduino board would have. The code would use a simple "delay" to wait a little bit before changing the LED state.
* The LED must be controlled by a "digital output port" just like an Arduino board would be.

This is the main question. Although I thought to ask a similar question with the restriction of "blinking exactly once per second", that would change completely the schema (not being a MINIMAL after all). So lets restrain to the main question. Maybe some day we can discuss the version 2.0!

body:
Here is the absolute minimal schematic required to blink a LED beyond power and decoupling:

![Minimal LED schematic][1]

  [1]: https://i.stack.imgur.com/VHNbc.png

Refer to "Which resistor to use for this LED" to calculate the appropriate value for R1.


body:
This schematic shows a complete connection of a blinking led.

* Red cable = +5V (pin 8)
* White cable = Ground (pin 4)
* Resistor = 1 end at pin 5 (IO 0) and the other in the LED anode (+)
* Led anode (+) in the resistor, cathode (-) (small leg) in the ground

* Resistor = 330 Ohms

The arduino in the picture is not necessary, just used to give power. But in the video linked below its used to burn the ATtiny85. The resistor can be a 330 ohms for a simple project like this.

![Snapshot of the video linked below][1]

[Youtube Video with a simple explanation][2]

I hope this explanation will enlighten who wants to start on it.

--

Edited:

If you want to record your ATtiny85 using Arduino UNO as ISP, then you will also need:

* 10 uF electrolytic capacitor

Here a picture of the pins:
![enter image description here][3]

  [1]: https://i.stack.imgur.com/2aAfG.png
  [2]: http://youtu.be/i9WOwDrpRKs
  [3]: https://i.stack.imgur.com/QL6Sg.png


body:
Ignacio Vazquez-Abrams has already outlined the schematics.

> There must be a C program compiled and uploaded to it, just like an Arduino board would have.

There are however some differences between a fully equipped Arduino board with an ATMega328P and a bare ATtiny85 you would have to care for in your code:

1. A bare ATtiny85 runs at 1 MHz (8 MHz internal oscillator, *CKDIV8*). Define **F_CPU** accordingly.

1. The ATtiny85 only has one hardware port, **PB**. There's a reason Ignacio used **PBx** in his scheme ;)

On the plus side, the ATtiny85 allows to toggle a pin by setting the corresponding bit in **PINB**.

<!-- language: lang-c -->

    PINB |= (1 << PB0);


body:
My setup would be:

- a 10k resistor between Vcc and reset pin (pull-up)
- a 330k put in serial with a led,  connected between, e. g. PB0 and gnd.

That's all.

For programming, I use an ISP programmer.  I use a cheap Arduino Nano clone board for that.

I can run my ATtiny85 at 16Mhz internal oscillator,  but important: I remarked that I had better results after having burnt the bootloader onto the ATtiny85, even if it is not needed because there is no USB serial chip besides the MCU.

But perhaps using avrdude to program the ATtiny85 fuses bits could avoid to burn this useless bootloader (taking 1/4 of flash memory). If someone has a solution, he is welcome.


message:
Using a web server with Arduino

So I am not new to arduino, however, I am new with web servers. I am working on a project that can control a robotic arm that is at one location and I can be at my house. I know basic HTML, Basic CSS, Basic JavaScript, and a tiny bit of JQuery. Only reason I say basic is because I self taught all these languages to myself using codeacademy. So I have a few questions since I done research on the matter.

Can a project like this be done with just the languages I know? All the tutorials I have looked at say you have to know AJAX and JSON. I have no idea what these are.

Also, for the interface, I need to be able to take the value of the encoders on the robot and view them. I also need a button that will record the value at that point in time of the encoders so I can configure the points and maybe even name them. A box where I can see the points and their coordinates, and finally a box where i can place points in and then execute a sequence.

How tough should this be?

body:
You can use an [Arduino Yun][1]: it has a 32u4 microcontroller coupled with a cpu running linux. The linux side already has a webserver: together with the [Bridge library][2], you can use [REST-like APIs][3] to control a sketch, or build a web app that uses that APIs.

One example of remotely control an Arduino (although using an Android app instead of html+js) [is this][4]. Here is its [source code][5].

  [1]: http://arduino.cc/en/Main/ArduinoBoardYun?from=Products.ArduinoYUN
  [2]: http://arduino.cc/en/Reference/YunBridgeLibrary
  [3]: http://arduino.cc/en/Tutorial/Bridge
  [4]: https://www.youtube.com/watch?v=F-oRrcYfv8o
  [5]: https://github.com/Vadorequest/AAD1


body:
There is an example of using the ethernet shield as a simple web server on the arduino website:
http://arduino.cc/en/Tutorial/WebServer

Adafruit has another tutorial using an SDCard to hold the web application's files:
http://www.ladyada.net/learn/arduino/ethfiles.html

It would be possible to use the aforementioned techniques to host a simple web application.
Since the browser only understands HTML, CSS and JavaScript (browser plugins not withstanding), the application will have to be written using these languages.
The HTML file will describe the structure of the UI (text, buttons, etc.), the CSS will apply styles if necessary and the JavaScript will add the interaction code (e.g. what happens when you press a button). The JavaScript could request data from the arduino+ethernet shield using AJAX request and should be able to send data back the same way. Using jQuery, this should be pretty straightforward.

That said, it might be easier to use a full fledged network stack such as the one you can find on Linux (using a raspberry pi for example) and to communicate using the serial port with Linux. I have an example on GitHub (the documentation is lacking but I could update it if need be): https://github.com/ddm/arduino-express

But in that case you don't get to use the ethernet shield which you may have already bought...


message:
Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost

I am ***really*** despaired. I have spent a full day to understand this, and it seems that I still don't.

I have an Arduino UNO, with an ATMega328, for which I wrote a great piece of code.

Later, I have built a circuit on a bread board, where I want to use that same ATMega328, in a 3.3V configuration, and hence 8MHz oscillator .

So, I understood that I have to write a new boot loader to it (is that correct?)

So I follow many guides available, including the [Arduino Standalone][1], and then I understood that I don't have another chip (ATMega328), in order to use the UNO as a boot loader.

So, I was trying to connect the ATMega328 directly from the bread board to the UNO's serial data, change the `boards.txt` file to add `"ATMega on bread board 8MHz"`, and tried to boot-loading it, without success. I get the error that it `can't connect with the board`.

Now I have been told that **I can't** connect the ATMega328 directly to the UNO serial to boot load it, so my questions are:

 1. Do I really need to go over this hell in order to work with the same
    chip that worked with 16MHz, but now on 8MHz at 3.3V? (why
    in `microchip` I could just switch xtal? )
 2. If I do have to boot loading it, and I have **one** chip, and
    an UNO, how can I do that?
 3. How you do that in mass production?

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

body:
So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.

Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.

Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or [ScratchMonkey](http://microtherion.github.io/ScratchMonkey/index.html)); I don’t think your single-microcontroller idea would work.

For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s [mishap at SparkFun](https://www.sparkfun.com/news/1575?_ga=1.55332589.776570698.1363272950)


body:
There is a [very nice tutorial by Adafruit][1], which explains how to get the Arduino Uno run at 3.3v, with minimum hussle and while keeping it's speed at 16Mhz, despite it's a bit out of specs (they claim it shouldn't pose a problem).

The main idea is to replace the voltage regulator and the fuse on the Uno board. This involves some soldering, but will probably give you the fastest results for *prototyping*.

I would not choose the Arduino Uno for mass production anyway, since there are plenty of Arduino compatible boards that runs at 3.3v (like Arduino Due, Lilypad, and Arduino Pro Mini to name a few. Full list can be found on [Wikipedia][2]). As a side note, for mass production, I would probably go with a custom made PCB, and not an off-the-shelf product, considering its high cost.

The link you provided explains how to recreate the Arduino  around the Atmega328p on a breadboard. For that, you will need a USB to serial converter such as the suggested FT232, but please note that this tutorial **does not** address the issue on stake, which is running the chip at 3.3v (note the specs of the voltage regulator they offer, which is a 5v regulator).

  [1]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion
  [2]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion