message:
Timestamp in Arduino

int sensorArray[32] ;
    int selectPinZero = 8;
    int selectPinOne = 9;
    int selectPinTwo = 10;
    int selectpinthree=11;
    int Enablepin=7;

    int inputPinOne = 0;
    int inputPinTwo = 1;

    int sensor1;
    int sensor2;
    int voltage1;
    int voltage2;
    int Current_Sensor1[16];
    int Current_Sensor2[16];
    int row;
    int column;

    int array[17][5]={
                        {0,0,0,0,0},
                        {0,0,0,0,1},
                        {0,0,0,1,0},
                        {0,0,0,1,1},
                        {0,0,1,0,0},
                        {0,0,1,0,1},
                        {0,0,1,1,0},
                        {0,0,1,1,1},
                        {0,1,0,0,0},
                        {0,1,0,0,1 },
                        {0,1,0,1,0},
                        {0,1,0,1,1},
                        {0,1,1,0,0 },
                        {0,1,1,0,1},
                        {0,1,1,1,0 },
                        {0,1,1,1,1},
                        {1,0,0,0,0}
                     };

    unsigned long StopTime=0;
    int Counter=0;

    void setup(){

      Serial.begin(9600);
      pinMode(selectPinZero, OUTPUT);
      pinMode(selectPinOne, OUTPUT);
      pinMode(selectPinTwo, OUTPUT);
      pinMode(selectpinthree,OUTPUT);

      pinMode(inputPinOne, INPUT);
      pinMode(inputPinTwo, INPUT);
    }

    void loop()
    {

      for(row=0;row<17;row++)
      {

        digitalWrite(Enablepin,array[row][0]);
        digitalWrite(selectPinZero,array[row][1]);
        digitalWrite(selectPinOne,array[row][2]);
        digitalWrite(selectPinTwo,array[row][3]);
        digitalWrite(selectpinthree,array[row][4]);
        sensor1=analogRead(inputPinOne);
        sensor2=analogRead(inputPinTwo);
        voltage1=sensor1 * ARDUINO_ANALOG_SCALING;
        voltage2=sensor2* ARDUINO_ANALOG_SCALING;
        Current_Sensor1[row]=(10*voltage1)-25;
        Current_Sensor2[row]=(10*voltage2)-25;
        Serial.print("Currentsensor1:");
        Serial.println( Current_Sensor1[row]);
        Serial.print("Currentsensor2:");
        Serial.println( Current_Sensor2[row]);
         Counter=Counter+1;
        Serial.print("Counter:");
        Serial.println(Counter);
        Serial.println(".......................");
            delay(1000);

         }
    }

Here is my Arduino code. I wanted to activate Digital pin for every 1000ms delay.

During each delay the analog value should be stored in an array of index.

I don't know how to keep track of analog value read, or from which port I am reading. I could flicker the LED on the hardware side but it doesn't make any sense. Any method you can suggest here?

Application:

I have 32 hall sensors connected via mux circuit. I wanted to know which sensor is reading value. I want any idea to might suggest to me to keep track here.

body:
You should download timer1 library from http://playground.arduino.cc/Code/Timer1

Init timer1 with a value of 1000000 and it will perform an overflow every second. On every overflow it will perform an action, put your code to activate a pin there. And do the serial readings in your loop.


sender: user

message:
Sending data from a GUI to an Arduino nano via USB

Can somebody point me in the right direction for information on sending data to an Arduino nano?

My project is to send data that is updated from a GUI (presently written in Python) to an Arduino nano that then makes adjustments to a number of servo motors.

I have the servo code working but am presently using potentiometers to control the servo positions & would like the control done via a GUI.

What libraries would I need to be looking at. Have any of you done anything similar.

Thanks

Nic

sender: assistant

body:
Arduino Nano supports FTDI i.e. Virtual Serial Port. So all you have to do is initialize the serial communication using [pySerial][1].

When the data is entered into the GUI, store it in some variables. Send the data in variables to Arduino using Serial Communication. You might have design your own communication protocol on top of Virtual Serial Port in order to identify the data.

You can also use the same library to send the acknowledgement or some data from Arduino to PC, if you want.

Hope this helps you.

  [1]: https://pypi.python.org/pypi/pyserial


message:
How to improve wiring a breadboard?

just saw this tweet and was interested what wires are used there:

https://twitter.com/EngineersGarage/status/448014811280842752/photo/1

![enter image description here][1]

The wiring Looks cleaner than the setup I currently have with "normal" wires.

Thanks!

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

body:
I think the wire itself is perfectly normal. It looks like he's simply soldered right-angled header pins onto the ends. That way, the wires can lie flat on the breadboard instead of being bent over for connections, meaning the whole thing is lower-profile and a little easier to route neatly.

It also has the advantage that they will probably survive far more insertions/removals. With that said, it brings the disadvantage that it exposes the contacts more above the surface of the board, which could increase the risk of accidental connections (short circuits and such like).


body:
Using good wires helps to build clean breadboard setups. I also found that it greatly helps to wire vertically only and to use the breadboard for horizontal connections. If you look at my picture, wires are always vertical. This is easy to achieve when you work with buses like I²C. As you can see, I also used horizontal lines from another breadboard as you can use these like Lego bricks, though you need to cut the adhesive tape in the back. For the wires, I used standard Solderless Breadboard Jumper Cable Wire that you can buy almost everywhere online.

You can also check other pictures on my blog: http://ouilogique.com/horloge_cycles_ultradiens/

[![enter image description here][1]][1]

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


message:
Setting a Pin to HIGH to simulate a button with a "pull up" resistor

in the below Fritzing diagram, I have a button that has a pull-up resistor, which when pressed, sets the GPIO Pin 23 to HIGH. On the Raspberry Pi, when the button is released, the GPIO goes LOW. The Raspberry Pi detects when the button is released and pressed. This is my desired behavior.

However, in my current configuration, I have PIN 13 connected to the Base of a NPN transistor to try to simulate the same behavior as the button with a pull-up resistor. When pin 13 is set to high, it sets the GPIO 22 Pin to high. When I set the Arduino Pin 13 to low, The GPIO Pin goes low but the Raspberry PI does not detect that GPIO 22 pin went low. Is there a way to simulate the same behavior as a button with a pull-up resistor with an OUTPUT pin from the arduino?

![enter image description here][1]

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

body:
If you don't mind using SMD components you could use the NX3V1G66 analog switch.

When you send a signal to the IC it will simulate a push button.

Maybe there are leaded versions of this IC but I haven't found them on the website where I order all my components.


body:
First of all, I don't think you will need *full* simulation of a button. There are a couple of things this approach won't have:

 - Bouncing: it'll be (kinda, minus interference) a square wave. With a real button, the metal contacts "bounce," thus creating a weird waveform. Depending on interference, you'll still need debouncing code, although I would be surprised if it was necessary. I'd inlcude it in case I modified it to add a real button and/or there's some weird interference.
 - The time it's "pushed" may be very short, depending on your code. Keep this in mind when designing this.

Basically, you're hooking up the Arduino and the RPi together, with a voltage divider or a level shifter between the two.

Voltage divider:

> ![][1]

