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

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

Answers: 2

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


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

title: Cannot communicate with Serial Monitor - Arduino Yun

Answers: 1

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


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

title: Arduino Fio and BC127 communication

Answers: 3

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 voltage level translator. 5v to 3.3V. Dont just connect directly 5v tx to a 3.3v tx...!!

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


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

title: Arduino UNO serial send and receive issue

Answers: 2

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.


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

title: Identifying a counterfeit or authentic Arduino

Answers: 2

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.


body:
I try to test Grove - Infrared Temperature Sensor on Arduino Yun with the sample code but it does not work. In the console it shows that the object temperature is out of range all the time. However, when I try to test it on Arduino Uno, it works fine.

My sketch:

<!-- language: cpp -->

    #include <math.h>
    #include<Console.h>
    //#include <NewSoftSerial.h>       //if display in LCD(seeed serial LCD driver)
    //#include <SerialLCD.h>           //if display in LCD(seeed serial LCD driver)
    //#include "temp.h"

    const int temp_analog_in = A0;  // Analog input pin connect to temperature sensor SUR pin
    const int objt_analog_in = A1;  // Analog input pin connect to temperature sensor OBJ pin
    float temp_calibration = 0;     //this parameter was used to calibrate the temperature
    //float objt_calibration=0.000; //this parameter was used to calibrate the object temperature
    float temperature_range = 10;  //we make a map of temperature-voltage according to sensor datasheet. 10 is the temperature step when sensor and
    //object distance is 9CM.
    float offset_vol = 0.014;      //this parameter was used to set the mid level voltage,when put the sensor in normal environment after 10 min,
    //the sensor output 0.For example,the surrounding temperature is 29℃，but the result is 27℃ via the sensor,
    //you should set the reerence to 0.520 or more,according to your sensor to change.
    //the unit is V

    //SerialLCD slcd(11,12);
    float tempValue = 0;
    float objtValue = 0;
    float current_temp = 0;
    float temp = 0;
    float temp1 = 0;
    float temp2 = 0;
    unsigned int temp3 = 0;
    const float reference_vol = 0.500;
    unsigned char clear_num = 0; //when use lcd to display
    float R = 0;
    float voltage = 0;

    long res[100] = {
      318300, 302903, 288329, 274533, 261471, 249100, 237381, 226276, 215750, 205768,
      196300, 187316, 178788, 170691, 163002, 155700, 148766, 142183, 135936, 130012,
      124400, 119038, 113928, 109059, 104420, 100000, 95788, 91775, 87950, 84305,
      80830, 77517, 74357, 71342, 68466, 65720, 63098, 60595, 58202, 55916,
      53730, 51645, 49652, 47746, 45924, 44180, 42511, 40912, 39380, 37910,
      36500, 35155, 33866, 32631, 31446, 30311, 29222, 28177, 27175, 26213,
      25290, 24403, 23554, 22738, 21955, 21202, 20479, 19783, 19115, 18472,
      17260, 16688, 16138, 15608, 15098, 14608, 14135, 13680, 13242, 12819,
      12412, 12020, 11642, 11278, 10926, 10587, 10260, 9945, 9641, 9347,
      9063, 8789, 8525, 8270, 8023, 7785, 7555, 7333, 7118, 6911
    };

    float obj [13][12] = {
      /*0*/             { 0, -0.274, -0.58, -0.922, -1.301, -1.721, -2.183, -2.691, -3.247, -3.854, -4.516, -5.236}, //
      /*1*/             { 0.271, 0, -0.303, -0.642, -1.018, -1.434, -1.894, -2.398, -2.951, -3.556, -4.215, -4.931}, //→surrounding temperature,from -10,0,10,...100
      /*2*/             { 0.567, 0.3, 0, -0.335, -0.708, -1.121, -1.577, -2.078, -2.628, -3.229, -3.884, -4.597}, //↓object temperature,from -10,0,10,...110
      /*3*/             { 0.891, 0.628, 0.331, 0, -0.369, -0.778, -1.23, -1.728, -2.274, -2.871, -3.523, -4.232},
      /*4*/             { 1.244, 0.985, 0.692, 0.365, 0, -0.405, -0.853, -1.347, -1.889, -2.482, -3.13, -3.835},
      /*5*/             { 1.628, 1.372, 1.084, 0.761, 0.401, 0, -0.444, -0.933, -1.47, -2.059, -2.702, -3.403},
      /*6*/             { 2.043, 1.792, 1.509, 1.191, 0.835, 0.439, 0, -0.484, -1.017, -1.601, -2.24, -2.936},
      /*7*/             { 2.491, 2.246, 1.968, 1.655, 1.304, 0.913, 0.479, 0, -0.528, -1.107, -1.74, -2.431},
      /*8*/             { 2.975, 2.735, 2.462, 2.155, 1.809, 1.424, 0.996, 0.522, 0, -0.573, -1.201, -1.887},
      /*9*/             { 3.495, 3.261, 2.994, 2.692, 2.353, 1.974, 1.552, 1.084, 0.568, 0, -0.622, -1.301},
      /*10*/            { 4.053, 3.825, 3.565, 3.27, 2.937, 2.564, 2.148, 1.687, 1.177, 0.616, 0, -0.673},
      /*11*/            { 4.651, 4.43, 4.177, 3.888, 3.562, 3.196, 2.787, 2.332, 1.829, 1.275, 0.666, 0},
      /*12*/            { 5.29, 5.076, 4.83, 4.549, 4.231, 3.872, 3.47, 3.023, 2.527, 1.98, 1.379, 0.72}
    };

    float binsearch(long x)// this function used for measure the surrounding temperature
    {
      int low, mid, high;
      low = 0;
      //mid=0;
      high = 100;
      while (low <= high)
      {
        mid = (low + high) / 2;
        if (x < res[mid])
          low = mid + 1;
        else//(x>res[mid])
          high = mid - 1;
      }
      return mid;
    }

    float arraysearch(float x, float y) //x is the surrounding temperature,y is the object temperature
    {
      int i = 0;
      float tem_coefficient = 100;
      i = (x / 10) + 1;
      voltage = (float)y / tem_coefficient;
      //Serial.print("sensor voltage:\t");
      //Serial.print(voltage,5);
      //Serial.print("V");
      for (temp3 = 0; temp3 < 13; temp3++)
      {
        if ((voltage > obj[temp3][i]) && (voltage < obj[temp3 + 1][i]))
        {
          return temp3;
        }
      }
    }

    float temp_measure()
    {
      unsigned char i = 0;
      float current_temp1 = 0;
      int signal = 0;
      tempValue = 0;

      for (i = 0; i < 10; i++) //
      {
        tempValue += analogRead(temp_analog_in);
        delay(10);
      }
      tempValue = tempValue / 10;
      temp = tempValue * 1.1 / 1023;
      R = 2000000 * temp / (2.50 - temp);
      signal = binsearch(R);
      current_temp = signal - 1 + temp_calibration + (res[signal - 1] - R) / (res[signal - 1] - res[signal]);
      //current_temp1=current_temp;
      //slcd.setCursor(0,1);
      //slcd.print("sur T:");
      //slcd.print((int)current_temp1,DEC);
      Console.print("Surrounding temperature:");
      Console.print(current_temp);
      return current_temp;
    }

    float objt_measure()
    {
      unsigned char i = 0;
      unsigned char j = 0;
      float sur_temp = 0;
      unsigned int array_temp = 0;
      float temp1, temp2;
      float final_temp = 0;
      objtValue = 0;
      for (i = 0; i < 10; i++)
      {
        objtValue += analogRead(objt_analog_in);
        delay(10);
      }
      objtValue = objtValue / 10;
      temp1 = objtValue * 1.1 / 1023; //+objt_calibration;
      sur_temp = temp1 - (reference_vol + offset_vol);
      Console.print("\t Sensor voltage:");
      Console.print(sur_temp, 3);
      Console.print("V");
      //slcd.setCursor(11,1);
      //slcd.print((int)(temp1*10000),DEC);
      array_temp = arraysearch(current_temp, sur_temp * 1000);
      temp2 = current_temp;
      temp1 = (temperature_range * voltage) / (obj[array_temp + 1][(int)(temp2 / 10) + 1] - obj[array_temp][(int)(temp2 / 10) + 1]);
      final_temp = temp2 + temp1;
      if ((final_temp > 100) || (final_temp <= -10))
      {
        Console.println ("\t out of range!");
      }
      else
      {
        Console.print("\t object temperature:");
        Console.println(final_temp, 2);
        //Serial.println("℃");
      }
      ////////////////////////////////////////////////////
      //The fllowing code is used for display by serialLCD
      /*
        slcd.setCursor(0,0);
        slcd.print("obj T:");
        if((final_temp>=0)&&(final_temp<=100))
        {
          slcd.print(final_temp,DEC);
        }
        else if((final_temp<0)&&(final_temp>=-10))
        {
          slcd.setCursor(10,0);
          slcd.print('-');
          slcd.print(abs(final_temp),DEC);
        }
        else
          {
            slcd.setCursor(5,0);
            slcd.print("out of range");
            }*/
      //////////////////////////////////////////
    }

    void setup()
    {
      Bridge.begin();
      Console.begin();
      while (!Console);
      Console.println("Hi, what's your name?");// initialize serial communications at 9600 bps:
      //slcd.begin();//Add while using LCD to display
      //slcd.backlight();//Turn on the backlight of LCD while using LCD to display
      analogReference(INTERNAL);//set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
      //analogReference(INTERNAL1V1);//(mega only)set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
    }
    //If use LCD to display, adding below code to clear the screen in time
    void loop()
    {
      temp_measure();
      objt_measure();

      /*
        if(clear_num==10)
          {
            slcd.clear();
            clear_num=0;
            }
        else
          clear_num++;
      */
    }
