message:
How to send RPM data as analog input from arduino to Xbee

I am new to arduino and Xbee these stuff.
Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.

It seems XBee analog input read a range of 0 volts to 1.2 volts.
However, not quite sure how to implement and write the corret code.
Following are Arduino code and schematic circuit.
Any idea?
I really appreciate your help.

    int pin = 7;  //7
    float rpm;
    float duration;
    float y;

    unsigned long val;
    float rps;
    float read_rpm;
    int pin_out=10;

    void setup()
    {
       Serial.begin(9600);
      pinMode(pin, INPUT);
      pinMode(pin_out,OUTPUT);
    }

    void loop()
    {
     val =  pulseIn(pin, LOW,70000000);

     duration=(float)val/1000000.00;
     rps= 1.00/duration;
    rpm=60.00*rps;

    analogWrite(pin_out,(int)rpm);

    Serial.print("RPM=\t");

    Serial.print(rpm);

    Serial.print("\t rps= \t");

    Serial.print(rps);

    Serial.print("\t dt=\t");

    Serial.println(val);

    }

![enter image description here][1]

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

body:
I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use `float` and then convert it to `int`, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.

Here is my code:

    #include <SoftwareSerial.h>
    /* Serial communication with Xbee.
    On Arduino pin 9 is Rx connect to Xbee Tx,
    pin 8 is Txconnect to Xbee Rx*/
    SoftwareSerial xbeeSerial(9, 8); // RX, TX

    int pin = 7;  //7
    float rpm;
    float duration;
    float y;

    unsigned long val,time;
    float rps;
    float read_rpm;
    int pin_out=10;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      pinMode(pin, INPUT);
      pinMode(pin_out,OUTPUT);
      Serial.println("I am ready to send some RPM!");

      // set the data rate for the SoftwareSerial port
      xbeeSerial.begin(9600);
      time = millis();
    }

    void loop()// run over and over
    {
     val =  pulseIn(pin, LOW,70000000);

     duration=(float)val/1000000.00;
     rps= 1.00/duration;
    rpm=60.00*rps;

    /* Sending float to Xbee
    Float is 4 byte size*/
    serialFloatPrint(rpm);

    int floatToInt = (int)rpm;

    /* To send INT to XBEE
    Int is 2 byte size*/
    xbeeSerial.write(highByte(floatToInt));
    xbeeSerial.write(lowByte(floatToInt));

    /*Print RPM every second*/
    If(millis()-time>1000){
      Serial.print("RPM=\t");
      Serial.print(rpm);
      Serial.print("\t rps= \t");
      Serial.print(rps);
      Serial.print("\t dt=\t");
      Serial.println(val);
      time = millis();
     }
    }

    void serialFloatPrint(float f) {
      byte * b = (byte *) &f;
      //xbeeSerial.print("f:");
      xbeeSerial.print(b[0]);
      xbeeSerial.print(b[1]);
      xbeeSerial.print(b[2]);
      xbeeSerial.print(b[3]);
      /* DEBUG */
      Serial.println();
      Serial.print(b[0],BIN);
      Serial.print(b[1], BIN);
      Serial.print(b[2], BIN);
      Serial.println(b[3], BIN);
      //*/
    }


sender: user

message:
Pattern library for addressable LED strips

Is there any central place that we can get drawing pattern functions for the addressable LED strips like the once based on the WS2812B component?  These are sold on the Adafruit site under the NeoPixel name.  For example I know of a few pattern examples like the Larson Scanner (Cylon), a candle light flicker or a rainbow pattern.  However I could not find a single pattern repository.

I am working on a [project][1] for kids learning to program the Arduino and it would be nice to have all the patterns in a single place and to be able to switch between the program examples with a mode switch.

If people send me links I am happy to post a blog of them.

  [1]: http://datadictionary.blogspot.com/2014/08/new-arduino-moving-rainbow-lab-for-kids.html

sender: assistant

body:
I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154

He uses the Fast_SPI (now FastLED) library, which is truly exceptional!

https://plus.google.com/u/0/communities/109127054924227823508


body:
Thake a look at [this library][1].

In [this video][2] you can see some of the many animations available.

  [1]: http://yaab-arduino.blogspot.com/p/ala.html
  [2]: https://www.youtube.com/watch?v=w2nSKQxpV_I


message:
How to reset Arduino from software

As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.

I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?

I use C# to communicate with serial.

body:
OK, I have solved this by sending DSR pulse as seen on code below:

    mySerial.DtrEnable = true;
    mySerial.Open();
    Thread.Sleep(1000);
    mySerial.DtrEnable = false;


message:
error: ‘sleep’ was not declared in this scope

I am trying to use the sleep function in lieu of `delay()`, but when I include `sleep()`, I get `Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope`

I read some place, about `#include <avr/sleep.h>` but that is a fail.

    #include <avr/sleep.h>
    void setup() {
    }

    void loop() {
      digitalWrite(13, HIGH);   // set the LED on
      sleep(1);              // wait for a second
      digitalWrite(13, LOW);    // set the LED off
      sleep(1000);              // wait for a second
    }

I was able to locate `sleep.h`:

    $ locate sleep.h | grep avr
    /usr/lib/avr/include/avr/sleep.h

So then I started reading `avr/sleep.h`, and it seems like I'm doing it right, according to the examples. So, why might this be failing?

body:
"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.

AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).

If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.

Also, vanilla arduino should be using its own packaged avr lib, for example:

    arduino/hardware/tools/avr/avr/include/avr/sleep.h

instead of the one located in your usr/lib directory.


message:
ctc mode on atmega 328

I'm trying to use CTC mode on Arduino 1 but I have the following problem.
I need to generate an interrupt on threshold B and A and I have set the prescaler to 1 since I want to generate interrupt A at 15999 (correspond to 1ms) and interupt B at 15( ie a number small enough from the start of counting).
I'have write a println function in ISR(A and B) to proof the calling of the latter but the program does not print all the characters in the println function and furthermore the counter does not reset at treshold A but stop his work.
How I can resolve the problem?

Here is the program I wrote:

    void setup() {
        TCCR1A = 0x00;                // No outputs on compare math, no PWM mode
        TCCR1B = 1 | (1 << WGM12);    // Enable CTC mode up to OCR1A and prescaler /1 -> Start
        //TCCR1B = 0b00001001;
        TCCR1C = 0x00;                // Nothing to set into C register

        OCR1A = 15999;                // Set Threshold A
        OCR1B = 15;                // Set Threshold B
        TCNT1 = 0;                    // Clear Counter

        TIFR1 = (1 << OCIE1A) | (1 << OCIE1B);    // Clear Interrupt flag Match A and B

        TIMSK1 = (1 << OCIE1A) | (1 << OCIE1B);   // Enable Interrapt flag Match A and B

        analogRead(A0);            // Dummy Read to make Arduino setting the AD
        ADCSRA |= (1 << ADIE);     // Enable AD Interrupt on conversion completed
        ADCSRB = 5;                // Select Timer 1 Match B as trigger
        ADCSRA |= 1 << ADATE;      // Enable Auto trigger

        Serial.begin(115200);      // Initialize the USART
        Serial.println("Start");   // Write the welcome message

    }

    void loop() {
        // Nothing to do
    }

    ISR(ADC_vect)
    {
        Serial.print(TCNT1);
        Serial.print(" - ADC Conversion Completed (");
        Serial.print(ADC);
        Serial.println(")");
    }

    ISR(TIMER1_COMPA_vect)
    {
        TCNT1=0;
        Serial.print(TCNT1);
        Serial.println(" - Interrupt A");
    }

    ISR(TIMER1_COMPB_vect)
    {
        Serial.print(TCNT1);
        Serial.println(" - Interrupt B");
    }

body:
I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

* Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port.  That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character.  As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.

Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.


message:
Sending multiple channels with bluetooth

I have ordered my HC-05 BT modules.
My question is this:
Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.

If it is possible, could you please provide some more information on how its done?
Thanks!

body:
The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).

There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.

For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:

[Communication Protocol Best Practices and Patters][1]

  [1]: https://arduino.stackexchange.com/questions/4214/communication-protocol-best-practices-and-patterns/


body:
To add to BrettM answer, Bluetooth is the *RF* standard on which many protocols can *stack up*; each such protocol is called a 'Bluetooth Profile'.

The Bluetooth model you purchased comes only with the [Serial Port Profile][1] (**SPP**) profile implemented in the firmware. This mean that you can use it for establishing serial communication.

As serial protocol will probably be too slow for stereo Audio over Bluetooth, Audio usually use a different profile called [Advanced Audio Distribution Profile][2] (**A2DP**). Unfortunately, the HC-05 does not come with this protocol stack implemented in its firmware. If your primary goal is to send stereo Audio over Bluetooth, consider purchasing a dedicated chip, such as **XS3868** or Sparkfun's **RN-52**. For beginners, it is recommended to get one with a breakout board for easy integration with Arduino projects.