*[Sparkfun](https://learn.sparkfun.com/tutorials/voltage-dividers/all?print=1)*

That is a voltage regulator (drawn four different ways; it's the same circuit). I calculated the values you will need: 1700 ohm for R1, 3300 ohm for R2.

Of course, serial (with USB of the Arduino) communication would be a lot easier...

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


body:
I don't think your circuit is correct. If red is positive and your switch is momentary closed then it actually pulls GPIO23 low.

Likewise with the NPN transistor, using it in this way gives you an inverter. It should work if internal pull ups are enabled on GPIO22 and you remove the resistor.

IF GPIO23 is 5V tolerant, you can instead connect the resistor to 5V and GPIO23 straight to the collector.

You should also have a 1K resistor between the arduino pin 13 and the base of the transistor to limit the base current.

This all assumes that the VCE of the transistor is lower than the 0.8V low-level cutoff of the GPIO pins (it should be).

In any case, if GPIO23 is 5V tolerant, just connect it straight to the Arduino. If it isn't, follow penguins advice and use a voltage divider.


body: So the solution to this was to remove the transistor all together and connect the Arduino pin directly to the Pi. However, I need to change my Arduino sketch. The approach was to set the pin HIGH and go LOW when selected. I had it backwards.


message:
Is arduino starter kit disappearing?

It seems they stop the production of arduino starter kit (official), it's hard to find it on pro website.
Is there an other very good starter kit to start ? I mean I would like to try everything on small given project before starting my own project.

body:
Make has one: [Getting Started with Arduino Kit v3.0][1]

  [1]: http://www.makershed.com/Getting_Started_with_Arduino_Kit_v3_0_p/msgsa.htm


body:
AFAIK, it's still available on the [arduino store][1] website

  [1]: http://store.arduino.cc/index.php?main_page=product_info&cPath=2&products_id=185


body:
I recommmend you this one: [Beginner Learning Kit for Arduino][1], but they do not add the code here.

  [1]: http://www.icstation.com/product_info.php?products_id=3515#.VI-s8clGTQs


message:
Decimals missing when using radio.write(); with Arduino

I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.

I'm sure there's something wrong on the transmitter part of the code, but I can't see what.

Here's my code:

    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>

    OneWire oneWire(4);

    DallasTemperature sensors(&oneWire);

    // ce,csn pins
    RF24 radio(8,7);

    // init data buffer to hold a sensor type byte and one uint16_t sensor data
    unsigned char data[3] = {
      0};
    unsigned long count=0;
    void setup(void)
    {
      sensors.begin();
      Serial.begin(57600);
      Serial.println("**************V1 Send Sensor Data***********");
      radio.begin();
      radio.setPALevel(RF24_PA_LOW);
      radio.setChannel(0x4c);

      // open pipe for writing
      radio.openWritingPipe(0xF0F0F0F0E1LL);

      radio.enableDynamicPayloads();
      radio.setAutoAck(true);
      radio.powerUp();
      Serial.println("...Sending");
    }

    void loop(void)
    {

      sensors.requestTemperatures();
      float currentTemp;
      currentTemp = sensors.getTempCByIndex(0);

      //assign 'T' to represent a Temperature reading
      data[0] = 'T';

      data[1] = currentTemp;

      count++;

      sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
      radio.txMode(strlen(data));               // set # bytes to xmit
      radio.write(data);                        // send bytes

      // print and increment the counter
      Serial.print("Temperature sent:  ");
      Serial.println(currentTemp);
      // pause a second
      delay(500);
    }

In this example, when I print currentTemp, it will display the decimals, but if I print data[1], it won't.

What am I missing?

**EDIT:**

I've modified the code to include the answer from JRobert (updated code above), but it comes back the following error:

    nrf24SendSensorDataV1_ino.cpp: In function 'void loop()':
    nrf24SendSensorDataV1_ino:56: error: invalid conversion from 'unsigned char*' to 'char*'
    nrf24SendSensorDataV1_ino:56: error: initializing argument 1 of 'int sprintf(char*, const char*, ...)'
    nrf24SendSensorDataV1_ino:57: error: 'class RF24' has no member named 'txMode'
    nrf24SendSensorDataV1_ino:57: error: invalid conversion from 'unsigned char*' to 'const char*'
    nrf24SendSensorDataV1_ino:57: error: initializing argument 1 of 'size_t strlen(const char*)'
    nrf24SendSensorDataV1_ino:58: error: no matching function for call to 'RF24::write(unsigned char [3])'
    C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t)

Any thoughts?

**EDIT 2**

I've made a dirty fix that will solve the issue.

In the transmitter code I've added:

    uint16_t sensorValue = currentTemp*100;
    //do the bit shift to put uint16 into uint8 array
    data[1] = sensorValue >> 8;
    data[2] = sensorValue;
    // print and increment the counter
    radio.write(data, sizeof(uint16_t)+1);

This will send the (temperature value)*100

On the receiver end, I just convert the uint16_t to a float element and divide it by 100.

    uint16_t sensorValue = data[2] | data[1] << 8;
    float temp = (float) sensorValue/100;
    Serial.print("T: ");
    Serial.println(temp);

Dirty, but effective!

Many thanks guys for the help, it really pointed me and my lousy programming skills to the right direction.

body:
Since I can't comment yet I will place this as answer.

But have you tried to use `radio.print(data[1], DEC);` ?

DEC stands for Decimal for if you want to force something to print it in Decimals. When you want something to be printed in Hexadecimals you can use HEX for example. Hope this will help you.


body: data[] is an array of three chars.  You assign the letter "T" to data[0] (the first char of the array), then data[1] = currentTemp attempts to assign a float to the second char in the data array - floats won't fit in chars.


body:
From the Arduino playground [documentation][1] for the Nrf2401 library, the .write method accepts either: a byte to transmit, a pointer to your `unsigned char` buffer; or a void argument meaning use the library's internal buffer. You must have called the .txmode() method first.

Since you're trying to use your own buffer, you'll need to make it long enough to contain the message you want to transmit (plus one byte for the terminating NUL). You'll need a character representation of the value you want to send, not the binary number itself. At a quick read of the library doc I didn't see the message format the library wants, but assuming it's something like:
  `T<space>12.34<newline>`, you'll need something like this (untested, it may need tweaking)

    sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
    radio.txMode(strlen(data));               // set # bytes to xmit
    radio.write(data);                        // send bytes

  [1]: http://playground.arduino.cc/InterfacingWithHardware/Nrf2401


message:
Why does serial port stop sending data?

I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro.

I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.

One pressure sensor is digital, using the Wire lib, and the other is analog.

My sketch compiles, runs, and works until I try to get the data in Python using pyserial.

If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it.  If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string.  This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE.  Once the serial port stops sending, I have to reset the Leonardo in order to read new data.

I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data.  Another option is that the Wire protocol is getting stuck and halting the program.

Here's my sketch

    #include <Wire.h>

    int ADDRESS = 0x28;//I2C address of sensor
    int REQUEST = 4;//# of bytes to request from sensor
    int BAUD = 19200;//serial rate
    int PRESSURE_PIN = 1;

    void setup()
    {
      pinMode(A1, INPUT);
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(BAUD);  // start serial for output
    }

    void loop()
    {
      Wire.requestFrom(ADDRESS, REQUEST);    // request 6 bytes from slave device #2

      Serial.print(analogRead(PRESSURE_PIN));
      Serial.print(',');

      while(Wire.available())    // slave may send less than requested
      {
         Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
         Serial.print(',');
         Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
      }

      delay(10);
    }

and here is how I read it from python

    import serial

    serial_port = '/dev/tty.usbmodem1a1221'
    ser = serial.Serial(serial_port, 19200, timeout=0)

    vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)]

body:
The Arduino forums talk the Arduino resetting when the serial port is opened. A solution as stated in the forums is to add a short delay. See if that works.

Source: http://forum.arduino.cc/index.php/topic,18371.0.html


body:
The leonardo [doesn't reset][1] when the serial port is opened.

To check it isn't python, run your Arduino code, then open the terminal and run

    screen /dev/tty.usbmodem1a1221 19200

NOTE: to exit the screen session type Ctrl-A Ctrl=\ (see [here][2]). If you just close the window it will stay connected and lock up the serial port until you recycle the power on the Arduino.

If the Arduino program spits out just fine to screen, then python is the problem. One thing that can happen is a python/java/whatever program can lock up the serial port driver, *but recycling the Arduino power, not restarting the program,* is required to reinitialise the driver. So the Arduino is not necessarily problem, as the serial port will stay locked up for ALL programs. So "I would expect future calls to return data" is actually wrong. If I stuff up the serial port code in my java interface programs the same kind of thing happens.

Other ideas:

* Make the delay longer than 10ms.
* Make sure hardware flow control is off in the python serial
* Flash a LED in the Arduino loop to see if it is the main loop locked up or if that is running fine.

  [1]: http://arduino.cc/en/Guide/ArduinoLeonardoMicro?from=Guide.ArduinoLeonardo
  [2]: http://hints.macworld.com/article.php?story=20061109133825654


body:
My eventual workaround for the Leonardo was to set up a call-response loop on the Leonardo.  Here's the code:

    #include <Wire.h>

    int ADDRESS = 0x28;//I2C address of sensor
    int REQUEST = 4;//# of bytes to request from sensor
    int BAUD = 19200;//serial rate

    void setup()
    {
      pinMode(A1, INPUT);
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(BAUD);  // start serial for output
    }

    void loop()
    {
      if (Serial.available() > 0) {
        Serial.read();
        Wire.requestFrom(ADDRESS, REQUEST);    // request 4 bytes from slave device at 0x28
        while(Wire.available())    // slave may send less than requested
        {
           Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
           Serial.print(',');
           Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
        }
      }
    }

I was able to simplify a little.

There are two things to note:

* There is no built in delay and requests made too quickly will result in either an empty response or old data from the sensor.  Have to take into account in requesting program.

* The sketch will respond a number of times equal to the number of bits sent.  Use a single ASCII character for one response, 2 characters for 2 responses, etc...  This is important if you use an API similiar to a write() and writeln() as the second sends extra characters.


message:
Significance of the numbers used in the manual

i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.

For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.

Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?

Thanks!

body:
The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).

It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).

However, `analogWrite()` works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.

That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.

The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for `analogWrite()`.

You can get more information from the online documentation for Arduino:

 * http://arduino.cc/en/Reference/AnalogRead
 * http://arduino.cc/en/Reference/AnalogWrite


body:
More explanation: binary numbers are different than base 10 as you probably know. The meaning of those numbers is simple.

Start with 1 and double it. Keep doubling. You will soon hit 256 (computers start at 0 not 1,  so you have to take that into account, 0-255 is 256 different values). Keep doubling and you will soon hit 1024 (0-1023).

So these numbers are not arbitrary, they are Base 10 (0-9 like you learned in school) representations of Binary Numbers, more specifically, the high limit a given length of binary digits can represent before having to add another digit.

1111111 is binary for 127, with 0 thats 128 different values those 7 digits can represent. To get to 255, you have to add a digit for 8 total digits, 11111111 = 255. 9 digits or 111111111 = 511 and ten digits or 1111111111 = 1023.


body:
To clarify, analogRead() has a 10 bit range due to the arduino's Analog to Digital Converter, or ADC. 10 bits can store 1024 (2^10) different values; counting zero as a value gives the range 0-1023.

In arduino 0 is the reading when a pin is grounded, 1023 is the reading when an analog pin is connected to Vref, or 5v if there is nothing wired to Vref. The sensors provide a voltage somewhere between these values, but not the actual numbers your code gets.