I am sure that I connected the wires properly. The exact same wiring configuration is used with Arduino Uno.

title: Grove temperature sensor with Arduino Yun

Answers: 0


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

title: Issue with adding a library: No such file or directory

Answers: 1

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


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

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

Answers: 1

body:
AVR programmer helped.

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


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

title: How to make Arduino communicate with MySQL?

Answers: 1

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


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

title: Is there a pullup on I2C?

Answers: 2

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


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

title: Serial Communication over Desktop to Arduino

Answers: 1

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.


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

Answers: 1

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


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

title: USB mouse/keyboard passthrough feasible?

Answers: 1

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.


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

title: Multiple timers with different frequencies

Answers: 1

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


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

title: Arduino Uno PWM

Answers: 4

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.


body:
I use official Arduino GSM Shield with Uno R3.

I uploaded web server examples from official GSM library. I use a simple python script to make TCP/IP connections to my GSM Shield web server. I send simple requests from my computer to shield, and it responses back.

At first, this worked like a charm. I even connected a led to arduino uno, and started turn it on and off. But after some time, I get timeout errors from my script.

I turned on debug mode of gsm shield. At first, it displayed normal stuff. When connection gone between my computer and shield, it doesn't showed anything on serial window.

I thought there is something wrong with shield, but when I send a request from my computer; light of the shield indicates that there is a transmission incoming; but nothing shows on serial window. I think after some time, connection between arduino and gsm shield gets broken.