For completeness, there are many other Bluetooth profiles, each is optimized for different task. See Wikipedia for the full list:
http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles

  [1]: http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Serial_Port_Profile_.28SPP.29
  [2]: http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Advanced_Audio_Distribution_Profile_.28A2DP.29


message:
split reading sensors values from stream after it via xbee

I'm trying to make project to monitor my home. I am using some gas sensors and temperature and humidity sensors. I want to do this wirelessly and I think the
best thing to do that is XBee.

I use this code for the transmitter Arduino:

    char dataPacket[64];

    int gx = 1;
    int gy = 321;
    int gz = 456;
    int ax = 654;
    int ay = 789;
    int az = 987;
    int mx = 147;
    int my = 258;
    int mz = 369;

    void setup(){

     Serial.begin(9600);

    }

    void loop(){

       sprintf(dataPacket, "X%d" ,gx);
        //  sprintf(dataPacket, "A�����%dG%dH%dI%d", gx, gy, gz, ax, ay, az, mx,     my, mz);
    Serial.println(dataPacket);

        }

gx gy gz .... these are the sensor reading variables

and in the receiving Arduino I use this code

    void setup(){
     // Start up our serial port, we configured our XBEE devices for 9600 bps.
     Serial.begin(9600);
    }

    void loop()
    {

     if(Serial.available() > 0)
    {
       while(Serial.available() > 0)
     {
         char dataPacket[64];

    for (int i = 0; i < 64; i++)
    {
      dataPacket[i] = Serial.read();
     Serial.print(dataPacket[0]);

    }

    String show = Serial.readStringUntil('C') ;
    delay(500);

    }
    }
    }

but i can't split the values from the stream and put them into their variables (gx gy ...)

Does anyone have idea how to split it?

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

body:
Try a communication protocol with a `,` as a delimiter like:

    messageId,data1,data2,data3,....,dataN\n

And use the `Messenger` library to parse it.

See my answer on comms protocols here:

https://arduino.stackexchange.com/questions/4214/communication-protocol-best-practices-and-patterns/4222#4222

An how to use the `Messenger` library here:

https://arduino.stackexchange.com/questions/4436/send-processing-color-data-into-arduino/4527#4527


message:
Get board.vid and board.pid value in code

I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in <boardname>.board.vid and <boardname>.board.pid

From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.

But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.

body:
The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"

this line in "platform.txt" grabs them and makes build flags for them:

    build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

the -D* option in the build is equivalent to the following lines being in the code

    #define USB_VID /*value of build.vid*/
    #define USB_PID /*value of build.pid*/
    #define USB_MANUFACTURER /*value of build.usb_manufacturer*/
    #define USB_PRODUCT /*value of build.usb_product*/

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.


message:
Arduino if else code

I have made this If-Then-Else code, but it doesn't work.

First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.

What did I do wrong?

    int sensorPin = A0;    // select the input pin for the potentiometer
    int sensorValue = 0.00001;  // variable to

    void setup() {
      pinMode(13, OUTPUT);  //LED BORD UIT
      pinMode(12, OUTPUT);  //LED4
      pinMode(11, OUTPUT);  //LED3
      pinMode(10, OUTPUT);  //LED2
      pinMode(9, OUTPUT);   //LED1
      pinMode(8, OUTPUT);   //Elektro Magneet
      pinMode(A0, INPUT);
    }

    void loop() {
      if (A0 == HIGH) {
         digitalWrite(13, LOW);
         digitalWrite(12, HIGH);   //LED on, magnet off
         digitalWrite(11, HIGH);
         digitalWrite(10, HIGH);
         digitalWrite(9, HIGH);
         digitalWrite(8, LOW);

      } else {
         digitalWrite(13, LOW);
         digitalWrite(12, LOW);   // LED Off, magnet on
         digitalWrite(11, LOW);
         digitalWrite(10, LOW);
         digitalWrite(9, LOW);
         digitalWrite(8, HIGH);
      }
    }

body: You're comparing the pin variable value with `HIGH`. If you want to get the value *at a digital input* then you need to use <a href="http://arduino.cc/en/Reference/digitalRead">`digitalRead()`</a>.