analogWrite() accepts 8 bit numbers. That is 2^8 or 256 different values, called 0-255. It only simulates an analog voltage by pulsing a pin rapidly.

In short, the numbers are not arbitrary, but express the limits of the arduino chip's IO. They look random because they were written in decimal, but in binary they are very simple. If you are interested, you could look into replacing the decimal numbers in the code with hexadecimal numbers, which make their binary representations very obvious by way of 16 being 2^4.


message:
Reading CMPS10 raw values

I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)

    i2cBus->beginTransmission(I2C_Address);
    i2cBus->write(byte(10));
    i2cBus->endTransmission();

    i2cBus->requestFrom(I2C_Address, 4);
    xMagHighByte = i2cBus->read();
    xMagLowByte = i2cBus->read();
    yMagHighByte = i2cBus->read();
    yMagLowByte = i2cBus->read();

    xMag = short(xMagHighByte<<8);
    xMag |= xMagLowByte;
    yMag = short(yMagHighByte<<8);
    yMag |= yMagLowByte;

    if(yMag!=0){
      magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
    }
    else if(xMag>0) magBearing=0.0;
    else if(xMag<0) magBearing=180.0;
    else magBearing = 1000;
    if(magBearing < 0) magBearing+=360;
    magBearing=360-magBearing;
    return magBearing;

body:
Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.

But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.

To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,

    float Scale, Shift, Value;
    Scale =  (max-min)/2;
    Shift = -(max+min)/2;
    Value = float(raw+Shift)/Scale;

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.


message:
Reset fuses on atmega328p using Arduino

I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:

    avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

Response:

    avrdude.exe: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude.exe: Device signature = 0x1e950f
    avrdude.exe: reading input file "0x62"
    avrdude.exe: writing lfuse (1 bytes):

    Writing |  ***failed;
    ################################################## | 100% 0.06s

    avrdude.exe: 1 bytes of lfuse written
    avrdude.exe: verifying lfuse memory against 0x62:
    avrdude.exe: load data lfuse data from input file 0x62:
    avrdude.exe: input file 0x62 contains 1 bytes
    avrdude.exe: reading on-chip lfuse data:

    Reading | ################################################## | 100% 0.00s

    avrdude.exe: verifying ...
    avrdude.exe: verification error, first mismatch at byte 0x0000
                 0x62 != 0x00
    avrdude.exe: verification error; content mismatch

    avrdude.exe: safemode: lfuse changed! Was 62, and is now 0
    Would you like this fuse to be changed back? [y/n]

body: You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the `lfuse`, `hfuse`, and `efuse` memory types to read and write the fuse bytes.


message:
Using ArduinoISP on an Arduino Uno to program an ATmega328

I have an Arduino Uno R3 and would like to use it to program a blank ATmega328 on a breadboard. I've followed the instructions for the 8 MHz version on http://arduino.cc/en/Tutorial/ArduinoToBreadboard with an added 10K pullup resistor on the `RESET` pin of the ATmega328 on the breadboard; and I've uploaded the `ArduinoISP` sketch from the Arduino 1.0.5 distribution to my Uno.

I've also added the metadata for my setup: the following is the contents of  `~/sketchbook/hardware/breadboard/boards.txt`:

    atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

    atmega328bb.upload.protocol=stk500v1
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=57600

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05
    atmega328bb.bootloader.path=arduino:atmega
    atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328
    atmega328bb.build.f_cpu=8000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

I've also added the following section to my `~/.avrduderc` file:

    part
        id   = "m328";
        desc  = "ATMEGA328";
        has_debugwire = yes;
        flash_instr  = 0xB6, 0x01, 0x11;
        eeprom_instr = 0xBD, 0xF2, 0xBD, 0xE1, 0xBB, 0xCF, 0xB4, 0x00,
         0xBE, 0x01, 0xB6, 0x01, 0xBC, 0x00, 0xBB, 0xBF,
         0x99, 0xF9, 0xBB, 0xAF;
        stk500_devcode = 0x86;
        # avr910_devcode = 0x;
        signature  = 0x1e 0x95 0x14;
        pagel  = 0xd7;
        bs2   = 0xc2;
        chip_erase_delay = 9000;
        pgm_enable = "1 0 1 0 1 1 0 0 0 1 0 1 0 0 1 1",
       "x x x x x x x x x x x x x x x x";

        chip_erase = "1 0 1 0 1 1 0 0 1 0 0 x x x x x",
       "x x x x x x x x x x x x x x x x";

        timeout = 200;
        stabdelay = 100;
        cmdexedelay = 25;
        synchloops = 32;
        bytedelay = 0;
        pollindex = 3;
        pollvalue = 0x53;
        predelay = 1;
        postdelay = 1;
        pollmethod = 1;

        pp_controlstack =
     0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F,
     0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F,
     0x66, 0x76, 0x67, 0x77, 0x6A, 0x7A, 0x6B, 0x7B,
     0xBE, 0xFD, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00;
        hventerstabdelay = 100;
        progmodedelay = 0;
        latchcycles  = 5;
        togglevtg  = 1;
        poweroffdelay = 15;
        resetdelayms = 1;
        resetdelayus = 0;
        hvleavestabdelay = 15;
        resetdelay  = 15;
        chiperasepulsewidth = 0;
        chiperasepolltimeout = 10;
        programfusepulsewidth = 0;
        programfusepolltimeout = 5;
        programlockpulsewidth = 0;
        programlockpolltimeout = 5;

        memory "eeprom"
     paged  = no;
     page_size = 4;
     size  = 1024;
     min_write_delay = 3600;
     max_write_delay = 3600;
     readback_p1 = 0xff;
     readback_p2 = 0xff;
     read = " 1 0 1 0 0 0 0 0",
            " 0 0 0 x x x a9 a8",
            " a7 a6 a5 a4 a3 a2 a1 a0",
            " o o o o o o o o";

     write = " 1 1 0 0 0 0 0 0",
            " 0 0 0 x x x a9 a8",
      " a7 a6 a5 a4 a3 a2 a1 a0",
      " i i i i i i i i";

     loadpage_lo = " 1 1 0 0 0 0 0 1",
            " 0 0 0 0 0 0 0 0",
            " 0 0 0 0 0 0 a1 a0",
            " i i i i i i i i";

     writepage = " 1 1 0 0 0 0 1 0",
          " 0 0 x x x x a9 a8",
          " a7 a6 a5 a4 a3 a2 0 0",
          " x x x x x x x x";

     mode  = 0x41;
     delay  = 20;
     blocksize = 4;
     readsize = 256;
        ;

        memory "flash"
     paged  = yes;
     size  = 32768;
     page_size = 128;
     num_pages = 256;
     min_write_delay = 4500;
     max_write_delay = 4500;
     readback_p1 = 0xff;
     readback_p2 = 0xff;
     read_lo = " 0 0 1 0 0 0 0 0",
        " 0 0 a13 a12 a11 a10 a9 a8",
        " a7 a6 a5 a4 a3 a2 a1 a0",
        " o o o o o o o o";

     read_hi = " 0 0 1 0 1 0 0 0",
        " 0 0 a13 a12 a11 a10 a9 a8",
        " a7 a6 a5 a4 a3 a2 a1 a0",
        " o o o o o o o o";

     loadpage_lo = " 0 1 0 0 0 0 0 0",
            " 0 0 0 x x x x x",
            " x x a5 a4 a3 a2 a1 a0",
            " i i i i i i i i";

     loadpage_hi = " 0 1 0 0 1 0 0 0",
            " 0 0 0 x x x x x",
            " x x a5 a4 a3 a2 a1 a0",
            " i i i i i i i i";

     writepage = " 0 1 0 0 1 1 0 0",
          " 0 0 a13 a12 a11 a10 a9 a8",
          " a7 a6 x x x x x x",
          " x x x x x x x x";

     mode  = 0x41;
     delay  = 6;
     blocksize = 128;
     readsize = 256;

        ;

        memory "lfuse"
     size = 1;
     min_write_delay = 4500;
     max_write_delay = 4500;
     read = "0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0",
            "x x x x x x x x o o o o o o o o";

     write = "1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0",
            "x x x x x x x x i i i i i i i i";
        ;

        memory "hfuse"
     size = 1;
     min_write_delay = 4500;
     max_write_delay = 4500;
     read = "0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0",
            "x x x x x x x x o o o o o o o o";

     write = "1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0",
            "x x x x x x x x i i i i i i i i";
        ;

        memory "efuse"
     size = 1;
     min_write_delay = 4500;
     max_write_delay = 4500;
     read = "0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0",
            "x x x x x x x x x x x x x o o o";

     write = "1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0",
            "x x x x x x x x x x x x x i i i";
        ;

        memory "lock"
     size = 1;
     min_write_delay = 4500;
     max_write_delay = 4500;
     read = "0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0",
            "x x x x x x x x x x o o o o o o";

     write = "1 0 1 0 1 1 0 0 1 1 1 x x x x x",
            "x x x x x x x x 1 1 i i i i i i";
        ;

        memory "calibration"
     size = 1;
     read = "0 0 1 1 1 0 0 0 0 0 0 x x x x x",
            "0 0 0 0 0 0 0 0 o o o o o o o o";
        ;

        memory "signature"
     size = 3;
     read = "0 0 1 1 0 0 0 0 0 0 0 x x x x x",
            "x x x x x x a1 a0 o o o o o o o o";
        ;
    ;