What could be done to make this web server more stable? I don't want it stop working after half an hour.

**Edit:** Other than loop function, my code is same as web server example in the Arduino examples.

    // I connected leds to D11 and D12 to see what happens during program.
    void loop(){
      GSMClient client = server.available();

      digitalWrite (11, HIGH);

      if (client) {
        while (client.connected())
        {
          if (client.available())
          {
            char c = client.read();

            // when it receives 1, D12 pin is high for 3 seconds.
            if (c == '1') {
              digitalWrite (12, HIGH);
              delay(1000);
              client.stop();
              delay(2000);
              digitalWrite (12, LOW);
            }
          }
        }
      }
    }

title: Arduino GSM Shield web server hangs

Answers: 0


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

title: Atmega168 breaking out of ISR

Answers: 4

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.


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

title: Arduino UNO R3 possibility

Answers: 1

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.


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

title: Burn Arduino Bootloader - Atmega8L

Answers: 3

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


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

title: Flash "sketch" hex over ISP, without bootloader - possible?

Answers: 1

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.


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

title: C# and Arduino problem with serial port

Answers: 1

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.


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

title: How to continuously calibrate sensor

Answers: 1

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


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

title: Are the Arduino Micro, Mini, etc plug'n play?

Answers: 1

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.


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

title: atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v