body:
Replace the line:

      if (A0 == HIGH) {

by this one:

      if (digitalRead(A0) == HIGH) {

If you plan on using the pin back as an analog input, use something like this:

      if (analogRead(A0) > 512) {

The explanation is what Ignacio said: you were comparing the pin "name" `A0` directly to `HIGH` instead of reading from the input named `A0`. To make it clearer, the two lines are equivalent:

    if (A0 == HIGH)
    if (0 == HIGH)

Get it?

There's more about what pin names to use with digitalRead() and analogRead() here:

* [analogRead(0) or analogRead(A0) at EE.SE](https://electronics.stackexchange.com/questions/67087/analogread0-or-analogreada0).


body:
You have defined your pin as

    int sensorPin = A0;

Which should be replaced with

    #define sensorPin = A0

And then in your code, you need to read the value from  the pin in your `if` statement:

     if (digitalRead(sensorPin) == HIGH) {


message:
How do I activate emulation in the Coddeblocks Arduino IDE

I stumbled upon [this][1] question here, so I tried the Codeblocks alternative. After opening an Arduino Project, and leaving all options to default, I ran the Arduino version of the Hello World. A popup opened that requests a serial port to move on. What error did I do?

If more details are needed I'll answer the comments. Thanks in advance!

  [1]: https://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board

body:
I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details. ![Image of Code Blocks][1]

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

I just tested it out for the simple program but this looks pretty cool.


message:
20x4 LCD shows alternating blank lines

I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".

The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:

![lines: white blue white blue][1]

The below schematic is exactly how I've connected the display, which should be correct.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/kWKVx.png)

<!-- End schematic -->

I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.

The dead-simple example program is following:

    #include <LiquidCrystal.h>

    // LiquidCrystal display with:
    // rs on pin 12
    // rw on pin 11
    // enable on pin 10
    // d4, d5, d6, d7 on pins 5, 4, 3, 2
    LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

    void setup() {
     // Print a message to the LCD.
     lcd.begin(20, 4);
     lcd.print("hello, world!");
    }

    void loop() {
    }

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

body: I had similar problem and I found that I had wrong contrast/brightness. Communication was working but just the characters were invisible. I spent much time, changed the LCD and in the last minute before went to rubish I got it.


body:
Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.

A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.


message:
Performance of internal vs external resistors

Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like [this][1] and [this][2]. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated [here][3].

Is there any good reason to complicate your design with an extra resistor?

  [1]: http://www.arduino.cc/en/Tutorial/Pushbutton
  [2]: http://arduino.cc/en/tutorial/button
  [3]: http://arduino.cc/en/Tutorial/InputPullupSerial

body:
I think it depends on the application you're going for.  A simple switch probably doesn't need a resistor, since it doesn't require the chip to provide any specific voltage or current.

If you're trying to run an LED or something that requires a specific amount of current or voltage, then you may be better off supplying the power connection & resistor rather than relying on the chip to provide the proper power to the device.

Another situation may be where you're approaching the maximum power output of the chip that you might change to external pull-up/down resistors.


body:
If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.

There are a number of factors to consider.

If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).

If the pin is used as both input & output the pullup can reduce the voltage swing.

In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.


message:
Compiling includes with Ino

I'm attempting to compile this simple [bounce.ino][1] example with the [ino][2] tool, but it's giving me the error:

    Bounce2.h: No such file or directory

I've placed it in the same directory as bounce.ino. Why can't it find the header?

Edit: I'm using Ubuntu.

  [1]: https://github.com/thomasfredericks/Bounce-Arduino-Wiring/blob/master/Bounce2/examples/bounce/bounce.ino
  [2]: http://inotool.org/

body:
What OS are you using?

If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.


message:
Add -D option via boards.txt

I'm trying to find a way to set a -D compiler option from within the boards.txt file. Basically set a #define for use in code. There are already some special ones like board.vid but is there a generic way to do it?

Somehow the Teensy add-on adds a little magic that allows the IDE to recognize options like:
<boardname>.board.define0=-DHELLOWORLD
<boardname>.board.option0=-DHELLOWORLD

In other words, add the -DHELLOWORD (#define HELLOWORLD) to the command line for GCC.

BUT, I can't get this to work without the Teensy add-on installed.

Is there a way to do this with the stock IDE?

body:
Yes, it is possible in the 1.5.+ IDE. while not possible in the 1.0.+ and earlier.

[Hardware-specification](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification) refers to both the boards.txt and platform.txt files.

in short the boards.txt file specifies...

    uno.build.f_cpu=16000000L

and the platform.txt uses in the compile commands such as ...

     -DF_CPU={build.f_cpu}

You can your own. There is already a "build.extra_flags=" that some of the USB devices use to add their own FLAGs conditionally on the board type.


message:
Data from PROGMEM array mismatches initialisation

The amount of memory needed for my user interface is outrageous. Hence I decided to use flash memory. But after some successful readouts from program space, problems emerge.

**Updated:**
I have some sort of initialisation files to collect all global arrays which go into flash like this: (intitialisation.cpp)

    #ifndef INITIALISATIONDEF
    #define INITIALISATIONDEF

    #include "initialisation.h" //which includes Arduino libraries and "globals.h"

    const uint8_t gl_PsNMenuType[MAXMENUS] PROGMEM = { 0, 0, 0, 0, 0};  // this is, what I intend to read out later.
    const uint8_t gl_PsNMenuParent[MAXMENUS] PROGMEM = { MAXMENUS, 0, 0, 0, 0};
    const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM] PROGMEM = {
      { 20, 2, MFTS, MFTS, MFTS}, // 0
      {2, 9, 1, MFTS, MFTS}, // 1
      {2, 10, MFTS, MFTS}, //2
      {2, 11, MFTS}, //3
      {2, 12, MFTS} //4

    };
    #endif

**Updated:**
while I propagate all global vars via another header (globals.h):

    #ifndef GLOBALS
    #define GLOBALS
    #define SDTXT

    #define MAXMENUS 80
    #define MAXFIXTEXTSPM 5

    #include "initialisation.h"
    extern const uint8_t gl_PsNMenuType[MAXMENUS];
    extern const uint8_t gl_PsNMenuParent[MAXMENUS];  // referenz auf den übergeordneten MP
    extern const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM];  // Liste der festen Menütexte zu jedem MP
    #endif

as one can see, I do not initialise my arrays fully, as I'm in a development phase, but the first bytes should be zeroed out correctly AFAIK.

But, when accessing my stored values later in a third file: (uimenu.cpp)

    #include "uimenu.h" // which includes globals.h and initialisation.h

    // somewhere in the code inside a function, with uint8_t mp=0:
    Serial.print(pgm_read_byte(gl_PsNMenuType[mp]));

The last line should print 0, as stated in initialisation, but it prints 12.

So, I think, I'm doing sth. substantially wrong here, but have no clue at the moment. I have several guesses:

 1. I should not use const with PROGMEM. I did this to be informed by the compiler, if I accidentally write to an array stored in flash.
 2. I made some mess with #includes, perhaps with order of occurrence. At the moment I try to sort the order out.
 3. There's something with having global variables or arrays defined and declared in a header and accessed in another source files function. But I cannot imagene, what.
 4. **Updated:** something wrong with my indices for my arrays? is uint8_t insufficient?

If you need more information or code, I'll edit my question accordingly. Thanks in advance! I appreciate any help.
(all files were edited for brevity before posting them)

**Update:**
I moved the definitions of the progmem arrays to the source file and all macro constants (#define) to globals.h. The outcome is: different numbers are printed, but they are wrong whatsoever. I poked elsewhere into the progmem array and got other wrong numbers.

body:
> @TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call type-safe?

The PROGMEM word is an **attribute**, not a **type**. It might be type-safe but not attribute-safe (if there is such a thing). See [Data in Program Space](http://www.nongnu.org/avr-libc/user-manual/pgmspace.html)

---

## Reference

[Putting constant data into program memory (PROGMEM)](http://gammon.com.au/progmem)


message:
Common Wire sizes for connecting peripherals to arduino

Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.

body:
Depends what you’re doing.

For low power (< 12v, 500mA) peripherals and digital signals:

If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity.
(An example can be found at: http://www.maplin.co.uk/p/jump-wire-kit-fs65v)
Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.

After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility.
(You can find this stuff everywhere, but Sparkfun is always there if you can’t: https://www.sparkfun.com/products/10649)

For higher power (> 12v, 1A):

Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.

I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.

Hope this helps.


message:
How to wire QRB1114 IR sensor to an Arduino Uno

What's the best way to wire a [QRB1114 IR sensor][1] to an Arduino Uno? I'm attempting to use it as a white-line-on-black-background line detector. Google shows many different ways wire it to an Arduino, but I'm using [this one][2] because of its simplicity.

However, when I tested the circuit using the AnalogInput example code, I'm not getting the expected behavior. It registers a reading of 0 for both white and black backgrounds (I'm using white and black electrical tape as test surfaces), and occasionally registers between 5-10 if there's nothing in front of it at all.

What is the most likely problem? Is this circuit an improper way of wiring the sensor? Is my sensor defective? Is the code not reading it properly?

This is my test code:

    #define BUTTON_PIN 2
    #define LED_PIN 13

    const int IR_SENSOR_PIN = A0;
    int sensorValue = 0;

    void setup() {
        Serial.begin(9600);
        pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
        sensorValue = analogRead(IR_SENSOR_PIN);
        Serial.println(sensorValue);
        delay(1000);
    }

  [1]: https://solarbotics.com/download.php?file=483
  [2]: http://www.engr.ucsb.edu/~mdnip/me170c/images/qrb1114.png

body:
It was a dumb programming/wiring problem on my end. As I discovered from [this description][1], the signal pin needs a pullup resistor. Since my circuit doesn't have that, I need to enable the pullup resistor on A0, which I wasn't doing.

After modifying my code to do that, the sensor works as expected.

  [1]: http://abrobotics.tripod.com/Snuffy/line_sensor.htm


message:
ATmega168a Breadboard - can't load via Arduino IDE

I have ATmega168a on a breadboard. I am programming it via the Arduino IDE and a FT232RL USB adapter. When I select my board for 168 and upload, I get the following error:

    stk500_getsync(): not in sync: resp=0x00

Normally this error means that either:

 1. My wiring is not correct
 2. I choose the wrong board

So to double check my wiring, I replace the 168 with a 328p. I am able to program the 328, so I think its the board selection.

I have tried `Ardiono Diecimila or Duemilanove w/ ATmega168` and I also have a custom board entry:

    atmega168bb.name=ATmega168 breadboard (16 MHz internal clock)
    atmega168bb.upload.protocol=stk500
    atmega168bb.upload.maximum_size=14336
    atmega168bb.upload.speed=57600

    atmega168bb.bootloader.low_fuses=0x62
    atmega168bb.bootloader.high_fuses=0xDF
    atmega168bb.bootloader.extended_fuses=0xF9
    atmega168bb.bootloader.path=arduino:atmega
    atmega168bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_16MHz.hex
    atmega168bb.bootloader.unlock_bits=0x3F
    atmega168bb.bootloader.lock_bits=0x0F

    atmega168bb.build.mcu=atmega168
    atmega168bb.build.f_cpu=16000000L
    atmega168bb.build.core=arduino:arduino
    atmega168bb.build.variant=arduino:standard

Also, I am able to program the 168 via my AVR Programmer/Debugger. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Any suggestions I can try?

body:
Try adding a 1k resistor on the TxD and RxD pins to your chip. And a 100nF capacitor like the schematic below. And a 10k Pull-up resistor to the reset pin.

    Target processor                                 USB to Serial converter
    (Atmega 168)
    GND   ------------------------------------------ GND

    5V    <----------------------------------------- 5V
    RX    <--- 1K ---------------------------------- TX
    TX    ---- 1K ---------------------------------> RX
    RESET <----||----------------------------------- DTR_PIN
      |       100nF
     10K
      |
     5V

This will help stabalizing the signals.


body:
There is another possibility, which I have had in the past.

My AVR was brand new, and it was set to use the internal resonator, at 1/8th speed, for a total of 1mhz. This was too slow to program using the default settings.

I had an USBASP, and it very conveniently had "SLOW SCK" jumper option, to slow down the programming. This was enough to program it, and if I'd wanted to use an external crystal clock (which I didn't, and 1mhz was fast enough for the specific project), I could have changed the fuses Check out http://www.engbedded.com/fusecalc/ to calculate new fuse settings. Be careful, I managed to set one chip to the wrong fuses, and am no longer able to change it.

P.S. - I used AVRDUDE to program the fuses. You should be able to read the current values, before you start - again, at slow speed. AVRDUDE has the '-B' option to slow down the programming, if you do not have the "SLOW SCK" jumper option, option -B10 should be plenty (default = -B1 I think).

When checking what the current fuse settings are, I think the main ones that slow down the clock are: CKSEL and SUT (the top dropdown list on the calculator website), and CKDIV8 - divide clock by 8; the second tickbox on the list. The defaults for these for AtMega 168 should be: Internal RC Oscillator: 8mhz, and the "Divide clock by 8" option selected.


body:
Have you burned a bootloader?
The standard Arduino IDE upload requires that you have a bootloader on the chip.
You can burn a bootloader with the Arduino IDE and your AVR dragon


body:
>. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Your dragon is an ISP so you don't have to unplug and replug it for programming.

I would check if your ftdi board an indeed function as a stk500.

Another alternative is to burn the bootloader and go down the regular Arduino route.


message:
Flashing a ATmega328 that came from an Arduino to not use an external oscillator

I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.

![Arduino ISP][1]

This image has this caption.

> Because no external clock source is connected, the ATmega must be configured to use its internal clock.

I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator.

So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?

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

    » avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.05s

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

    avrdude done.  Thank you.

I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

body:
> Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.

Pick up a 8-16MHz crystal (*not* an oscillator) and two 15pF capacitors and use **very, very short** wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.


body:
Even though an answer has been accepted, I just want to add for future viewers that you can google for arduino breadboard internal oscillator and get the text to copy into the boards.txt file.  That will allow you to use the Arduino IDE to burn the fuses.  You will be able to find versions to run at both 8mhz and 1mhz.

Also, if you have an extra Uno laying around, you could always pop the chip in there and reset the fuses, then take it out and use it on a breadboard.


message:
Auto detecting Baud Rate of Arduino

I'm trying to detect baud rate of Arduino Mega2560 by using C#. My code is below:

    SerialPort SP=new SerialPort();
    SP.BaudRate = 115200;

BaudRate is specified as a constant like this, but I would like to automatically detect it.

For instance, if Arduino code includes Serial.begin(xxxx), program should declare SP.BaudRate = xxxx.

How can I do it?

body: I'm not a C# programmer but [this](https://stackoverflow.com/a/16590749/4138037) StackOverflow answer might be what you're looking for.


message:
'readPulsioximeter' was not declared in this scope

I am new to Arduino. I am trying to use Pulsioximeter sensor with e-health Platform (<http://www.cooking-hacks.com/documentation/tutorials/ehealth-biometric-sensor-platform-arduino-raspberry-pi-medical>) on Arduino Uno. Line number 13 is working fine in the example code given in the library and works just fine. But when I try to upload my custom code (setup function definition is given below), I get an error stating 'readPulsioximeter' not defined in this scope. The error doesn't seem obvious to me. Please guide.

Here is the custom code upto setup() function:

    #include < eHealth.h >
    #include < PinChangeInt.h >
    bool configuration = false;
    //bool in_it=true;
    byte val; // variable to receive data from the serial port
    int ledpin = 13; // LED connected to pin 48 (on-board LED)
    int A=1;
    void setup() {
               pinMode(ledpin, OUTPUT);
               Serial.begin(115200);
               eHealth.initPulsioximeter();
               //Attach the interruptions for using the pulsioximeter.
               PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
               delay(500);
    }

 EDIT1:
readPulsioximeter is declared in eHealth.h library which has been included in program. The function has been defined as below in eHealth.cpp file:

        //!******************************************************************************
     //!  Name: readPulsioximeter()            *
     //!  Description: It reads a value from pulsioximeter sensor.    *
     //!  Param : void                *
     //!  Returns: void               *
     //!  Example: readPulsioximeter();           *
     //!******************************************************************************
     void eHealthClass::readPulsioximeter(void)
     {
      uint8_t digito[] = {0,0,0,0,0,0};
      uint8_t A = 0;
      uint8_t B = 0;
      uint8_t C = 0;
      uint8_t D = 0;
      uint8_t E = 0;
      uint8_t F = 0;
      uint8_t G = 0;
      for (int i = 0; i<6 ; i++) { // read all the led's of the module
       A = !digitalRead(13);
       B = !digitalRead(12);
       C = !digitalRead(11);
       D = !digitalRead(10);
       E = !digitalRead(9);
       F = !digitalRead(8);
       G = !digitalRead(7);
       digito[i] = segToNumber(A, B, C ,D ,E, F,G);
       delayMicroseconds(2800); //2800 microseconds
      }
       SPO2 = 10 * digito[5] + digito[4];
       BPM  = 100 * digito[2] + 10 * digito[1] + digito[0];
     }

body: The problem is that you have no function called "readPulsioximeter" in your code. Either define it, pick a different function, or remove that line of code.


body:
It looks like your missed naming the eHealth object, and that that statement should read:

`PCintPort::attachInterrupt(6, eHealth.readPulsioximeter, RISING);`

as you did with the initPulsioximeter call. (In otherwords, "which pulsioximeter?").


message:
Arduino Yun - Sensor Data logging to MYSQL on External Server

I want to log data from Sensors (Say Temperature, moisture or humidity) to a MYSQL database (provided by a online hosting company). Is it possible to establish communication between Arduino Yun and that database and log the data to it

body:
Yes, you can do that [using python][1] as well as other languages, or you can [use Temboo][2]: there's an example bundled with the Arduino IDE, it's called "SendDataToMySQL"

  [1]: http://dev.mysql.com/doc/connector-python/en/connector-python-examples.html
  [2]: https://www.temboo.com/arduino/yun/mysql


message:
avrdude: usbdev_open(): did not find any USB device "usb"

I was programing the arduino and things were going great.
Then I plugged in another chip, and went to burn a boot loader.
(New chips) now, I get:

    avrdude: usbdev_open(): did not find any USB device "usb"

when I try to upload code to old chips, I get:

    avrdude: usbdev_open(): did not find any USB device "usb"

ten times.
I have tried reseting, and it doesnt do anything.
when I plug the device in,

dmesg shows that the device responds to my PC

    [526199.130716] usb 3-1: new full-speed USB device number 7 using xhci_hcd
    [526199.149422] usb 3-1: New USB device found, idVendor=2341, idProduct=0043
    [526199.149427] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [526199.149430] usb 3-1: Manufacturer: Arduino (www.arduino.cc)
    [526199.149433] usb 3-1: SerialNumber: 649343332353518022F0
    [526199.149579] usb 3-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
    [526199.149766] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

IDE settings:
board: Audruino Uno
serial posrt /dev/ttyACM0
Programer: AVRISP mkII

I also tried AVR ISP

in the command line, I tried:

       avr-gcc -DF_CPU=16000000UL -mmcu=atmega328 -o Balls.out Balls.c
       avr-objcopy -O ihex -R .eeprom Balls.out  Balls.hex
       sudo avrdude -V -F -c stk500v1 -p m328 -b 19200 -P /dev/ttyACM0 -U flash:w:Balls.hex

each time, I get:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

How can I troubleshoot the Arduino Uno?
Is this thing broken?

body:
Generated from IDE
====

Because this is a generic error, I'll answer it. I was getting this on STDERR when using the IDE:

> avrdude: usbdev_open(): did not find any USB device "usb"

This is because in the IDE I was using

* Sketch → **Upload Using Programmer [Ctrl + Shift + U]**

However, I should have been using

* Sketch → **Upload [Ctrl + U]**


message:
Asynchronous control framework

Can anyone recommend an Arduino-based asynchronous scheduling library for controlling a small mobile robot?

I'm writing the control code for a small 2-wheeled Arduino-Uno based robot. It has a few bumper sensors, IR sensors, and ultrasonic sensors. I've written an initial pass from scratch, using `loop()` to read sensors and set motor values appropriately and then wait for the motor to have effect, but I'm finding this cluggy. Some of the sensors, like the ultrasonic range finders, require a small delay to operate, and the motors require a delay to have an effect. Blocking `loop()` is the simplest way to achieve this, but it wastes cycles, and can be difficult to time each action properly without throwing off other behaviors. Writing an asynchronous scheduler would be more efficient, but a lot more complicated, and I expect I would be reinventing the wheel.

I found [this list](http://playground.arduino.cc/Main/LibraryList#Sched), of existing scheduling libraries, but I'm not sure which, if any, would be appropriate.

body:
I would recommend [ChibiOS][1]: albeit it just got support for Arduino and it lacks a few drivers (I'm writing one for INTx and PCINT), it's got a fundamentally healthy design, a community around it and the author himself is very responsive.

You might have to write or port the drivers for external shields, however the upside is to get rid of the cruft that plagues most of the Arduino libraries.

You can even choose between 2 RTOS:

 - ChibiOS RT, a full fledged RTOS.
 - ChibiOS NIL, a minimalistic OS, actually almost a scheduler, which leaves more space and execution time for your own code. -
But if you check the amount of FLASH taken up by a typical binary built with the default Arduino libraries, you will see that it pulls in a large amount of typically unused stuff, so you could trade that for the use of the full fledged RT.

Disclaimer: I'm just a very happy user of the OS, I do not have any other involvement with it, especially the commercial part.

  [1]: http://www.chibios.org/


body:
I recommend writing your own in C++.  Arduino works well with C++ as it is written in C.  You can focus on getting the asynchronous behavior to do what you need instead of writing drivers.  I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.

Igor points out the advantages of going to a real time operating system.  I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.


message:
Need help to send serial data from arduino to XBee and to another XBee wirelessly?

I try to send serial data RPM to XBee series1 and then from XBee to another XBee wirelessly in API with Escapes Mode. I think I have to send the data Frame.But not very sure.
Any help?

Following is the code to read RPM and send to XBee?

    #include <XBee.h>
    #include <SoftwareSerial.h>
    /* Serial communication with Xbee.
    On Arduino pin 9 is Rx connect to Xbee Tx,
    pin 8 is Txconnect to Xbee Rx*/
    SoftwareSerial xbeeSerial(9, 8); // RX, TX

    XBee xbee = XBee();

    int pin = 7;  //7
    float rpm;
    float duration;
    float y;

    unsigned long val,time;
    float rps;
    float read_rpm;

    uint8_t start_data[] = { 0x7E, 0x00, 0x50, 0x01, 0x01, 0xff, 0xff,0x00, 0x05, 0x00,0x01,0x03, 0x84, 0x00 };

    void setup()
    {
      Serial.begin(9600);
      pinMode(pin, INPUT);
      Serial.println("I am ready to send some RPM!");
      xbeeSerial.begin(9600);
      time = millis();
    }

    void loop()
    {

    void loop()// run over and over
    {
     val =  pulseIn(pin, LOW,70000000);

     duration=(float)val/1000000.00;
     rps= 1.00/duration;
    rpm=60.00*rps;

    /* Sending float to Xbee
    Float is 4 byte size*/
    serialFloatPrint(rpm);

    int floatToInt = (int)rpm;

    /* To send INT to XBEE
    Int is 2 byte size*/
    xbeeSerial.write(highByte(floatToInt));
    xbeeSerial.write(lowByte(floatToInt));

      Serial.write(0x03);

      delay(2000);
    }

    void serialFloatPrint(float f) {
      byte * b = (byte *) &f;

      //xbeeSerial.print("f:");
      xbeeSerial.print(b[0]);
      xbeeSerial.print(b[1]);
      xbeeSerial.print(b[2]);
      xbeeSerial.print(b[3]);
      /* DEBUG */
      Serial.println();
      Serial.print(b[0],BIN);
      Serial.print(b[1], BIN);
      Serial.print(b[2], BIN);
      Serial.println(b[3], BIN);
      //*/
    }
    }

body:
You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. [Xbee-Arduino][1] library.

  [1]: http://code.google.com/p/xbee-arduino/


message:
How to convert byte array to float

How can I convert a byte array to float?

Code:

    void send_data() {
        CCPACKET data;
        data.length=2;

        float lon=26.533255;
        float lat=27.533463;

        data.data[0]=lon;
        data.data[1]=lat;

        if(cc1101.sendData(data)){
        Serial.println(data.data[0]);
        Serial.println(data.data[1]);

        Serial.println(" sent ok ");
        return true;
        }else{
        Serial.println("sent failed ");
        return false;
        }

     }

The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.

Here is the header file for CCPACKET I use:

    #ifndef _CCPACKET_H
    #define _CCPACKET_H

    #include "Arduino.h"

    /**
     * Buffer and data lengths
     */
    #define CC1101_BUFFER_LEN        64
    #define CC1101_DATA_LEN          CC1101_BUFFER_LEN - 3

    /**
     * Class: CCPACKET
     *
     * Description:
     * CC1101 data packet class
     */
    class CCPACKET
    {
      public:
        /**
         * Data length
         */
        byte length;

        /**
         * Data buffer
         */
        byte data[CC1101_DATA_LEN];

        /**
         * CRC OK flag
         */
        boolean crc_ok;

        /**
         * Received Strength Signal Indication
         */
        byte rssi;

        /**
         * Link Quality Index
         */
        byte lqi;
    };

    #endif

I was trying to fix it by this part of code, but without success:

    float lon=26.533543;

    *((float *)data.data[0]) = lon;

Can someone help me to convert the byte array to float?

body:
> /**
*Data buffer*/
byte data[CC1101_DATA_LEN];

That line of code declares an array of datatype [byte][1]. I suggest you review [variable declaration for Arduino][2].

A byte will store an 8-bit unsigned number with a range of 0 to 255, no decimal points. I also suggest you review truncation to understand how computer systems handle mathematic calculations that produce decimal results when the result is being stored in a variable type that doesn't store decimals.

A float stores a 32-bit value with decimal point.

The quick answer to your problem is to change the above quoted code from byte to float.

  [1]: http://arduino.cc/en/Reference/Byte
  [2]: http://arduino.cc/en/Reference/VariableDeclaration


body:
You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:

    ((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3]
    ((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7]

When printing you should also treat the data array as float array:

    Serial.println(((float *)data.data)[0]);

It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a  float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.


message:
What does the datasheet information for a switch mean?

I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps.

A project I'm working on now requires turning on an LED using a float switch like this one:
[Water Level Switch][1]

  [1]: http://www.seeedstudio.com/depot/water-level-switch-p-565.html

The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.

body:
A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than
20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.


body: It says "*maximum* breakdown voltage: 250 V DC". That's maximum, not minimum. Above 250 V DC the arc which is created by an opening contact isn't guaranteed to extinguish. It's defined for DC voltage because then the arc remains; for AC the arc will extinguish automatically when the current crosses zero.


message:
Can I simply unplug the Arduino usb if serial communication is active?

So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it.
Should be safe as long as nothing is uploading.
But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?

body: if the sketch is uploaded, it wont hurt it to unplug. Just give it another source of power and it will run its sketch.


body:
You can unplug it, it does not harm.
If your arduino does not need power, eg. for writing EEPROM or FLASH, then no danger there.
(in case it was writing EEPROM/FLASH it could write it faulty but usually even that is not a problem either)


body: Yes, you can unplug it directly whether if serial communication is active or not if you dont need power supply anu more using usb cable


message:
Breakout vs Shield

I would like to extend my arduino uno with WIFI and I am checking different options.

These are:

[Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna][1]

[Arduino WiFi Shield (integrierte Antenne)][2]

Viewing the price, obviously I understand that the shield will have more functions, I think also it is more "friendly" for programming and the breakout requires more low level code(I am not afraid of it...)

I already have an arduino yun but it is busy with a project, so I need something for the uno.

For what kind of projects could be better each of them? and what are the main differences between a shield and a breakout?

Also in the future I would do some projects with gsm, so this question could be similar ... gsm shield vs breakout.

  [1]: http://www.exp-tech.de/Shields/Wireless/WiFi/Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna.html
  [2]: http://www.exp-tech.de/Shields/Arduino-WiFi-Shield-integrierte-Antenne.html

body: Shields are in a form factor suited for direct attachment to the Arduino, but have fixed functionality for their connections. Breakout boards require more wiring work, but allow you to connect to any appropriate pins.


body: If you prototyping for a device intended for production then use breakout board with supposed WiFi module. Also if space is constraint then shield might be problem. For a hobby system use WiFi shield, which uses rather complicated circuit with AVR32 MCU, but you just plug-in and uses prooved libs. For production MCU would mean one more firmware flashing, upgrades, maintainance and higher price - from my point of view useless.


body:
A breakout board usually has the sole purpose of making a single chip (gross generalization here...) available to the experimenter by "breaking out" its signal lines on to dedicated pins - header pins, for instance. It is only large enough for the chip and the printed circuit wiring to do this, and seldom adds any function beyond what the chip itself provides.

A "shield" is a larger board that usually plugs directly onto an Arduino board, matches its form factor, and is built for a dedicated more complex function, like a complete GPS system or cellular communication system (although some shields are left mostly blank to provide you the space to build your own device). They probably have several chips engineered and built into a complete plug-and-go sub-system.

One is to learn to use a chip or other device without having to solder up your own board, especially with surface mount devices. The other is a ready-to-go system building block.


message:
How to pass rx/tx led outputs to a shield

I have an Arduino Uno. I am building a custom shield and was wondering how I would connect two of the LEDs on the shield to the TX / RX LEDs on the Uno. Digital pins 0 and 1 seem obvious, but after further research, it appears that they are not for this.

In better terms, I want two LEDs on my shield that replicate the TX / Rx LEDs on the Arduino Uno.

How would I do this?

body: The TX/RX LEDs on the Uno are not connected to the main MCU but are instead connected to the USB communication chip, be it a FTDI or ATmega16U2. You would need to solder wires to the appropriate connections on the board and then connect them to the shield in question.


body:
If you need just indicate data on TX/RX you can make simple circuit on shield bound to TX/RX lines.

![enter image description here][1]

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


message:
Help with a function that accepts different parameter types

I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.

    char PingTime[6] = "3ms";
    char PingText[60] = "ping reply blah blah";
    float humidity = "40.56";
    int DigialPin = 0;

    PrintXMLTag(cl,"pingtime",PingTime);
    PrintXMLTag(cl,"PingText",PingText);
    PrintXMLTag(cl,"humidity",humidity);
    PrintXMLTag(cl,"DigialPin",DigialPin);

    void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val)
    {
      char tmp [100];
      StrClear(tmp,100);

      // If val type is float ----------------------
      int d1 = val; // Get the integer part
      float f2 = val - d1; // Get fractional part
      int d2 = trunc(f2 * 10000);// Turn into integer
      sprintf(tmp,"<%s>%d.d</%s>\n",tag,d1,d2,tag);
      // end float

      // If val type is string ----------------------

      // If val type is int ----------------------

      // If val type is char ----------------------

      cl.print(tmp);
    }

------------------------------------------

Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.

    void PrintXMLTag(EthernetClient cl, char* tag,  char* val)
    {
      char tmp [100];
      sprintf(tmp,"<%s>%s</%s>\n",tag,val,tag);
      cl.print(tmp);
      StrClear(tmp,100);
    }

body:
take a look at: http://www.cplusplus.com/doc/tutorial/functions2/

    template <typename SomeType>
    SomeType sum (SomeType a, SomeType b)
    {
      return a+b;
    }
This appears to be what you want.


body: If your goal is really to print the value from XML, you don't need to worry about types, as long as you believe the XML to be correctly formed. The value in the XML file is already character string just print it. The converting from string to variable (sprintf()) and back to string (Serial.print() or printf()) is unnecessary.


body:
try using this example instead of iostream you can use iostream.h too..

    #include <iostream>
    using namespace std;

    int sum (int a, int b)
    {
      return a+b;
    }

    double sum (double a, double b)
    {
      return a+b;
    }

    int main ()
    {
      cout << sum (10,20) << '\n';
      cout << sum (1.0,1.5) << '\n';
      return 0;
    }


message:
DateTime to string

For some reason I can't use the `Time.h` lib.

Can you guys tell me how to create a string from the datetime into a format like this:

    yyyy.MM.dd:hh.mm.ss
    2014.10.29:07.12.33

Seems odd that I can't find any examples of this.

body:
There's no built in function to do that, I'm afraid.

I suggest you create a method that will format the string like so. Something along the lines of:

    void formatTime()
    {
       string str = year() + "." + month() + "." + day() + ":" + hour() + "FILL IN THE REST";
    }


body:
Is that what you want, mate?

    char buf1[20];
    DateTime now = rtc.now();
    //Updated now.day to now.date
    sprintf(buf1, "d:d:d d/d/d",  now.hour(), now.minute(), now.second(), now.date(), now.month(), now.year());

    Serial.print(F("Date/Time: "));
    Serial.println(buf1);


body:
If by `DateTime` you are referring to RTClib's [`DateTime`][1] (this is something you have to clarify in your question), then you can call [`unixtime()`][2] method on your `DateTime` object. The returned value is regular Unix "epoch" time, which can be used as `time_t` value with functions from `<time.h>` (and it's `<time.h>`, not `<Time.h>`).

For example, you can use [`ctime`][3] to convert Unix `time_t` value to a C-string, although the format of that string is different from the one you requested

    DateTime dt;
    ...
    time_t t = dt.unixtime();

    const char *str = ctime(&t);
    Serial.println(str);

On Arduino you also have `ctime_r` available to you as a reentrant version of `ctime`.

Or, if you need more flexibility with the format, you can use `gmtime` or `localtime` and then [`strftime`][4], but this might be excessive, since `struct tm` generated by `gmtime` is in essence very similar to `DateTime`. You can simply use `snprintf` in a manner suggested in @şevket Karayılan's answer.

Nevertheless, note that `strftime` provides you with quite extensive formatting capabilities, which would take some effort to reimplement manually

    DateTime dt;
    ...
    time_t t = dt.unixtime();
    struct tm *lt = localtime(&t);

    char str[32];
    strftime(str, sizeof str, "%Y.%m.%d:%H.%M.%S", lt);
    Serial.println(str);

    strftime(str, sizeof str, "%x %X", lt);
    Serial.println(str);

    strftime(str, sizeof str, "%F %T", lt);
    Serial.println(str);

  [1]: https://github.com/adafruit/RTClib/blob/master/RTClib.h#L30
  [2]: https://github.com/adafruit/RTClib/blob/master/RTClib.h#L49
  [3]: https://en.cppreference.com/w/cpp/chrono/c/ctime
  [4]: https://en.cppreference.com/w/cpp/chrono/c/strftime


message:
Multiple Stepper Motors in One Shield?

![enter image description here][1]

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

I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?

body:
Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).

But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)


message:
Modbus master slave

I need Help in two thing Here.
1)My main project is i have 23 hallsensors with analog output. There are connected to arduino UNO analog pins using 16:1 Mux or 8:1 mux circuit. The currently i can receive data properly with proper switching. Which are floating point values.
Second stage: Now this has to communicate via MODbus protocol .(here only transmission is pending)

2) Now I am in to transmission data. Here i am using basic library downloaded from
[Download link modbus library][1]

Now my setup is like this
I have arduino Board. RS485 sheild and USB to RS485 converter. Qmodbus software to view data.

I have uploaded the below code.

    #include <ModbusRtu.h>

    // data array for modbus network sharing
    uint16_t au16data[16] = {
      3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  u8serno : serial port (use 0 for Serial)
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus slave(1,0,0); // this is slave @1 and RS-232 or USB-FTDI

    void setup() {
      slave.begin( 9600 ); // baud-rate at 19200
    }

    void loop() {
      slave.poll( au16data, 16 );
    }
so i am expecting this answer if i am not wrong.

    uint16_t au16data[16] = {
      3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

But i am getting data as below.

questions:

1) Whats making wrong to get below data??
2)If i want to store float values how can name uint16_t au16data[16] or changes to be made
3) Is there any working code ON modbus![OUTPUt of MODBUS][2]

**Finally i got it working i can read The values. Now i am in second part. I have totally 20 values . currently i stored them as integer only. But my values are flaoting point.How to split real & floating value store in au16data[16] register.???**

Assume i got my Sensor value converted as
*

    CS=30.10
    Int_CS=int(CS)
    FLOAT_CS=(Int_CS-CS)*100
    How to store the Int_CS & FLOAT_CS values in au16data[0]??

*

body:
In Modbus protocol, `coils` are bits and `registers` are 16-bit unsigned integers.

Hence if you ask Modbus to read your `au16data` array as coils, and not as registers (which is what they actually are), then you'll get the binary representation for them with QModbus:

Your first register is `3` which is `0000 0000 0000 0011` in binary. Then when you read it as an array of 16 cils, you get these bit values, in reverse order (bit 0 is the lowest order bit and bit 15 is the highest order bit of your register); this is exactly what QModbus shos you:

- First 2 bits are 1
- All other bits are 0

Now regarding `float` values, if I remember correctly this is just not possible with Modbus protocol, hence you cannot do it out of the box.

What you can do, however, is to **cast one float as 2 registers** and transmit it this way, then it is up to the Modbus client to cast it back to a float; but QModbus will not do that for you as it strictly follows Modbus standard.


message:
Which side should I connect the resistor on?

I understand that when connecting an LED and a resistor in series; the resistor can be placed on any side of the LED as the current will remain same in a series connection. Please correct me if I'm wrong, but I was under the impression that conventionally the electrons flow from positive to negative. So shouldn't the resistor be placed before an LED to limit the flow of charge.

In this scenario the negative is connected ground and the positive to a power source. So I don't understand the chain Link analogy as well. Where the whole chain moves as a whole because here the flow ends with the GND right ?

body:
Resistor on any side of led will intercept current flow.
Just use another analogy with water, tube and water tap.


body: Another way to look at it is this:<br>Imagine the current flowing through the LED toward the resistor to be greater than the current flowing out of the resistor toward ground. The only way this could happen is if some of the charge - the difference due to the different currents - accumulated in the resistor. But that cannot happen forever, and not even for any appreciable length of time. (If it could, and did, the device would eventually fail - spectacularly!) So, because charge in must equal charge out over time (and over a very short period, at that) current in has to equal current out.


message:
sprintf trouble

char cTime[22];

    sprintf(cTime, "s/s/%2s:s:s:s", year(), month(), day(), hour(), minute(), second());

This `sprintf` line causes this error:**B0100000063f694Š

Could someone help me debug this?
Thank you.

body: *%s* is string macro but output of *year(),...* is probably an integer type. Use *%d* or *%u* macros in format.


body: Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.


message:
TCS3200 color sensor not reading with delay lower then 4000 ms using TimerOne.h

I'm trying to get the color sensor TCS3200 to give color values with a delay lower than 4000 ms. I've found a library to interface the TCS3200 from this [link][1].

I've modified the code to serve my needs and its works fine, almost! The before mentioned library uses [TimerOne.h][2], which can not accept a delay lower than 4000 ms.

My question is therefor, if it is somehow possible to modify my code, so I can lower the delay?

This is my code:

<!-- language: c -->

    #include <TimerOne.h>

    #define S0     6
    #define S1     5
    #define S2     4
    #define S3     3
    #define OUT    2

    int   g_count = 0;    // count the frequecy
    int   g_array[3];     // store the RGB value
    int   g_flag = 0;     // filter of RGB queue
    float g_SF[3];        // save the RGB Scale factor

    // Init TSC230 and setting Frequency.
    void TSC_Init()
    {
      pinMode(S0, OUTPUT);
      pinMode(S1, OUTPUT);
      pinMode(S2, OUTPUT);
      pinMode(S3, OUTPUT);
      pinMode(OUT, INPUT);

      digitalWrite(S0, LOW);  // OUTPUT FREQUENCY SCALING 2%
      digitalWrite(S1, HIGH);
    }

    // Select the filter color
    void TSC_FilterColor(int Level01, int Level02)
    {
      if(Level01 != 0)
        Level01 = HIGH;

      if(Level02 != 0)
        Level02 = HIGH;

      digitalWrite(S2, Level01);
      digitalWrite(S3, Level02);
    }

    void TSC_Count()
    {
      g_count ++ ;
    }

    void TSC_Callback()
    {
      switch(g_flag)
      {
        case 0:
             TSC_WB(LOW, LOW);              //Filter without Red
             break;
        case 1:
             g_array[0] = g_count;
             TSC_WB(HIGH, HIGH);            //Filter without Green
             break;
        case 2:
             g_array[1] = g_count;
             TSC_WB(LOW, HIGH);             //Filter without Blue
             break;
        case 3:
             g_array[2] = g_count;
             TSC_WB(HIGH, LOW);             //Clear(no filter)
             break;
       default:
             g_count = 0;
             break;
      }
    }

    void TSC_WB(int Level0, int Level1)      //White Balance
    {
      g_count = 0;
      g_flag ++;
      TSC_FilterColor(Level0, Level1);
      Timer1.setPeriod(1000000);             // set 1s period
    }

    void setup()
    {
      TSC_Init();
      Serial.begin(115200);
      Timer1.initialize();             // defaulte is 1s
      Timer1.attachInterrupt(TSC_Callback);
      attachInterrupt(0, TSC_Count, RISING);

      delay(4000);

      for(int i=0; i<3; i++)
        Serial.println(g_array[i]);

      g_SF[0] = 255.0/ g_array[0];     //R Scale factor
      g_SF[1] = 255.0/ g_array[1] ;    //G Scale factor
      g_SF[2] = 255.0/ g_array[2] ;    //B Scale factor

      Serial.println(g_SF[0]);
      Serial.println(g_SF[1]);
      Serial.println(g_SF[2]);
    }

    void loop()
    {
      g_flag = 0;

        int R = int(g_array[0] * g_SF[0]);
        int G = int(g_array[1] * g_SF[1]);
        int B = int(g_array[2] * g_SF[2]);

        if((R>245) && (R<265) && (G>245) && (G<265) && (B>245) && (B<265))    // White
        {
          Serial.println("Color is white");
        }else if((R>24) && (R<44) && (G>56) && (G<76) && (B>95) && (B<115))  // Blue
        {
          Serial.println("Color is blue");
        }else if((R>56) && (R<76) && (G>107) && (G<127) && (B>80) && (B<100))  // Green
        {
          Serial.println("Color is green");
        }else if((R>171) && (R<191) && (G>154) && (G<174) && (B>71) && (B<91))  // Yellow
        {
          Serial.println("Color is yellow");
        }else if((R>77) && (R<97) && (G>46) && (G<66) && (B>43) && (B<63))  // Brown
        {
          Serial.println("Color is brown");
        }else if((R>39) && (R<59) && (G>38) && (G<58) && (B>36) && (B<56))  // Brown dark
        {
          Serial.println("Color is brown dark");
        }else if((R>20) && (R<40) && (G>43) && (G<63) && (B>48) && (B<68))  // Turkis
        {
           Serial.println("Color is turkis");
        }else if((R>39) && (R<59) && (G>77) && (G<97) && (B>55) && (B<75))  // Green
        {
           Serial.println("Color is green");
        }else
        {
          Serial.print("Red = ");
          Serial.println(R);
          Serial.print("Green = ");
          Serial.println(G);
          Serial.print("Blue = ");
          Serial.println(B);

        };

       delay(4000);
    }

I've searched all over the net and didn't find any good solutions, where I can still specify the colours by hex degree.

All help would be highly appreciated!

  [1]: http://www.elecfreaks.com/5521.html
  [2]: http://playground.arduino.cc/Code/Timer1

body:
You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400).

PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.


message:
Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino

I'm asking if how can I implement this one. I'm aware about multiple devices being connected over SPI, like having to select individual SS pin for each. Adafruit's CC3000 works fine alone along with the default Adafruit library. CC3000 uses SPI. MFRC522 RFID module by sonmicro (bought at Sparksfun) uses SPI too. It works fine too, independently. But whenever I connect them together, only WiFi works perfectly. I dont want to turn on and off the wifi to make way for the RFID to communicate since it takes some time for it to be connected in a wireless network. I want the two to work synchronously (or having to be scheduled but really fast that's unnoticeable by the user)

here's my code as of now. i cannot post it here as strange things happen i don't know why haha https://drive.google.com/file/d/0B0bZsYo0xMH8YV9uWXJaRFdPT3M/view?usp=sharing

I'm thinking of replacing the RFID with SonMicro's SM130 RFID Module w/ SparkFun Eval board with UART (convertible to I2c) or Adafruit's PN532 with I2c by default. Are these okay to be paired with SPIs like the CC3000? Or should I change CC3000 with the Official WiFi module (UART) or WiFly Module (SPI-to-UART)

body:
I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers

I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.

However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).

So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.


message:
Rotary encoder on Uno and interrupts issue

This question is regarding a project using an Arduino Uno.

I have one of these [quadrature rotary encoders][1].

I'm using a slightly modified version of the code from the article, [Quadrature Encoder too Fast for Arduino (with Solution)][2], which uses a library called [digitalwritefast][3].

My version of the code on [pastebin][4] - I modified to use different pins for the Uno and a single encoder:

<!-- language: c -->

    #include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

    #define c_LeftEncoderInterrupt 0
    #define c_LeftEncoderPinA 2
    #define c_LeftEncoderPinB 3

    volatile bool _LeftEncoderBSet;
    volatile long _LeftEncoderTicks = 0;

    void setup()
    {
      Serial.begin(115200);
      pinMode(c_LeftEncoderPinA, INPUT);
      digitalWrite(c_LeftEncoderPinA, LOW);
      pinMode(c_LeftEncoderPinB, INPUT);
      digitalWrite(c_LeftEncoderPinB, LOW);
      attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
    }

    // Interrupt service routines for the left motor's quadrature encoder
    void HandleLeftMotorInterruptA()
    {
      _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
      _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
    }

    void loop()
    {
      Serial.print(_LeftEncoderTicks);
      Serial.print("\n");
      delay(20);
    }

I am attaching output A of the encoder to pin 2 and output B to pin 3.

This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying `c_LeftEncoderPinB` accordingly).