So I thought I'd be good to go: I've set the programmer type to `ArduinoISP` and the board type to `ATmega328 on a breadboard (8 MHz internal clock)` in the IDE.

However, when I try to either upload the Arduino bootloader, or use the `Upload using programmer` feature on the `Blink` example, I get this:

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

Full output:

    /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build6008715511691559175.tmp/Blink.cpp.hex:i

    avrdude: Version 5.11.1, compiled on Apr 28 2013 at 18:46:46
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
             User configuration file is "/home/cactus/.avrduderc"

             Using Port                    : /dev/ttyACM0
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
             AVR Part                      : ATMEGA328
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
    avrdude: Send: A [41] . [80]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [02]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [81]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [01]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [82]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [12]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [98]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
    avrdude: Send: A [41] . [84]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [85]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [86]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [87]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [89]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: Send: A [41] . [81]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [01]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [82]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [12]
    avrdude: Recv: . [10]
    avrdude: Send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: Send: P [50]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: AVR device initialized and ready to accept instructions

    Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: V [56] 0 [30] . [00] . [01] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    ################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    ################################## | 100% 0.06s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude: Send: Q [51]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]

    avrdude done.  Thank you.

I've double-checked and triple-checked, I've rebuilt the whole circuit on another breadboard with another ATmega328, I've even checked the jumper cables one by one, they all work.

How do I use my Arduino Uno as an ISP to upload code to this blank ATmega328?

body:
>     avrdude: Device signature = 0x000000
>     avrdude: Yikes!  Invalid device signature.
>              Double check connections and try again, or use -F to override
>              this check.

This is the clue to the solution. The signature is different between different versions of the ATmega328, for example:

 - ATmega328-PU
 - ATmega328P-PU

and so on...

You can google on "arduino signature error ATmega328P" to find the solution.

One hint is: http://forum.arduino.cc/index.php?topic=201920.0

I can be more specific if you post the version off the ATmega328 you have.


body: Do you have another UNO or similar? Try getting the boot loader upload working on a stock board just to confirm it is not the programmer. 0x000000 usually means it can't talk to the chip being programmed.


body:
Feeling really stupid about it in retrospect...

One last thing I tried was taking the ATmega328P out from the Arduino Uno and plugging the blank ATmega328 in its place, thinking I could use the Uno programmer as such to burn the bootloader on the chip. That didn't work and I don't know if it's supposed to work.

However, to plug the new chip into the DIL on the Uno, I had to bend the DIP legs inwards slightly to give it a smaller straddle. After seeing that it didn't work, I plugged the ATmega328P back into the Uno and plugged the ATmega328 back into the breadboard. However, this time, because of the smaller straddle, it slipped in deeper into the breadboard, the plastic package actually touching the board. And with this setup, wiring it up again via the Arduino and using the `ArduinoISP` I was able to burn both the bootloader and (via the 'Upload with programmer' functionality) test programs to it.

TL;DR: I didn't have the blank ATmega328 properly plugged into the breadboard...


message:
util/delay.h from arduino _delay_ms not delaying in accurate time with my hardware configuration

I have configured my arduino as a flash programmer and i'm sending data to an atmega328P. It is actually working and the data is send to my atmega328. But what is strange that the _delay_ms from <utils/delay.h> from the Arduino library is not delaying in accurate seconds.

 _delay_ms(1000) who should wait from 1s, is actually more 8 seconds from my atmega328P hardware point of view.

My question is what could possibly turn the program wrong. I'm strongly assuming that this a misconfigured clock cycle from my Atmega, but this is my newbie guess,  it can be something else, that's why I'm posting my question here. Can someone can hint me what's wrong with my configuration?

Here's the sample code, a dumb toggle pin on / off:

    #include <util/delay.h> // from arduino library

    /*
    */

     DDRB |= 0b0000001;

      while (1) {
        PORTB = 0b00000001;
        _delay_ms(1000); // it should be 1 second, but on my hardware it is more ~8 seconds

        PORTB = 0b00000000;
        _delay_ms(1000);
      }

And my configuration is (from arduino IDE)

*Arduino Pro / pro Mini (3,3v 8 Mhz) / Atmega 328*

I have tried with

*Arduino Pro / pro Mini (5v 16 Mhz) / Atmega 328*

expecting that more power will affect speed, but the result is actually the same.

body:
At a 30000 ft. level, it's because the defined `F_CPU` value doesn't match your hardware. This can happen because the incorrect device is chosen in the IDE or because the device is misconfigured in boards.txt, or because the hardware is somehow different from what is expected.

Given that you are using a bare ATmega328P, assuming that you've selected the correct crystal, and that the apparent time scale is 8x, it is likely that the CKDIV8 fuse is set. This means that the chip is running at 1/8 the crystal speed. You will need to unprogram (set to 1) bit 7 of the low fuse byte in order to reset it. Use AVRdude from the command line to read the low fuse byte (`-U lfuse:r:-:h`), set the bit (lfuse | 0x80), and then write it back (`-U lfuse:w:0xnn:m`).


message:
Interfacing Arduino through USB or I2C?

I am planning to connect multiple Arduinos to my Raspberry Pi. There are basically two ways I can achieve that:

1. Use an USB hub. Each Arduino will then be available through ordinary serial commands both for reading and writing. The USB hub I have is powered and can handle both communications and powering the Arduinos.

2. Use I2C, so that the Arduinos are I2C slaves of the Raspberry Pi.

Since USB is used for updating the Arduino, I don't have the best feeling about using this same connection for "management" tasks.

**Are there any known disadvantages to using the pre built USB socket on
the Arduino in "production", any best practises or similar saying that I should not do
this? Is this USB socket meant to be used for debugging and code deployment only?**

The plan is to let the computer send commands to the Arduinos using a serial protocol. The computer will automatically detect whenever an Arduino is connected and immediately send a "hello" command over serial. The Arduino is then supposed to send back its "name" and a list of capability keywords. A capability may be "motion-sensor". The computer will then know that it can ask the Arduino if it has detected motion. Other capabilities may be "temperature-sensor", "barometric-sensor", "lights".

It's for a generic open source home automation system/robotics system I am working on creating a framework for.

body:
One complication you should be aware of is that in its default configuration, an Arduino Uno (and I assume that is what you’re talking about) will automatically reset whenever a serial connection is opened to it. This is easily bypassed with a capacitor between RESET and GND, but not taking it into account might make for hours of debugging fun.

The other complication is that just after a power up or RESET, an Arduino will delay for a second or two to listen for a programmer connection on the serial port, but that’s something you’ll have to take into account anyway.


body:
I would go with USB rather than I2C for these reasons:

 - The Arduino can be powered via USB so there is no need for extra power supplies.
 - The system will work with PCs, making it easier to develop the code and the product more versatile.
 - USB cables are commercially available with standardised sockets. I2C cables would have to be made to specification (e.g. [this app note][1]) and would require some kind of additional socket for robust termination.
 - The Arduino Wire (I2C) library will hang if you disconnect the cable in the middle of waiting for a byte.

A good product will be robust and easy to use. One thing you may wish to consider is to create an internet of thing (IoT) type system. This involves the Arduinos sending sensor data to the web via the RPi. It could be that the RPi is a dumb conduit for the Arduinos, or it could collate the data and present itself as the end device. Check out Xively for details. I made a basic system to do the former, it is on github [here.][2]

  [1]: http://www.nxp.com/documents/application_note/AN10658.pdf
  [2]: https://github.com/geometrikal/serial-xively-bridge


body:
In my opinion, think USB on the Arduino is stable enough for production use.* There are ways to rename your Arduino if someone would connect it to a computer.

I think the real problem with this approach is people tampering with it. I know it's open source and all, but do you really want users (if it does get produced on a big scale, which is unlikely, but *possible*) without much tech knowledge plugging it into their computer?

If none of that sounds like a problem to you (and the delay/reset problems outlined by others isn't a big deal), I'd say go for USB. It's pretty easy to use, and it's universal, thus someone could connect the system to their computer if you developed the software for PC.

*Assuming you're using a full Arduino in a production environment, you won't care about if it shows up to the computer as "Arduino Uno."


message:
Why does increasing resistance make a capacitive sensor more sensitive?

From the [Capacitive Sensor Page](http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) on the Arduino website, it states the following:

> The capacitiveSensor method toggles a microcontroller send pin to a new state and then waits for the receive pin to change to the same state as the send pin. A variable is incremented inside a while loop to time the receive pin's state change. The method then reports the variable's value, which is in arbitrary units.

AND

> Use a 1 megohm resistor (or less maybe) for absolute touch to activate. With a 10 megohm resistor the sensor will start to respond 4-6 inches away. With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size)...

However, as mentioned above, what I'm measuring is the time taken to change state, and I understand that more resistance = more time taken = higher value, how exactly does increasing the resistance make the sensor more sensitive, allowing it to respond without even touching it (i.e., inches away)?

Am I not simply increasing the time taken to change state by increasing resistance? How would that make it more sensitive?!?

body: A capacitor is created from two conductors with a dielectric between them. The capacitance of the capacitor is determined by the surface area of the conductors and the distance between them. The larger the conductive surface, the higher the capacitance. **The further apart the conductors, the smaller the capacitance. Using a higher resistance means that you can use a smaller capacitance, i.e. be further away from the sensor**, to get the same results.


message:
How do I know if a board fits my requirements?