Answers: 1

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


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

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

Answers: 1

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.


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

title: Arduino Digital Input Causing Output Problems

Answers: 1

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.


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

title: Simple IR sensor

Answers: 1

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.


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

title: ATtiny85 minimum setup to blink led

Answers: 4

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.


body:
My first experience with Arduino ended in a tragedy. I bought a Leonardo from ebay and upon arrival, attached it to my laptop. Programmed a simple blink demo with the onboard LED. It started working. Then detached it from USB and plugged in a 9v adapter. The board started smoking and it doesn't work anymore. I measured the voltage of the adapter and it reads 9.7v. So, what is the reason of this tragedy?

***Edit:***

I think that the smoke was from a component close to the processor. Right now, when I attach a 9v battery to the board, both the ON LED and the L LED remains on. The processor also warm.

title: 9v adapter burned out Leonardo style board

Answers: 0


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

title: Using a web server with Arduino

Answers: 2

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


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

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

Answers: 2

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


body:
I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:

    #define IRSENSOR PIND
    int irpin = 2;

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?

To read the sensor I use this code:

    while (IRSENSOR & (1 << irpin )) {

Have no idea why this work. Does anyone know this kind of programming with arduino?

title: What is this PIND command

Answers: 2

body:
PIND refers to the arduino's IO register for input in port D

Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN*, DDR*, and PORT*; B,C, and D).

The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.

In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.

Pin 9 is actually bit 1 of port B, not D, so see if this works:

    #define IRSENSOR PINB
    int irpin = 1;

alternatly, using a reference instead of define,

    volatile uint8_t& IRSENSOR = PINB;
    int irpin = 1;

body:
Reason explained by @BrettM. To be more perfect use macros everywhere, e.g.:

    #define IRSENSOR PIND
    #define IRSENSOR_PIN PD2

    while (IRSENSOR & _BV(IRSENSOR_PIN)) {

Arduino's *digitalWrite(),digitalRead(),pinMode()* functions are useless for more serious coding because they are 1) slow 2) you cannot address pins not connected to headers (e.g. at *Arduino2560*).


body:
I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.

My code is very simple:

    void setup() {

     Serial.begin(9600);
     //pin 12 as output
     DDRB = B00010000;
     //pin 12 as low
     PORTB = B00000000;

    }

    void loop() {

     //pin 12 as high
     PORTB = B00010000;
     delayMicroseconds(10);
     //pin 12 as low
     PORTB = B00000000;

     long start_time = micros();

     //While reading high in pin 13 keep running the loop
     while (PINB & B00100000)) {

     }

     Serial.println(micros() - start_time);

     delay(1000);

    }

The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?

title: Port register not working

Answers: 1

body:
According to anything I could find, the Echo output is normally *low* and then goes *high* for a duration equal to the range. Your initial while condition is inverted, and you need to check for *both* edges.

    unsigned long up, down;

    // trigger pulse
    while (!(PINB & _BV(PB5)))
      ; // wait for leading edge
    up = millis();
    while (PINB & _BV(PB5))
      ; // wait for trailing edge
    down = millis();
    Serial.println(down - up);


body:
I got an Ethermega, and learned that Pin 13 already has a LED.

Are there other digital pins with special circuitry or already allocated to a specific function? (like usb,serial,ethernet,sd, etc)

I need about 30 inputs so I can skip some if that would avoid headaches.

title: Arduino Mega: which Digital pins are already used for something?

Answers: 2

body:
Don't worry about the led on pin 13, it just sits there but doesn't block anything.