I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

  [1]: http://www.sparkfun.com/products/11102
  [2]: http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino
  [3]: http://code.google.com/p/digitalwritefast/
  [4]: http://pastebin.com/ts1QzbgM

body:
When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.


body:
My first thought is that something else is off because there is no reason that shouldn't work.  It will of course only count 1/4 of the ticks since that's how it was designed to work for very fast motors.  I can't comment yet but to Gerben above, I think it is meant to be bidirectional as indicated by the ternary operator.  My guess is the problem is with the digitalReadFast library and I would be interested to know if this works when using digitalRead() instead.

My second thought is that this is usually not the best way to do things.  Firstly, you would need a really fast motor for the read fast function to matter.  Secondly, you're sacrificing resolution by only using one interrupt instead of two.  The more generally accepted method is to attach both pins of the encoder to an interrupt.  Alternatively, you could use pin change interrupts which allow any pin to be used as an interrupt.  However, there are only 3 interrupt service routines on the Uno, one for each port of pins.  Whenever one pin on that port triggers, the ISR triggers and you need to keep track of the pin states in order to do anything with it.  Here's a good example of the [first][1] and info on the [second][2] method.

  [1]: http://bildr.org/2012/08/rotary-encoder-arduino/
  [2]: http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/


body: OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.


message:
Homebrew Arduino using ATMEGA328P, ISP or ICSP?