I'm new to Arduino and I saw on their website that there are many different kinds of boards.
What are the differences, or to be more specific, how would I know which board meets my requirements? I understand that the shields can be connected to the board, but are some boards that do not support certain shields?

Another thing, is it possible to connect external sensors to an Arduino board or there are special sensors that can communicate with the board? I want to use weight sensors.

body:
To start with arduino you need to have some factors in consideration, for example the board you will chose, arduino UNO being the starting board for most beginners, if you are already an experienced programmer in C++ you might want to try more powerful boards.
You have a pretty good overview of all of them in this link :
http://arduino.cc/en/Main/Products
Also there are hundreds of shields out there, you will find some in the link above.
Adafruit also has some interesting ones, https://www.adafruit.com/search?q=arduino, you can even find them on ebay, and you can always buy individual sensors, LEDs, buttons etc, and plug them in directly or in a breadboard.
Sparkfun has a big variety of very interesting sensors.
There is also a lot of open source shields out there, you can check a very simple one i designed myself :
http://electropepper.org/projects/prototyping/item/proto-i-os-arduino-v1-0


body:
**Things to consider when picking an Arduino board:**

 - Do I want native keyboard/mouse support? If yes: you'll need the Leonardo (or it's breadboard mountable equivalent) or the TRE (not released, dual MCU board).
 - Do I want a small form factor and/or have it breadboard mountable? If yes, choose a board like the Mini/Micro/Nano/etc.
  - If you want to make it even smaller, either get a board without USB built in or try using an ATTiny
 - Am I computing large numbers with it? If yes: use the Due, Galileo, or TRE (not released yet)
 - Do I want video/audio? If yes: TRE is the only way to go as of now (but it's not released yet).
 - Do I need a USB host (and not want to have an external shield)?  If yes, use the Mega ADK (limited support), Yun, TRE (again, not released yet), or Galileo.
 - Do I need WiFi/ethernet built in? If yes; use the Yun, TRE (still, not released yet), Ethernet *board*, or Galileo.
 - How many pins do I need (and how many of each type)?
  - Digital: simple ON or OFF. Use these for buttons, simple lights, some communication, etc.
     - Stay away from the Due if you don't want to mess with 3.3V logic. Most other boards are 5V. You can work around this with either voltage dividers (doesn't always work) or level shifters. As far as I know, you can't really do much if a sensor provides max 5V; level shifters AFAIK only work with digital signals.
  - UART Pins: these are the pins that you can use the serial library on. (Note: this doesn't include the software-serial library). One of these on most boards is connected to a USB chip.
  - SPI Pins: These are pins which are used by a form of communication (like on the Ethernet shield).
  - Inturupt Pins: These can trigger an event when the signal getting sent to the board changes. There are a couple of different settings, but this can be used for near-instant response time when low latency is critical.
  - PWM Pins: pins that go on and off to simulate a lower voltage. It does this by turning it on and off very rapidly. This is used often for dimming LEDs and controling the speed of a motor.
  - Analog pins: pins that can read a voltage and convert it into a number.
     - The Arduino Due has a much higher precision rate, as it has more possible values and it has less voltage, thus much more accuracy.

    All of these types of pins can act as a digital pin. All of these, except the analog pins, are under the "digital pin" section of your Arduino board. I didn't go into the technical aspects of the pins; I explained then in the simplest way I could.

I left a lot of boards out of this list, but this should give you some things to think about when choosing a board. There's a lot of weird quirks with this list, so it's incomplete, especially with the types of pins. You'll just have to do research and figure out what you need and if a board can meet your needs. Just make sure to not plan two things on the same pin, especially when mixing different shields and sensors! Shields *do* take up pins.
****
Shields: they are pretty much compatible with every board except for if the board is 3.3V (newer shields can adapt automatically) OR if it's a breadboard mounted board, like the Nano. There are ways to work around this problem, but it's very difficult.


body:
The usual suggestion I give to people new to Arduino is to get a Starter Kit (either from the [store][1] or from a [local reseller][2]): it contains an UNO, plenty of sensors and actuators and a projects book.

  [1]: http://store.arduino.cc/index.php?main_page=product_info&cPath=2&products_id=185
  [2]: http://arduino.cc/en/Main/Buy


body:
There are some good answers already, but here are a some secondary considerations

 1. Many Arduino boards use a ceramic resonator rather than a crystal as their timing source. This rules out using them in critical timing applications. For instance you might need to add a real time clock board if you need to keep track of time of day.
 2. The boards based on the Atmega328 chip only have three timers, and one of these (Timer 0) is used by the delay() function, which is in turn used by other libraries. Timer 1 and timer 2 get used if you include the PWM and tone libraries. The boards based on  the 2560 chip have 6 timers, which is a lot more generous.
 3. If you want to count external inputs at speed (i.e. up to 4MHz), you need to access the Tn pin of the appropriate timer counter(s). On the UNO, only T0 is exposed to the outside world, and the timer is already in use. Even the Mega2560 boards only seem to expose T0 and T5.


message:
Using arduino mega with linear encoder to control movement of dispenser

My goal is to deliver very small quantities (100 microliters) of fluid to the (approximate) center of a 25mm x 75mm surface. My first idea was to repurpose an old inkjet printer for the project. I thought I'd load the fluid dispensers (probably 3ml syringes) into the unit where the ink cartridges would go and use an arduino to manipulate the linear encoder used by the printer to tell the dispenser unit where to go.

Main problem at the moment is that I'm having trouble getting the dispenser unit to go exactly where I want it to. I've tried incorporating the PID library into my code to get the head to oscillate around the desired position until it stops at the right location. However the oscillation never stops and the head always moves beyond the desired position.

I'm trying to figure out the easiest way to get this done. Maybe that'll mean moving away from using the inkjet printer but I'd like to get some feedback here before I make any decisions.

Code:

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"
    #include <PID_v1.h>

    //
    //// Interrupt information
    //// Int 0 on pin 2
    //// Int 1 on pin 3 Not used
    //
    #define encoderI 2  // Interrupt 0 is use
    #define encoderQ 4 // Only use one interrupt in this example
    #define maxPos   3733 // left hand side
    #define minPos   0    // right hand side
    #define maxSpeed 150
    #define minSpeed 0
    #define Freq     1600
    #define maxWait  500 //12 millisec before stopping the motor
    #define maxPositionError 10 //max error from actual desired position. It is approximately 0.032 of an inch
    #define PIDsampleTime 25

    //
    //// Tuning parameters
    double kP=0.37; //Initial Proportional Gain
    double kI=2; //Initial Integral Gain
    double kD=0.020; //Initial Differential Gain
    double Drive = 0;

    int outputSign;
    //
    double Setpoint, Input, Output;

    PID myPID(&Input, &Output, &Setpoint,kP,kI,kD, DIRECT);

    volatile int ActualHeadPosition; //current position will be modified with each interrupt
    volatile int PreviousHeadPosition; //Previous position will be modified with each interrupt
    volatile uint8_t Speed = maxSpeed;                      //Speed for the dispenser head
    volatile unsigned long lastPositionTime;
    volatile int setPoint;
    volatile int Err;
    volatile int lastError;
    volatile int Integral;

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    //
    //// Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *dispenserDCMotor = AFMS.getMotor(1);
    //
    void setup() {
         Serial.begin(9600);           // set up Serial library at 9600 bps also this is the baud rate per second for the input?
         pinMode(encoderI, INPUT); //pin #2 is assigned as an input
         pinMode(encoderQ, INPUT);
         attachInterrupt(0, handleEncoder, CHANGE);
    //
         AFMS.begin(Freq);
    //
    //    // Set the speed to start, from 0 (off) to 255 (max speed)
        dispenserDCMotor->setSpeed(Speed);
        dispenserDCMotor->run(FORWARD);
    //    // turn on motor
        dispenserDCMotor->run(RELEASE);
    //
      Setpoint = 1800;
      myPID.SetSampleTime(PIDsampleTime);
      myPID.SetOutputLimits(minSpeed, maxSpeed);

        //turn the PID on
        myPID.SetMode(AUTOMATIC);

         //Initialize procedure should be the first thing
        Initialize();
    }

    void loop() {
      Serial.print(", ActualHeadPosition: ");Serial.print(ActualHeadPosition);Serial.print(", SetPoint: ");Serial.println(setPoint);

      setPoint = 1800;
      Input = ActualHeadPosition;
      outputSign = myPID.Compute();
      Err = setPoint - ActualHeadPosition;
      Serial.print("PID Output");Serial.print(Output);Serial.print(" Error: ");Serial.println(Err);
      Speed = Output;
      if (Err > 0){
        moveLeft();
        Serial.println("moveLeft");
      }
       else if (Err < 0){
         moveRight();
         Serial.println("moveRight");
      }

    };
    //
    void handleEncoder(){
      lastPositionTime = millis();
       PreviousHeadPosition = ActualHeadPosition;
       if(digitalRead(encoderI) == digitalRead(encoderQ)){
         //dispenser is moving to the left
         ActualHeadPosition++;
       }
       else {
         //dispenser is moving to the right
         ActualHeadPosition--;
    }

     }

    void moveLeft(){
      uint8_t i;
      dispenserDCMotor->run(FORWARD);
      dispenserDCMotor->setSpeed(Speed);
    }

    void moveRight(){
      uint8_t i;

      dispenserDCMotor->run(BACKWARD);
      dispenserDCMotor->setSpeed(Speed);
    }

    boolean isMotorMoving(){
      if (((millis() - lastPositionTime) > maxWait))
        return false;
      else
        return true;
    }

    void Initialize(){
        //Move to origin
        moveRight();
        while (isMotorMoving()){
      //    Serial.println("MOVING!");
      delay(10);
        }
        ActualHeadPosition = 0;
        PreviousHeadPosition = 0;
        dispenserDCMotor->setSpeed(0);
        dispenserDCMotor->run(RELEASE);

    }

body:
The easiest option, using the code you have, is to spend a little time tuning the PID algorithm. The lines you are interested in are these

    double kP=0.37; //Initial Proportional Gain
    double kI=2; //Initial Integral Gain
    double kD=0.020; //Initial Differential Gain

PID takes a setpoint and a current location, calculates error, and uses it to make a new output that should sent the location to the setpoint. It does this by adding

P*(error)+I*(all historic error added together)+D*(recent change in error)

By changing the multipliers P, I, and D, you change how it reacts to different situations. In your system, the D value will have very little effect (at least in my experience). You should probably keep that where it is, or even just set it to 0.

The P value controls direct response to error, and should be the main component in your setup. Try increasing this to make it move faster, and mildly decrease the oscillations.

The I value controls how much all historic error affects output. It is the factor leading to all the oscillations. Lowering it will make your output settle sooner. It also assists when fighting other constant forces, or if static friction keeps the head locked in one position too close for the P term to overpower. My guess is in your isolated and low friction system, it should be very low.

Increment these values slowly (.05 at a time maybe) and experiment, you should be able to fix your oscillations and make the system behave how you want.


body:
The reason why your slide/microarray microdispenser continually oscillates about a point rather than dispense the fluid containing your cells/DNA sample specifically at a particular specified/designated point on your slide/microarray is due to your code below:

    if(digitalRead(encoderI) == digitalRead(encoderQ)){
         //dispenser is moving to the left
         ActualHeadPosition++;
       }

       else {
         //dispenser is moving to the right
         ActualHeadPosition--;
    }

which tells the Arduino to actuate the motor regardless of the values stored in the vars encoderI & encoderQ.


message:
How to create delays in AVR assembly language

Hi i'm new to AVR assembly language so i was trying to get delay function to create 1 ms , 100us, and 1us  delays to do that i need to figure out what to replace nop's with below here (mainboard arduino uno r3 ATmega328
Thank you.

    "delay_ms%=:    nop                 ; code to replace  nop  \n"
    "delay_100us%=: nop                 ; code to replace  nop  \n"
    "delay_1us%=:   nop                 ; code to replace nop  \n"
    "               sbiw r30,1          ; decrement ms count (r31:r30)\n"
    "               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
    "               ret                 ; return from subroutine      \n"
The rest is below.

    word millisecs;
    Serial.begin(9600);
    }
    void setup() asm volatile(
    "          ldi r16,0x3F    ; r16 = 00111111\n"
    "          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
    ::: "r16");
    millisecs = 1000;            // 1s blink delay
    Serial.begin(9600);
    }
    void loop()
    {
    long starttime = millis();        // make a note of the start time

    asm volatile(
    // jump to "blink" - ie jump around the delay_ms subroutine
    "            rjmp  blink%=        ; relative jump to 'blink' \n"
    "          ldi r16,0x3F    ; r16 = 00111111\n"
    "          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
    ::: "r16");

    registers used:
    r31 - millisecond count (lo byte)
    r30 - millisecond count (hi byte)
    r17 - 100 microsecond count
    r16 - 1 microsecond count
    Overall delay (ms) = r30:r31 * r17 * r16
    ---------------------------------------------------------------------*/
    "delay_ms%=:    nop                 ; code to replace  nop  \n"
    "delay_100us%=: nop                 ; code to replace  nop  \n"
    "delay_1us%=:   nop                 ; code to replace nop  \n"
    "               sbiw r30,1          ; decrement ms count (r31:r30)\n"
    "               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
    "               ret                 ; return from subroutine      \n"

body:
AVR LibC already has macros that do this, provided `F_CPU` is set correctly.

    // Note: The Arduino IDE gets the value for F_CPU from boards.txt
    #define F_CPU xxxxxxxxxx

    #include <util/delay.h>

     ...

    _delay_ms(1);
    _delay_us(100);
    _delay_us(1);


message:
How does the Arduino handle serial buffer overflow?

Does it throw away the newest incoming data or the oldest?  How many bytes can the buffer hold?

body:
For hardware serial ports you can see in [HardwareSerial.cpp][1] that the buffer size varies depending on the amount of RAM available on the particular AVR:

    #if (RAMEND < 1000)
        #define SERIAL_BUFFER_SIZE 16
    #else
        #define SERIAL_BUFFER_SIZE 64
    #endif

For a software serial port in [SoftwareSerial.h][2] the receiver buffer size `_SS_MAX_RX_BUFF` is defined as 64 bytes. In both cases it stops attempting to insert received data into the queue when it is full, so you could get a mix to old and new data depending on how you're retrieving data from the queue.

Ideally it would be best to ensure the buffer always gets emptied in a prompt manner to avoid the buffer filling. Maybe take a look at timers and implementing a simple state machine if your problem is related to other code blocking the main loop.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp
  [2]: https://github.com/arduino/Arduino/blob/master/libraries/SoftwareSerial/SoftwareSerial.h


body:
## Receiving

<!-- language-all: lang-C++ -->

You can see from the source of HardwareSerial that if an incoming byte finds the ring buffer full it is discarded:

    inline void store_char(unsigned char c, ring_buffer *buffer)
    {
      int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;

      // if we should be storing the received character into the location
      // just before the tail (meaning that the head would advance to the
      // current location of the tail), we're about to overflow the buffer
      // and so we don't write the character or advance the head.
      if (i != buffer->tail) {
        buffer->buffer[buffer->head] = c;
        buffer->head = i;
      }
    }

> I get the impression that if I transmit data to the Arduino and don't have an active "puller" of data on the Arduino side then if more data arrives than can fit in the buffer, it will be discarded. Can you confirm that?

Yes it will be discarded. There is no software or hardware flow control, unless you implement your own.

However with a 64-byte buffer, and receiving data at (say) 9600 baud, you get one byte every 1.04 ms, and thus it takes 66.6 ms to fill up the buffer. On a 16 MHz processor you should be able to check the buffer often enough that it doesn't fill up. All you really have to do is move the data from the HardwareSerial buffer to your own, if you don't want to process it right now.

You can see from the `#if (RAMEND < 1000)` check that the processors with 1000+ bytes of RAM get the 64-byte buffer, the ones will less RAM get the 16-byte buffer.

---

## Sending

Data that you write is placed in a same-sized buffer (16 or 64 bytes). In the case of sending if the buffer fills up the code "blocks" waiting for an interrupt to send the next byte out the serial port.

If interrupts are turned off this will never happen, thus you do **not** do Serial prints inside an Interrupt Service Routine.


message:
Making analog telephone calls?

How can we make the Arduino board interact with old, analog telephone, and to make phone calls?

I guess it involves connecting the board to the telephone with some specific cable (how it's called?)

In addition, I assume it will require us to use the telephone low-level dialing protocol (in order to actually interact with the phone and to send commands). Where can I read about it?

Is there a reason to concern about conversation between the digital/serial board and an analogous device?

By the way, I've read that analog telephones have relatively high voltages that can easily damage the board. I'd love to get any information about things like this, related to connecting Arduino to analog telephones, in order to know about such issues and about what to be concerned and to explore.

Thanks a lot!

body:
Buy an external voice modem with a RS-232 connection. Connect it to a RS-232C shield. Use AT commands to dial numbers and pick up calls. Use voice AT commands to transmit or receive audio.

Never attempt to connect the telephone line directly to an Arduino since, yes, you will fry it. The voltage is all wrong in the first place, and goes even higher when the phone line rings.


body:
Connect a microcontroller to a telephone line is a rather technical task and requires knowledge concerning the operation of the line, but it is not an impossible task, although it can be dangerous, and sample some nasty shocks if you're not prepared for such work.

Initially you should build a rectifier circuit, mainly for its polarizing power circuit, since you do not know which is the antibody positive your telephone line but know that tensions are measured inversely ie, when measured with respect to ground (GND) the measures will be negative, this is because it was discovered that the poles of the batteries used to be gnawed less well when connected to the system.

A second step is you develop a small coupler to avoid connecting your circuit directly to the telephone line. For this you can use a pair of low-pass filters, which are placed at each connection point of the line after the bridge rectifier, and the downside of the bridge rectifier is connected to ground your circuit with this filter. And the plus point is connected to a PWM output of your controller.

Other important information you can not connect the PWM port directly to this filter, because the voltage levels in the telephone line are quite different, namely:

- When the line rings you get a voltage exceeding 60V oscillating above 20Hz.
- When the line is in standby mode it remains between 30V and 48V as your carrier and region.
- When the line is busy or because your circuit or another extension you will have a voltage between 6V and 12V.
- Already the audio modulation in their line occurs with peak 0,7Volts equivalent to 3dBm therefore its PWM output should give output like this.

To match the level of your line voltage with the telephonic system you can use a voltage divider which has an output of 0 to 0,7Volts ie when the door PWM pulse maximum output voltage of 5V should be 0,7Volts the divisor resistive. Another way is to use an operational amplifier having a gain reverse, thus reducing output. you can also use a optoacoplado circuit with 4n25 and thus polarize the phototransistor for such variation with the pulses in your diode.

Another important component in this circuit is a pair of diodes to be done clipping the signal, ie, as our voltage limit for audio is 0,7Volts after the filters put a couple of diodes between the positive and negative of your signal filtered in the bridge rectifier, so prevent signals above this level reaches the arduino when ouver noise on the line.

More Information: http://carlosdelfino.eti.br/WorkshopTelefoniaAutomacao/
![A General Schema About This][1]

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


message:
Arduino Due - wireless programming via Xbee

I would like to integrate an Arduino Due into a project, which probably will evolve over time and will need some re-programming. Instead of having to disconnect and pull out the Arduino Due out from the enclosure, I was wondering whether it can be set up for wireless programming via an Xbee in a similar way as for the Arduino Fio (like described here: http://arduino.cc/en/Main/ArduinoBoardFioProgramming).

Has anyone tried that already or succeeded doing that?

body:
Theoretically, it is possible I have not tried to do it on an Arduino but I did work something similar with a pic controller. Usually, when we program the board with the firmware file we break the firmware file and send it as multiple packets over the serial com port to be written to on a certain flash memory location on the controller.

In your case, you can try an experiment by using 2 XBee modules that are connected together with the appropriate channel and network ID settings wirelessly. connect one XBee to your computer using a serial to USB cable. On the Arduino side, you have to connect to power it and use the second XBee to connect to it on the UART port. This way the XBee acts as a simple wireless data transfer channel to send and receive data wirelessly (if I am right this should be achievable in the transparent mode on XBee).

One thing to note is to check the Arduino schematic to see how exactly the data over USB is sent to the controller. If it is on UART then this should work straightforward if not then you may have to figure out something else for it.


message:
Are there any products based on Arduino that are sold by companies?

Ok, Arduino is a good technology but is it used professionally? Is the quality good enough to be used for professional purposes?

body:
Yes, you can also use an Arduino for professional usage. The Arduino is actually just a prototyping device and easy to use for people at home/school. I suppose there might be products on the market which were developed using an Arduino. But the most important thing is the Atmel MCU inside the Arduino which can be used for anything. But, if you wanna know if the ATmega328P-PU which is used in the Arduino Uno is a common MCU used by professionals? The answer would be no. Everything has to be smaller and better so it'll be more likely to find the same MCU like the Arduino Leonardo, Mega etc etc.

Examples where professionals might use an Arduino for as base (The end product will only contain the MCU of the Arduino):

 - Kid toys like an Simon Says Game, Line following toy cars etc etc.
 - Small industrial products like an automated tape dispenser.
 - AVR programmers.
 - Card readers.


body:
In theory, an Arduino board *could* be used in some low-end professional products (i.e. where the performance and memory limitations aren't an issue). The build quality of the official boards is certainly good enough. The only issue they would potentially have is making suitably robust connections -- i.e. anything plugged into a female header would have the potential to get shaken loose.

In practice though, using an Arduino board would only make sense for extremely small-scale projects, where only a few units will be produced, and where there will be a minimum of external circuitry.

A commercial project would normally have a custom circuit board designed. That allows them to economise on space and features, eliminating unnecessary costs. Even if it only saves a small amount per board, it can make a big difference if you're doing mass-production.

With that said, a professional product could certainly use an AVR microcontroller or similar at its heart (much like the Arduino boards). Atmel was producing chips long before Arduino was around, and their products are well known and widely used. The choice really depends on the needs of the individual project.


body:
Yes, I work for an engineering design house and we use Arduino frequently to prototype ideas for clients.  It significantly speeds up the time to get a proof-of-concept device in the hands of the client and their potential investors.

We have found though that there is significant work to get from an Arduino-based prototype to a commercially-ready product.  Essentially you have to start again and design a completely custom printed circuit board, which is a relatively expensive exercise.

We are now developing a platform that is compatible with the Arduino IDE, but uses surface-mount modules rather than the Arduino shield system, allowing it to be manufactured in an automated surface-mount facility.  Check it out if you are interested at duinopro.cc.  We are in development stages at the moment, but already have hardware and are mainly working on our website, and designing new modules.


message:
CC3000 - Send GET request to an app on heroku

I'm struggling to get the CC3000 to connect to a heroku hosted app, and other examples posted online haven't turned on the light bulb quite yet for me.

The gist is that I collect some temperature and humidity readings, and then send those via a GET request using the CC3000. The heroku app then reads the parameters and displays them on a page.

The CC3000 hardware is A-OK, as I've tested it using the test sketches. The sketch I've put together (on github: https://github.com/jsimms/compost_monitor) works except for the last bit where it needs to connect to the server and send the HTTP request. Which makes me wonder if this is a heroku quirk, or if I'm just screwing something up right at the finish line.

First, I define everything

    #define WEBSITE      "myapp.herokuapp.com"
    String route = "/sensor";
    uint32_t ip;
    int port = 80;

Then during setup, I use getHostByName to assign the ip variable. I print it out, just to confirm it was able to snag an ip. I then close it to make sure I don't screw up anything during the loop.

      ip = 0;
      Serial.print(WEBSITE); Serial.print(F(" -> "));
      while (ip == 0) {
        if (! cc3000.getHostByName(WEBSITE, &ip)) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }

      cc3000.printIPdotsRev(ip);
      Serial.println("");

      // Close the connection
      Serial.println(F("Closing connection..."));
      cc3000.disconnect();
      Serial.println(F("Connection closed."));

During the loop, I create a String with the request, and then call a function that actually does the request.

    String request = "GET " + route + "?temp=" + temperature + "&hum=" + humidity + " HTTP/1.0\r\n";
    send_request(request);

Finally, the send_request function is supposed to take care of connecting via TCP and sending it.

    void send_request (String request)
    {
      // Connect to server
      Serial.println("Connecting to server...");
      Adafruit_CC3000_Client www = cc3000.connectTCP(ip, port);

      // Send the request
      if (www.connected()) {
          www.println(request);
          www.println(F("User-agent: CompostMonitor/1.0\r\n"));
          www.println(F("\r\n"));
          Serial.println("Connected & data sent successfully...");
        }
        else {
          Serial.println(F("Connection failed."));
        }

        while (www.connected()) {
          while (www.available()) {

          // Read answer
          char c = www.read();
          Serial.println(c);
          }
        }

      // Disconnect
      Serial.println("Closing connection...");
      Serial.println("");
      www.close();
    }

However, I never get anything but connection failed.

Any insight and help would be wonderfully appreciated. :)

UPDATE: Ok. So, through the comments below, I was able to identify by telnet'ing the web app, that there was something wrong with the HTTP requests. I made a small tweak to the app, but the real issue was that I wasn't including Host: weathervane.herokuapp.com in the header. FML! I'm going to test out sending the request with the Arduino later tonight. Hopefully that puts an end to this HTTP 101 lesson I've been doing.

body:
Have a look at this code:  https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/examples/SendTweet/SendTweet.ino

There is a delay after `cc3000.connectTCP` to wait for connection. Your code does not wait for the connection and thus gives 'connection failed' straight away.

    Serial.print(F("OK\r\nConnecting to server..."));
    t = millis();
    do {
        client = cc3000.connectTCP(ip, 80);
    } while((!client.connected()) &&
        ((millis() - t) < connectTimeout));

    if(client.connected()) { // Success!

    etc

Edit based on comment:

getHostByName returns positive value on success and negative on failure. Therefore the check should be

    if (cc3000.getHostByName(WEBSITE, &ip) < 0)

Also try putting `http://` in the website address


body:
    www.println(request);
    www.println(F("User-agent: CompostMonitor/1.0\r\n"));
    www.println(F("\r\n"));

Both `request` and the other two strings end with `\r\n`. You also use `println()`, which adds `\r\n` of itself. This means that you end every line with two CRLF sequences, which is not correct according to the [HTTP standard](http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2) (Sec 2.2, Basic Rules).

Instead, use `print()` which doesn't add anything, or don't add `\r\n` to the strings yourself.

Servers may not complain about this but your code is not conform the standard and may not work on all servers / may stop working after a server update. It's also possible that some of the header fields are not being considered by the server because it treats them as body instead of headers.

---

Besides that, you should considering use HTTP 1.1. There's no hard reason to change _now_, but it's newer, includes more features, is supported by (almost) all server software, and will still work even when (_if_) servers decide to start phasing out HTTP 1.0 support. You then need to change `1.0` to `1.1` in the `request` string, and after that specify the Host field explicitly:

    www.println("Host: myapp.herokuapp.com");


message:
What is the cheapest way to add wifi to Arduino?

I am trying to find some sort of wifi adapter for Arduino, it needs to be as small as possible (not a shield) and as cheap as possible.

So far I can only seem to find shields that cost about £10+ but I figured that if you can get a replacement wifi adapter for a laptop for next to nothing that I should be able to get a wifi adapter for Arduino much cheaper than this.

It's possible I just don't know what to search for.

body: The Roving Networks RN-XV WiFly module ([found sold at €30](http://www.watterott.com/de/Roving-Networks-RN-XV-WiFly-Module)) might be a solution. I've never tried it. It supports 802.11b/g.


body:
Some months have passed since my previous answer and now the ESP8266 based WiFi modules are available.

They get connected to your project serially (3.3V) and are controlled in a modem like way using AT commands.

With a pricing of round about $5 they fit the question better than my previous OpenWrt based answer.

For more information about ESP8266 ask your favorite finding machine or [list news with tag ESP8266 at Hackaday](http://hackaday.com/tag/esp8266/).

<hr>

*(Old answer from the pre-ESP8266-days:)*

I vote for a small router reflashed with OpenWrt like "TP-Link TL-WR703N".

It is like building an own Yùn with an Arduino of your choice...

The WR703N:

It has Ethernet, 150MBit WiFi, USB and if you want to solder, a serial console and 2 GPIO-Pins which can be turned into I2C.

This sure is not a chip- or stamp-sized solution but often cheaper than the alternatives, more powerfull and extendable.

Search the net with your favourite find'o'bot for "arduino wr703n" and you'll find lots of examples...


body:
[Texas Instruments CC3000][1] module 10USD/1000pcs, it does only support connecting to AP, i.e. no AdHoc/AP which is useless for direct using with iPad.

  [1]: http://www.ti.com/product/cc3000


body:
https://www.forward.com.au/pfod/CheapWifiShield/index.html
provides a very inexpensive wifi addon for Arduino

[![Completed Shield][1]][1]

The WiFi Shield needs just two parts, 4 bits of wire and some soldering equipment. Parts List:-

Adafruit HUZZAH ESP8266 Breakout US$9.95 + shipping
Uno Protoshield US$1.88 + shipping
Total US$11.83 (as of June 2015)
For an even cheaper version ~US7 see https://www.forward.com.au/pfod/CheapWifiShield/ESP2866_01_WiFi_Shield/index.html
Both of these need a US10 USB to TTL cable to program them

After you have installed the [pfodESP8266BufferedClient library][2], open the Arduino IDE and copy this sketch, [ESP8266_WifiShield.ino][3], into the IDE.
That provides this setup webpage.
[![Config webpage][4]][4]

  [1]: https://i.stack.imgur.com/OjJAA.jpg
  [2]: https://www.forward.com.au/pfod/pfodParserLibraries/pfodESP8266BufferedClient.zip
  [3]: https://www.forward.com.au/pfod/CheapWifiShield/ESP8266_WifiShield.ino.txt
  [4]: https://i.stack.imgur.com/nYvAK.png


message:
What's the most accurate way to time-stamp analogRead data?

I want to sample an Analog sensor as fast as possible, and time-stamp each sample that I take as accurately as possible.

Currently, I'm doing the following:

    val = analogRead(SENSOR_PIN);
    clocktime = micros();

    writeData(val, clocktime); // writes the values to an SD card

I'm wondering if there is a more-accurate way of time-stamping the data from the analogRead call. Put another way, I would like to record the exact time that the analogRead data was collected. My guess is that this is basically impossible on an Arduino, so what technique will let me get as close as possible?

body:
There is no more accurate way of getting time on the arduino, but I would suggest you use millis() instead.

micros() returns microseconds, or millionths of a second, since the arduino was turned on. The issue is that the 32 bit unsigned integer used to store time on the arduino can only count about 70 minutes worth of micros before overflowing and resetting to 0. (see http://arduino.cc/en/reference/micros)

millis() is in thousandths of a second since the arduino turned on, and it will not reset for about 50 days. If you think one thousandths of a second is good enough resolution, it will probably be the better choice.

If you need time to be absolute, as in the current day/hour/minute, you will need to buy a real time clock to plug into the arduino. They are about 20 bucks, and available from all the standard arduino accessory stores like sparkfun, adafruit, ect.

On your question of the order, both commands run so quickly, I can think of no reason it would matter.


body:
For "as fast as possible", I'd

 1. Rewrite your sampling code in assembly language (just those two statements, not the whole program); and
 2. Buffer the raw data pairs in memory if you have enough of it, then store it to the card after the measurement burst. If you need more data space, consider that the timing of a tight assembly loop will be consistent (and fast!) and can be measured. You may not need to read the clock at all. Note that you can get the same timing consistency using C/C++ if you read the analog and clock ports directly, and maybe as fast. It's just that with assembly language, WYWIWYG (what you write is what you get); the compilers' code-generators and optimizers won't mess with it.

A possible issue with your code as you've written it is that writeData probably buffers the data on most calls, but whenever a call results in a full buffer, writes the whole buffer to the card, introducing jitter into your sampling.

Addressing your edit of June 3, 2014, "I would like to record the exact time that the analogRead data was collected":

Since you proposed using micros() (as opposed to a real-time clock), I assume you are satisfied with the relative time. Once you know your data collection code is completely predictable, then the offset from reading data to reading time is constant, and since we're using relative time anyway, can be discounted, or at least, corrected for.

It isn't *completely* predictable of course, since in this case, you're using an interrupt-maintained clock, and can expect that sometimes the interrupt will occur between the data read and the clock read, stretching the offset for that tuple. To get even more accurate, you'd need to keep interrupts off, read the timer yourself in an invariant way. f/ex, you might run the timer at such a rate that you could expect to take two or more samples between overflows of the low-order byte, read and store only the low order byte as your time sample, and post process the time data to reconstruct the high order byte by detecting wrap-around in the low-order.

With no interrupts running, and once you know the rate at which you can sample data without reading the clock, you could read and save the clock once immediately prior to taking the first sample, and infer the times of each subsequent sample based on the known sample rate.


message:
How do I avoid this error trying to connect arduino to pc with linux fedora 20

I used Arduino successfully on my old Linux Fedora 12 system. Now I have a brand new PC with Fedora 20, and have today installed Arduino on it. In my first attempt to use it I typed Arduino as follows at the root prompt, after the "yum install arduino" gave me "Complete!", as follows:

    Complete!
    [1344][root@localhost:/home/Harry]# arduino
    WARNING:  RXTX Version mismatch
     Jar version = RXTX-2.2
     native lib Version = RXTX-2.2pre2

Subsequently I have loaded the "Blink" sketch, and that is running nicely, whether I start the IDE from the command line, which still gives me the same WARNING, or from the desktop icon, which does not give it.

So my question is: please, does this WARNING matter? If so, what should I do about it?

body:
The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one.

RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it.


message:
Arduino servo acts weird with photocell (lightsensor)

![enter image description here][1]I have a weird thing with my servo, I really dont know what is wrong with my code, I tried everything. Either it is my connection on arduino or my code. Please help me guys, this is my code.

    #include <Servo.h>

    int servoPin = 9;
    Servo servo;
    int angle = 0;
    int photocellPin = 0;

    void setup() {
      servo.attach(servoPin);
    }

    void loop() {
      int reading = analogRead(photocellPin);
      Serial.print("Reading = ");
      Serial.println(photocellPin);
      int newAngle = reading / 2;
      servo.write(newAngle);
      delay(80);
    }

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

body:
Servos accept a signal from 0 to 180, with 90 being the center point on the servo. analogRead() will output a number from 0 to 1023. The arduino "map" function makes a conversion easy to do. just replace

    int newAngle = reading / 2;
with

    int newAngle = map(reading, 0, 1023, 0, 180);
you can read more about the map function here: http://arduino.cc/en/reference/map

It is hard to tell from the picture that everything else is wired correctly, but this should fix up your code.


message:
How do I remotely acquire data from Arduino based portable device?

I am making a device which will have an Arduino board and a sensor attached to it. The sensor will acquire data every 10 minutes and the data will be uploaded to my server. The size of every upload is about 200 characters. I'd like this device to work anywhere in my city (US).

What are my options for uploading data to my server? Keep in mind that it will work without human intervention. FYI... this is NOT for reconnaissance device! ;)

body:
I can't guarantee *anywhere* in your city, but this hack will work pretty much wherever there is cell coverage for the carrier you choose.

You'll want the **[GSM shield](http://arduino.cc/en/Main/ArduinoGSMShield)**.

>![][1]

*Picture from Arduino*

Anyway, it uses pins 2, 3, and 7 on it. It also has the ability to solder (on the bottom of it) a microphone and speaker connection. You'll need to buy a SIM card and a contract to connect your shield to a network. I don't know how often you would use this, but I've seen a pay-as-you-go plan that charges you $2 for unlimited talk/text/internet per day. If you're going to use this once a month, that would be the way to go. I didn't look to see if they supported the GSM shield (it was on TMobile's site). You would want to contact them for more details. Also, depending on where you live, I don't know if you would get good coverage. This goes with any cell phone provider, but make *sure* that you get coverage where you want to go (and don't always trust the maps they provide).

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


message:
Does millis() conflict with the PWM pins associated with timer 0?

I've read that the `millis()` function uses the same timer as a couple of PWM pins.

If you're using those PWM pins, will `millis()` still return the correct value?

body: They do not conflict as `millis()` strictly reads the immediate value in `TCNT0` whereas PWM via timer 0 uses the hardware's ability to compare the value of `TCNT0` with the values in `OCR0x` without affecting the value of any of them.


body:
Just to add to @Ignacio's answer which has directly answered your question. The "conflict" you speak of is in relation to `Timer0`'s prescaler.

For the most part, you can use those pins (incidentally pins 5 and 6 on the UNO) with PWM without an issue, and read the correct value of `millis()` (as well as get the expected delay from `delay`)

Where you run into problems is if you want to change the prescaler (usually to modify the frequency of the PWM signal). If you change this, then you directly affect the calculation and reporting of `millis()` and the length of `delay(x)`.