You can still use the pin as a normal IO pin.

You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.

I have never used the **MCP23017** mentioned by *Martynas*, but the linked article looks very interesting and I'll definitely order one of these amazing chips!

Another option might be using 8 bit PISO (*parallel in - serial out* shift registers, such as the **74HC165**. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via [SPI](http://arduino.cc/en/Reference/SPI).

Advantages:

- it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)

- the shift registers can be *daisychained*, subsequent calls of [ShiftIn](http://arduino.cc/en/Reference/ShiftIn) allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just **three pins** on your Arduino.

body:
D4: ChipSelect for the SD card reader (can be used if no SD is present)

D0 and D1 are Serial RX and TX (just like any other arduino)

D10: Ethernet enable line

D13: led. Led is connected via a mosfet, so it doesn't interfer (like on the uno)

D50, D51, D52: SPI for the ethernet chip and SD card

All this was found in the [schematic](https://github.com/freetronics/EtherMega/raw/master/EtherMega.pdf)


body:
running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds-
closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?

here is whats running:

    int i=0;
    int req=18;

    void setup(){
    Serial.begin(115200);
     DDRD = DDRD | B10000010;
     interrupts();
    pinMode(req,OUTPUT);
    }

    void loop(){
    i=1;
    digitalWrite(req, HIGH);
    delayMicroseconds(3); //gives 7.5 microsecond pulse?
    digitalWrite(req, LOW);

    while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
     delayMicroseconds(1);
     i=(i+1);}
     }

title: delayMicroseconds- error?

Answers: 2

body:
Unless you want program PWM timer as suggested in comment then for short delays you need calculate how many instruction cycles are needed to make such a delay based on clock/crystal frequency and make that delay in inline assembler to have code under control. To manipulate digital output use writing data to PINx (which is equal to xoring PORTx).

To satisfy exact 250ms you need compensate errors because of rounding. Arduino's delay/tick functions do it. For the long delays you need a simple scheduler not to spend all the CPU time for pulse generating.

body:
This a very partial answer. I do not know your requirements, whether or
not PWM can do the job, etc... I just wanted to point out that you can
make a pulse exactly 8 µs long with this:

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

    #include <util/delay.h>
    #include <util/atomic.h>

    // Pulse PD3 (digital 18 on Mega 2560)
    // for exactly 8 us (128 clock cycles @ 16 MHz)
    static void pulse() {
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
            PORTD |= 1 << 3;
            _delay_us(8 - 0.125);
            PORTD &= ~(1 << 3);
        }
    }

The `_delay_us()` function from avr-libc is actually cycle-accurate
inline assembly. The 0.125 µs I subtracted is the time needed by
the actual port writes: both the sbi and cbi instructions take two cycles
(0.125 µs), but that delay should only be counted once.
`digitalWrite()` should always be avoided in time-critical code.

The 242 µs delay between pulses would be harder to generate without
PWM. A timer interrupt at 4 kHz seems like the simplest option, but
it is not cycle-accurate.

**Edit**: here is the scope trace, showing a quite accurate timing:

![oscilloscope trace](https://i.stack.imgur.com/0ekEE.png)


body:
I am working on a project involving the Uno, and I would like to benchmark the power requirements of Arduino. I am using the external 9V supply option.

Specifically, the Uno will be in to states,`power-intensive` and `power-save`. In the first mode, I am doing some heavy processing tasks (RF and some sensors are the only external loads), and the Arduino typically runs `loop()` without any delays. In the second mode, `loop()` is execued about every 10-40 seconds.

I am interested in benchmarking how much power is consumed in both states (I need this to estimate the size of the battery required for the 9V supply).

Obviously, googling yielded me solutions that involved measuring current using chips in series with the supply (I probably can pull this off with a multimeter). What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

title: Measuring power consumption on Arduino off of DC supply

Answers: 1

body:
>  What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power)


body:
I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?

I actually want to analogRead() a potentiometer inside the ISR.

This is my code so far, http://pastebin.com/ykpp78GB

And my circuit is just two potentiometers connected to pin A0 and A1.

title: Interrupts for analog inputs

Answers: 1

body:
It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.

It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.

In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.


body:
I'm working on using my Raspberry Pi (Raspbian) to upload sketches. However, I'm not sure which package is appropriate for command line usage (like described [here on Github][1]).

It seems like `sudo apt-get install arduino` would install the whole IDE, not just the command line. It seems like `arduino-core` would be more fitted for this purpose. However, the repository has a note online to use a package called `arduino-mk` for a CLI, which is what I want. However, this concerns me [in the repository's page][2]:

> This package will install a **Makefile** to allow for CLI programming of the Arduino platform.

(Emphasis mine)

What exactly does this mean? What are the differences between the three packages available?

  [1]: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
  [2]: https://packages.debian.org/wheezy/arduino-mk

title: Different Arduino packages on Raspbian

Answers: 2

body:
I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:

**arduino**: The whole java IDE and avr code libraries

**arduino-core**: the libraries and code that comes with arduino to be compiled for avr

**arduino-mk**: a makefile for compiling arduino code without the IDE (but no code)

The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.

I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.

The makefile is a configuration for the [gnu make][1] software. There is some information on the specific usage of the arduino makefile on its github page [here][2]

  [1]: https://www.gnu.org/software/make/
  [2]: https://github.com/sudar/Arduino-Makefile

body: Previous versions of arduino-mk had a dependency on arduino, which was everything, but with the split out of arduino-core, which both of the other packages now depend, arduino only includes the ide, everything else is in core so that you do not need the ide to develop, compile and load standard projects to your Arduino. I have only used the ide for less than 15 minutes And do all my work using vi and the command line. the makefile allows you to compile ino files with a make just by linking it into your project directory, it also has options for uploading using make.


body:
I have written a code for my Arduino which spans multiple files, In the file containing the main task, i have a Global Array like this

    addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

where

    #define NUM_CHILDS 0x02
    #define CHILD1_I2C_ADDR   0x10
    #define CHILD2_I2C_ADDR   0x02

Now to debug my issue, in my Task i do this

    Serial.print(childAddr[0]);
    Serial.print(childAddr[1]);

All i receive is

    00

I looked at the issue online, someone pointed it towards overshooting the RAM, I am working on a Pro Mini with ATmega328P with 2K RAM.
![This is my Output for analyzing the eld with "avr-size"  utility][1]

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

title: Global Arrays read as Zero

Answers: 2

body:
Since `addr_t` is a character type, I suspect `Serial.print()` is trying to output the ASCII character representation of your two values. ASCII codes 0x10 and 0x02 are non-printing characters, so it might just be outputting 0's for lack of anything better to do.

To output the data as actual numbers, try casting them to integers:
<!-- lang-all:cpp -->

    Serial.print( static_cast<unsigned int>(childAddr[0]) );
    Serial.print( static_cast<unsigned int>(childAddr[1]) );

body:
You should try to post a minimal piece of code that reproduces your problem. From what you posted I assembled this:

    typedef unsigned char addr_t;

    #define NUM_CHILDS  0x02
    #define CHILD1_I2C_ADDR         0x10
    #define CHILD2_I2C_ADDR         0x02

    addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println(childAddr[0]);
      Serial.println(childAddr[1]);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output is:

    16
    2

Clearly the problem isn't where you think it is.

---

By the way, in your file `Project.h` you have this:

    #include "Project.h"

Why is it including itself?

---

    void commRxISR(int count){
     /*
      ISR for the dats received on the I2C bus
     */
     Serial.write("Inside serial receive ISR\n");
     while (1);
     while (0 < Wire.available()){
      MyNode.commChild.commWriteInBuffer(Wire.read()); // Project specific implementation
     }
    }

The infinite loop in the ISR is interesting. Also don't do Serial prints inside an ISR. They can (almost certainly will) hang the system.


body:
Shift registers need 3 digital pins in order to work (data, clock and latch), but Attiny45/85 chips provides 2 digital and 2 analog pins.

Would I use 1 analog pin as digital pin? How?

title: Shift register on Attiny85 programmed by Arduino

Answers: 2

body: The ATtinyX5 does not have *any* analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).

body:
As *Ingnacio has already pointed out*, **PB0** to **PB4** can be used as digital IO ports **without problems**. It night be a good idea though not to touch **PB6**, the `RESET` pin.

Btw, this isn't different from an Arduino, where all so-called *analog pins* can be used for digital output as well.

If you want to drive shift registers from an ATtiny85 using SPI, you might want to have a look at the [tinySPI](https://github.com/JChristensen/tinySPI) library written by **Jack Christensen**. *Please note that I haven't used this library personally!*


body:
I am looking for a way to control an LED on a circuit board using audio input for learning purposes.

I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with **fft** or **dct** operations on audio input divided into 10ms frames.

Any advice will be appreciated.

title: Using Arduino audio to control an LED light

Answers: 1

body: The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.


body:
I have written a code that transmits data over the I2C channel, The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTrasnmission().

I found the issue using Serial debug messages.

Strange thing:

When i disconnect the SCL line (A5 on arduino Pro Mini), the hang disappears and the code starts to function again.

A search brought me to this forum
http://forum.arduino.cc/index.php?topic=66353.0

where a guy talks about the code snippet

    if(hang)
    unfreeze();

is this possible, if yes where do i place it?

Observation:  The hang goes away if i disconnect the SCL line on either of the arduinos communicating, the sam edoes not happen if i disconnect the SDA.

title: Wire.endTransmission() Hangs

Answers: 1

body:
> The device ID and every other stuff is working fine. The only issue being that my code gets stuck at Wire.endTransmission().

* Nothing is transmitted until you call `Wire.endTransmission()` so that is where it will hang.

* You should not try to do Wire transmissions inside an ISR (if you are doing that).

* There is an alternative to the Wire library which times-out rather than hanging. It is at: [Arduino I2C Master Library](https://github.com/rambo/I2C).

* Make sure you have pull-up resistors on SDA and SCL. Typically 4.7 k from both to +5 V.

* If none of that helps, please post your code.


body:
Hi I have this ultrasonic sensor:

http://www.micropik.com/PDF/HCSR04.pdf

I use this code to read distances:

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

    digitalWrite(trigPin, LOW);
    delayMicroseconds(5);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    long time = pulseIn(echoPin,HIGH);

My question is this: in the datasheet says that the sensor will send 8 pulses at 40khz. Every pulse will take 0.000025 seconds so 8 pulses would be 200 usec.

So why the delay is only 10 usec if it should be 200usec?

title: Ultrassonic sensor

Answers: 2

body: The 10us delay is just your trigger pulse HIGH phase. Refer to the timing diagram on bottom of page two in your datasheet.

body: The 10 us pulse to the TRIG pin activates the ultrasonic detector. It then sends 8 pulses at 40 kHz, and finally, sends a pulse to the ECHO pin. That pulse sent to the ECHO pin has a pulse-width proportional to the distance of the nearest object.


body: Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

title: Using Intel Galileo Ethernet Port

Answers: 3

body:
The Galileo board is Arduino compatible; meaning that you can run Arduino sketches on it, and use its I/O pins the same way you would with, say, Arduino Uno.

Therefor you can communicate between Galileo and Arduino the same way you would with two Arduino devices. This can be done using your favorite communication channel - Serial, I2C, OneWire, RF or even Infrared - it all depends what exactly are your needs, knowledge and timing requirements. Of course, doing it this way, would require you to have code running on both the Galileo and the Arduino, in charge of the inter-communication.

By doing so, you could utilize the Galileo as a 'server' as you say, that will receive commands from the Arduino, send them over the network and reply to the Arduino with the response.

body:
Yup - the Galileo Ethernet port works the same way as any other Arduino. For some sketch examples have a look at

> File > Examples > Ethernet

body:
I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)

Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access the wonderful world of BSD sockets (much more powerful than the sockets within the W5100).

Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script that changes the IP parameters at startup, but it's pretty heavy to do.