I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.

So the question is; Do I use ISP or ICSP, or both?

body: ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.


body:
To program it you could use an ISP programmer. In which case you would not need the bootloader. You can [use an Arduino as an ISP programmer][1], but that's not really a long term solution, as you can no longer use the arduino for anything else.

The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.

Third option would be implement USB into the bootloader, just like the *completely Open Source* Pro Trinket ([bootloader](https://github.com/adafruit/Adafruit_ProTrinket_Bootloader) and [schematic](https://learn.adafruit.com/system/assets/assets/000/018/948/large1024/adafruit_products_protrink5vschm.png?1408558753)). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


message:
Adafruit gps breakout module help

I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush.
Thanks in advance.

    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    #include <TinyGPS++.h>

    #define RXPin 2
    #define TXPin 3
    #define GPSBaud 4800

    SoftwareSerial ss(RXPin, TXPin);
    TinyGPSPlus gps;
    LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

    double latt;
    double lon;
    int screen;

    void setup(void);
    void loop(void);
    void readGPS(void);
    void update(void);
    void render(void);

    void setup() {
      //variable initialization
      latt = 0.0;
      lon = 0.0;
      screen = 0;

      //lcd initial setup
      pinMode(9, OUTPUT);
      analogWrite(9, 100);
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);

         //display intial screen
      lcd.begin(16,2);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Searching for");
       lcd.setCursor(6,2);
        lcd.print("Signal ...");
        ss.begin(GPSBaud);
    }

    void loop() {
     readGPS();
     update();
    }

    /** Receives data from the gps if available */
    void readGPS() {
     while (ss.available() > 0) {
      gps.encode(ss.read());
     }
    }

    /** Processes the data read by readGPS() */
    void update() {
     if (gps.location.isUpdated()) {
      latt = gps.location.lat();
      lon = gps.location.lng();
      render();
     }
    }

    /** Displays the current screen on the lcd */
    void render() {
     if (screen == 0) {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Lat:");
      lcd.print(latt);
      lcd.print(" Lng:");
      lcd.print(lon);
      lcd.setCursor(0,1);
      lcd.print("Sats:");
      lcd.print(gps.satellites.value());
     }
    }

body:
Adafruit GPS breakout has their own library setup.

Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.

You can just change that into SoftwareSerial.

    #include <SoftwareSerial.h>
    #include <Adafruit_GPS.h>
    #define GPSECHO false // Disables GPS breakout debug

    boolean usingInterrupt = false;

    HardwareSerial gpsSerial = Serial1;
    Adafruit_GPS GPS(&Serial1);

    SoftwareSerial XBee(2, 3); // For wireless

    unsigned int REFRESH = 20;

    double lat_deg, lon_deg, lat_min, lon_min;
    char lat, lon;

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

      GPS.begin(115200);
      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
      GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
      GPS.sendCommand(PGCMD_ANTENNA);

      useInterrupt(true);
    }

    SIGNAL(TIMER0_COMPA_vect)
    {
      char c = GPS.read();
    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;
    #endif
    }

    void useInterrupt(boolean v)
    {
      if(v)
      {
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      }
      else
      {
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    void loop()
    {
      if(GPS.newNMEAreceived())
      {
        if(!GPS.parse(GPS.lastNMEA()))
        {
          writeData(1, true);
          Serial.print(GPS.hour, DEC); Serial.print(F(","));
          Serial.print(GPS.minute, DEC); Serial.print(F(","));
          Serial.print(GPS.seconds, DEC); Serial.print(F(","));
          Serial.print((int)GPS.fix); Serial.print(F(","));
          Serial.print((int)GPS.fixquality); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999"));
        }
        else if(GPS.fix)
        {
          writeData(1, true);
          parseGPS(GPS.latitude, GPS.longitude);
          Serial.print(GPS.hour, DEC); Serial.print(F(","));
          Serial.print(GPS.minute, DEC); Serial.print(F(","));
          Serial.print(GPS.seconds, DEC); Serial.print(F(","));
          Serial.print((int)GPS.fix); Serial.print(F(","));
          Serial.print((int)GPS.fixquality); Serial.print(F(","));
          Serial.print(lat_dd, 8); Serial.print(F(","));
          Serial.print(lon_dd, 8); Serial.print(F(","));
          Serial.print(GPS.speed); Serial.print(F(","));
          Serial.print(GPS.angle); Serial.print(F(","));
          Serial.print(GPS.altitude); Serial.print(F(","));
          Serial.print(GPS.satellites);
        }
      }
      delay(REFRESH);
    }

    void parseGPS(float _latitude, float _longitude)
    {
      lat_deg = (int) (_latitude / 100);
      lon_deg = (int) (_longitude / 100);

      lat_min = _latitude - (lat_deg * 100);
      lon_min = _longitude - (lon_deg * 100);

      lat_dd = (double) lat_deg + ((double) lat_min / 60);
      lon_dd = (double) lon_deg + ((double) lon_min / 60);

      lat = GPS.lat; lon = GPS.lon;

      if (lat == 'S') lat_dd = -lat_dd;
      if (lon == 'W') lon_dd = -lon_dd;
    }

    void writeData(float data, boolean next)
    {
      Serial.print(data);
      if (next) Serial.print(F(","));
    }


message:
Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react

Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.

    int button_prev = 0;
    int button = 0;

    void loop(){

        button_prev = button;

        button = digitalRead(12);

        if (button_prev != button) {

          digitalWrite(act_pin[j], HIGH);

          j = (j+1) % 5;

        }
    }

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...

[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]

[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.

But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
`Serial.println` as well just spits out one character, similiar looking to a `d`.]

Can anyone point out my mistake to me?

This is the circuit

![enter image description here][1]

and this is the *old code* of the sketch

    int act_pin[6] = {A0, A1, A2, A3, A4};

    int j = 0;

    void setup(){

      Serial.begin(9600);

      for (int k = 0; k < 5; k++) {

         pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

         digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

         pinMode(12, INPUT); //sets pin connected to button as input

    }

    }

    void loop(){

      char button = {digitalRead(12)}; //stores if the button was pressed

      Serial.println(button);

      if(button == HIGH){

        digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

        j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

        button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
    }

    }

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

body:
>     if(button = HIGH)

Oops.

    if (button == HIGH)

And see the Debounce example sketch to learn how to debounce inputs.


body:
Your code has a serious bug here:

    if(button == HIGH){

        digitalWrite(act_pin[j], HIGH);

        j = j+1;

        button = LOW;
    }

You increment `j` without any boundary so it will have the following cycling values:

    0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly `act_pin[j]` will return garbage...

The solution is easy, you must limit `j` to `[0,1,2,3,4]`, just replace the `j = j + 1` line as follows:

    j = (j + 1) % 5;

`%` is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.


body:
I think you're looking for the action (in pseudo-code):

    ONCE (Button Pressed):
        Light LED j;
        j++

But you have an IF(button) in a Loop{}. Something like:

    WHILE (Button Pressed):
        Light LED j;
        j++

So when you press the button j will increment every iteration of Loop {}  (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.

Try printing j instead of button at the line:

    Serial.println(j);

and that should highlight the problem.

I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.

        button_prev = button;
        button = digitalRead(12);
    // Check if button changed from LOW to HIGH
        if (!button_prev && button) {
        ...code
        }

EDIT: Dealing with Contact Bounce

Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.

See [Measuring Switch Bounce][1]

![enter image description here][2]

You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:

    ONCE (Button Pressed):
       WAIT(20ms)              // wait for the bounce to stop
       IF(Button Pressed):     // Ensure the button is still pressed
        ...code...

Try the following Arduino Code:

        button_prev = button;
        button = digitalRead(12);
    // Check if button changed from LOW to HIGH
        if (!button_prev && button) {
           delay(20);                 // Wait for debounce
           if(digitalRead(12))  {     // Make sure the button is still pressed
            ...code
           }
        }

  [1]: http://www.picotech.com/experiments/switch_bounce/measuring-switch-bounce.html
  [2]: https://i.stack.imgur.com/I0Zol.gif


message:
Problem with piezo readings and Arduino Due

I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

![enter image description here][1]

and the following code to observe the readings in the serial monitor:

    int piezo = A0;
    int threshold = 200;//anything over 200 means I've hit the piezo

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

    //this part checks if the threshold has been reached and then writes the strenght of the signal

    void loop(){
        int piezoVal = analogRead(piezo);

        if (piezoVal>threshold){
            Serial.println(piezoVal);

            delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
        }
    }

The things that bother me are:

- if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.

- if I do not use delay, then I'm getting getting multiple values one after another

- and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?

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

body:
The problem is timing.  When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero.  You are expecting the code to capture the peak value.  Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.

So imagine this stream of signal values

    time  signal   analogRead()
          at pin   occurs
    ----  ------   --------
     1     190      190
     2     190
     3     199
     4     210
     5     220      220 - trips threshold, prints and then waits
     6     230
     7     260
     8     280
     9     320      (this point occurs during delay())
     10    280
     11    260

The same exact signal, but at a slightly different time could be read different by the code:

    time  signal   analogRead()
          at pin   occurs
    ----  ------   --------
     1     190
     2     190
     3     199      199
     4     210
     5     220
     6     230
     7     260      260
     8     280
     9     320      (closer, but still did not read the peak)
     10    280
     11    260

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value.  There are two ways forward: hardware or software.

You could use electronics that latches the maximum value.  If you search "peak hold circuit" you will find many circuits that would capture and hold the peak.  That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak.  Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.

You could use code to capture the peak. Something along the lines of this psuedo code:

    lastreading = analogread()
    if(lastreading > threshold) {
      peakreading = lastreading
      keeplooking = true
      while(keeplooking) {
        nextreading = analogRead()
        if(nextreading > lastreading) {
          // the signal is increasing, save this and see if next point is even higher
          peakreading = nextreading
          lastreading = nextreading
        }
        else {
          //signal is decreasing, the peak is over
          keeplooking = false
        }
      }

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.