body:
You could try not `digitalRead`, but `analogReadVoltage`. [Analog Read Voltage][1]

From Arduino examples:

    /*
      ReadAnalogVoltage
      Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
      Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

     This example code is in the public domain.
     */

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);
      // print out the value you read:
      Serial.println(voltage);
    }

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


sender: user

message:
How to generate Chirp Signal using Arduino

i would like to generate Chirp Signal (Frequency Sweep) using Arduino. i have searched a lot in internet but didn't find anything.

Basically, any parameters is also ok. But the concept is what i am searching for.
The signal will be sent to the DAC of the Arduino board.

Edit
I would like to generate sine wave signal from 3kHz up to 100kHz sweep frequency with amplitude peak to peak 1.5 volt.

thanks for your support.

sender: assistant

body:
Recommend to use a VCO PLL as external hardware device to get the wanted variable-frequency signal. The DAC output from Arduino can control the voltage to external VCO PLL module. Here is the link for an app note for VCO PLL from Vectron.

http://www.vectron.com/products/vcxo/vcxo.pdf

Hope it helps.


body:
If you're ok with starting with square wave signals, this can be done on an Arduino.
You need to do the following:

 1. Configure a 16-bit Timer to **CTC** mode
 2. Select the right prescaling
 3. Add a RC low pass filter to the output and voltage divider

Configure a 16-bit Timer to **CTC** mode
-----------------
Assuming I'm using **Timer 1** and **OCR1A**:

    TCCR1A |= (1<<COM1A0); // Toggle OC1A on match
    TCCR1B |= (1<<WGM12); // Clear to Compare mode
    TCCR1B |= (1<<CS10); // No prescale

Select the right prescaling
-----------------
In case you're wondering, prescales are used when the MCU clock is much faster than the output you desire.
Without prescaling, the highest frequency is 16MHz/2 = 8MHz, and the lowest frequency would be 8MHz / 2^16 = 122Hz . Which covers the range of frequencies that we want.

Setting OCR1A value to 80 gives you a frequency of 100kHz
Setting OCR1A value to 2667 gives you a frequency of 2.9996kHz

You can then control the chirp like so:

    // Linear rise in wave period
    int x = 10;
    for (int x=80; x < 2668; ++x){
      OCR1A = x;
      delay(10); // 10ms delay
    }

Add a RC low pass filter to the output and voltage divider
-----------------
Making the perfect sine waves may be too troublesome, so we'll resort to the poor man's sine wave.

Here's the [poor man's implementation][1] by TI (still require quite a few parts.)

Personally, I'm cheap so I'd go for the [RLC approach][2]. ;-)

  [1]: http://www.ti.com/lit/an/sbfa003/sbfa003.pdf
  [2]: http://www.wenzel.com/documents/waveform.html


body:
Since you mentioned SINE wave, I think you're seeking a SWEEP signal.  A chirp is a much more complex sound.

To get a sine wave sweep, you probably want a sine function that doesn't use up most of the Arduino executable space.

You can use one of the compact sin(theta) functions that leverage a simple table of values. Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c_src/cordic/cordic.html. C runs in Arduino sketches almost out of the box. You may or may not need some things from the cordic.h. That's why I said "almost". The cordic_prb.c test file has a function test002() that shows you how to call the sine function.

Letting theta = t * (t + k), you will get your sweep, with your instantaneous frequency, f = 2 * pi * (t + k).  You will need to calculate the correct k and set t_max to end your loop.  This can be obtained from the above formula and your f_min of 3kHz and f_max of 100kHz.

You can use a linear translation to get the sample in the range of values that you want: s = s_center + s_peak * sin(theta) / 2, but you will need to calculate your s_ave and s_peak from your center voltage, V_center, and your peak to peak voltage, V_peak.  So there are two translations.  This second one depends on the Voltage range of your Arduino board DAC.

Record your sample and voltage range for the board and then Work backward from Voltage range to V_center and V_peak to s_center and s_peak to your two coefficients to multiply and add to your sin(theta) result.

It's just a little algebra and some integration of some code, and you've got your SWEEP generator.

Also remember that boards like the Uno and Mega do not have a real D-to-A converter, so they will only give you a rectangular wave that has digital noise over the primary harmonic that approximates your sweep.  Use the Due to avoid lots of digital noise. That's the down side of the pulse width modulation of the lower end Arduino chips.

Either way, you may want to attenuate higher frequencies from any type of D-to-A conversion with a simple passive (RC) or active (op amp) low pass filter.


message:
How to access multiple SPI interfaces on Arduino

I have worked on [SPI][1] devices connected with an Arduino one at a time. How do I work with two different SPI devices at the same time?

  [1]: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

body:
Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.

When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.

There are some devils in the detail using multiple slaves, and [these are explained in more depth here](https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi), but in general, it's quite common and OK to use more than one SPI device as a slave.

[This blog post](http://www.dorkbotpdx.org/blog/paul/better_spi_bus_design_in_3_steps) will give you more information and is a good place to start reading.


message:
RFID system for proximity detection with data logging

I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., <= 1 meter).  Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.

My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated.  (Please keep in mind that I am not an engineer!)

I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system.  For beta-testing, this device could be set in an enclosed case and attached to a belt.  I presume it would require a fairly robust battery supply.  The other person would be wearing an RFID tag that has a range of <= 1 meter and would log the event.  Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.

Here are a few other things to keep in mind:

1.  The people using the hardware should not have to do anything other than simply wear the constructed devices.

2.  The reader itself should be as small as possible.

3.  My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).

Thanks in advance!
Brian

body:
This is a cheapo 125khz reader from Seeed Studio (Shenzhen):
http://www.seeedstudio.com/wiki/index.php?title=Electronic_brick_-_125Khz_RFID_Card_Reader

The range on it is very limited and I'm not suggesting you buy that specific one. Instead, just notice the pinout, +,-,TX,RX. You will find many, many readers with that same pinout. When a tag is detected, the reader blindly transmits the ID via UART (serial). You will also find many WiFi modules with similar TX/RX pins.

In your situation, the Arduino is actually wasteful since it's only purpose will be to mirror the reader's data from it's RX to it's TX. It's better to cut out the middle-man and just connect the (voltage-compatible) reader directly to the WiFi module to save power.

Many wireless modules are capable of automatically going low-power when there is nothing to do. Part of the receiver circuit will activate for transmitting, but since you are only transmitting sporadically from the belts, neither the receiver or transmitter needs to be powered constantly. I think you will be pleasantly surprised by the battery life.


body:
Consider using two basic XXMhz transceivers:

    -Master loops through used ID's and transmits them one at a time.
    -If a belt receives an ID other than it's own, it remains quiet.
    -If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
    -For a receiver to hear the very quiet signal, it will need to be very close.
    -The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
    -If sufficient proximity is detected, the event is reported to the Master.
    -If it receives no response, it informs the Master.
    -Master proceeds to the next ID.

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)

So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.

If ID is only 7 bits, the "protocol" could be as simple as a bitmask:

    Server = Send(ID &  (1 << 7)); //1XXXXXXX
      Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

Belts only reply to their ID if MSB is 1

This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data.
http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html

    Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
    Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

Neither is 100%, but both should work.


message:
Controlling image display on LED matrix by buttons

Building a 9x9 LED matrix and facing following 2 problems in Arduino code,

The current code displays 2 images (using byte arrays and then using bitRead) one by one, each for a certain duration of seconds. Persistence of vision is obtained by a delay of 300ms. There is a subroutine called upon in the main loop function with arguments of desired byte array and duration. I want to control the images by using 2 push buttons (push button1 and it displays 1st image until button2 is pressed, push button2 and second image is displayed until button1 is pressed). But the scanning algorithm exits the scan routine upon completion of the given input duration and restarts the routine with new argument (byte array of image2). I WANT THE IMAGE TO BE RETAINED ON THE MATRIX UNTIL BUTTON IS PRESSED. Can't figure out how to accomplish this.

If i nest the routine in a DO WHILE loop, then my problem is that how will the buttons be read from the main loop? Because I believe as long as the subroutine is being executed, main loop will be halted. (or I am totally wrong in this assumption?)

Reference code which I intend to manipulate. (Here its for an 8x8 Matrix. Thats not an issue)

    byte bigHeart[] = {
        B01100110,
        B11111111,
        B11111111,
        B11111111,
        B01111110,
        B00111100,
        B00011000,
        B00000000};

    byte smallHeart[] = {
        B00000000,
        B00000000,
        B00010100,
        B00111110,
        B00111110,
        B00011100,
        B00001000,
        B00000000};

    const int columnPins[] = { 2, 3, 4, 5, 6, 7, 8, 9};
    const int rowPins[] = { 10,11,12,15,16,17,18,19};

    void setup() {
        for (int i = 0; i < 8; i++)
        {
            pinMode(rowPins[i], OUTPUT); // make all the LED pins outputs
            pinMode(columnPins[i], OUTPUT);
            digitalWrite(columnPins[i], HIGH); // disconnect column pins from Ground
        }
    }

    void loop() {
        int pulseDelay = 800 ; // milliseconds to wait between beats
        show(smallHeart, 80); // show the small heart image for 100 ms
        show(bigHeart, 160); // followed by the big heart for 200ms
        delay(pulseDelay); // show nothing between beats
    }

    // routine to show a frame of an image stored in the array pointed to by the
    // image parameter.
    // the frame is repeated for the given duration in milliseconds
    void show( byte * image, unsigned long duration)
    {
        unsigned long start = millis(); // begin timing the animation
        while (start + duration > millis()) // loop until the duration period has passed
        {
            for(int row = 0; row < 8; row++)
            {
                digitalWrite(rowPins[row], HIGH); // connect row to +5 volts
                for(int column = 0; column < 8; column++)
                {
                    boolean pixel = bitRead(image[row],column);
                    if(pixel == 1)
                    {
                        digitalWrite(columnPins[column], LOW); // connect column to Gnd
                    }
                    delayMicroseconds(300); // a small delay for each LED
                    digitalWrite(columnPins[column], HIGH); // disconnect column from Gnd
                }

                digitalWrite(rowPins[row], LOW); // disconnect LEDs
            }
        }
    }

body:
OK. Figured out a solution which is working for me. Upon reading a forum on Arduino.cc. That stated a nice analogy to handle this issue.

You have something to heat up on stove while also waiting for an important email which you have to respond to immediately. (You only have a PC in the farthest corner of house at which you have to monitor your outlook :D) How will you do both tasks simultaneously? Run the stove for 10seconds, go to PC to check email, return to stove, run it again for 10 seconds, then again go to PC to check email. Do this until you get the email or your food gets hot enough.

To implement this in our program. I read the states of 2 buttons at start of the main loop. Store their values in 2 variables. Then check the values to check if some button is pressed. if value A is 1 and B is 0, call function A, if A is 0 and B is 1 call function B. The called function comprises of the scan routine. So when called, it performs 1 scan and comes back to the main loop. If no button was pressed meanwhile, the variables have same values, so the same function is called again and it performs the 2nd scan. if a button was pressed meanwhile, then 2nd function is called instead of the 1st one. The speed of all this is enough so that the user does not experience any delays, neither Arduino misses a button pressed while executing the scan.

The LEDs started to flicker when I implemented this code. So I further reduced the delay in the scan routine (time for which each LED is lit before turning it off and lighting the next one) from 300 microsecond to 100 and all went fine. My matrix of 64 LEDs is working fine however I assume that if matrix goes beyond some 100 LEDs then problems like delay or flickering or reduced brightness may arise.

Here is the complete code

    byte img1[] = {
        B01100110,
        B11111111,
        B11111111,
        B11111111,
        B01111110,
        B00111100,
        B00011000,
        B00000000
    };

    byte img2[] = {
        B00000000,
        B01100110,
        B01100110,
        B00000000,
        B00011000,
        B10000001,
        B01000010,
        B00111100
    };

    const int rowPins[] = {13,12,11,10,9,8,7,6};
    const int columnPins[] = {5,4,3,2,14,15,16,17};

    const int but1 = 18;
    const int but2 = 19;

    int but1State = 0;
    int but2State = 0;
    int but1Now;
    int but2Now;

    int value1;
    int value2;

    void setup() {

        for (int i = 0; i<8; i++){
            pinMode(rowPins[i], OUTPUT);
            pinMode(columnPins[i], OUTPUT);
            digitalWrite(columnPins[i], HIGH);
        }

        pinMode(but1, INPUT);
        pinMode(but2, INPUT);

        but1State = digitalRead(but1);
        but2State = digitalRead(but2);
    }

    void loop() {

        but1Now = digitalRead(but1);
        delay(5);
        int but1Now1 = digitalRead(but1);

        if(but1Now == but1Now1)
        {
            if(but1Now != but1State)
            {
                value1 = 1;
                value2 = 0;
                //show(img2);
            }

            but1State = but1Now;
        }

        but2Now = digitalRead(but2);
        delay(5);
        int but2Now1 = digitalRead(but2);

        if(but2Now == but2Now1)
        {
            if(but2Now != but2State)
            {
                value1 = 0;
                value2 = 1;
                //show(img2);
            }

            but2State = but2Now;
        }

        if(value1 == 1)
        {
            show(img1);
        }

        if(value2 == 1)
        {
            show(img2);
        }
    }

    void show(byte*image) {

        for(int row = 0; row<8; row++)
        {
            digitalWrite(rowPins[row], HIGH);

            for(int col=0; col<8; col++)
            {
                boolean pixel = bitRead(image[row],col);

                if(pixel == 1)
                {
                    digitalWrite(columnPins[col], LOW);
                }

                delayMicroseconds(150);
                digitalWrite(columnPins[col], HIGH);
            }

            digitalWrite(rowPins[row], LOW);
        }
    }


message:
Plugged in shield off by one, now all analogues read high

I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

![enter image description here][1]

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.

Now though A0-A5 are all reading high values (~900-1000 when I do `analogRead(A0)`), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.

The digital writes all work perfectly.

I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?

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

body:
There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.

If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.

Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?

![enter image description here][1]

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


message:
WORDS in ATmega328 datasheet note

I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.

It is the (8) note in pg.296-297 of [this datasheet][1]: what does WORDS mean in that context?

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

body:
**See jwpat7's answer.**
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

A Byte is most usually used to refer to an 8 bit quantity.

A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.

In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.

However,  the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "**Address Word**"is formed by the MSB + LSB combination.

![enter image description here][2]

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


body:
The notation is being used to indicate that the 16-bit address (as formed by the central bytes of a Write Program Memory Page instruction) is the address of a program-memory *word*, rather than a  program-memory *byte*.

The size of program memory is specified in bytes, but it often is addressed as words.  For example, the PC (program counter) register contains word addresses.

For some instructions, when the Z register is used to address program memory, it contains a word number and a byte selector:
> The Z-register in the Register File is used to access the Program memory. This 16 bits register pair is used as a 16 bits pointer to the Program memory. The 15 most significant bits selects the word address in Program memory. Because of this, the word address is multiplied by two before it is put in the Z-register. ... The least significant bit of the Z Address Register selects either Low byte (0) or High
byte(1) of the Program memory word. — [AVR108: Setup and Use of the LPM Instruction](http://www.atmel.com/Images/doc1233.pdf), page 1

*Note:* Some of the low bits of the word address in a “Write Program memory page” serial programming instruction are treated as don't-cares.  The number of don't-care bits depends on flash page size, which in Atmel AVR devices is 32, 64 or 128 words, depending on device series.

For example (as shown in Table 129 on page 304 of [doc2467.pdf](http://www.atmel.com/images/doc2467.pdf)) the ATmega128 with 128-word (256-byte) flash pages has seven don't-care bits in the low byte of the address.

    Table 129. SPI Serial Programming Instruction Set
                     -----------Instruction Format----------
     Instruction       Byte 1    Byte 2    Byte 3    Byte 4    Operation

    Write Program    0100 1100 aaaa aaaa bxxx xxxx xxxx xxxx
    Memory Page                                              Write Program Memory
                                                             Page at address a:b.


message:
Connecting a LSM9DS0 9DoF module to Arduino Uno

I got a bit confused by Sparkfun's [hookup guide](https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) for [this 9DoF breakout](https://www.sparkfun.com/products/12636) module.

It says the VDD-in on the breakout *"should [get voltage] regulated between 2.4V and 3.6V"*, yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.

Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?

body:
I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.

In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.


message:
Make a PC graphical interface for Arduino - Any easy software?

What's the best/easiest software to make a PC-Arduino interface? Ideally, I need to create a .exe that shows up a simple graphic interface, where the user can display data acquired from sensors connected to the Arduino (eg. Voltage, current etc.) and from there he should be able to control Arduino outputs through graphical buttons/switches.

To say that I am not a programmer, so if there's some sort of 'graphical coding' or 'non coding' software to make such things it'd be great!

Thanks for your help!!!

UPDATE:

Image of how the user interface should look like:

![Image of how the user interface should look like][1]

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

body:
Almost impossible to answer really. Questions with "best" are always going to yield opinions which probably won't apply to your situation. For example, I would do a C# desktop application because that's what I do, and nothing in that environment hinders communication with an Arduino. So, what's best for me is best because of "familiar and will work" and we can't decide what meets those criteria for you.

If you will update your question to describe more about your application, details about your interface, users, and what skills you have, then I will update this answer, but as it stands "the world is your oyster" because almost any programming environment capable of making an application will be able to interface with Arduino in some way.

For "graphical" programming look into LabView - I can think of a lot of reasons to not go that way though.  http://www.ni.com/labview/

Here's a tutorial for interfacing a c# application with Arduino:
http://www.codeproject.com/Articles/473828/Arduino-Csharp-and-Serial-Interface

The gist of it is this:

  1. Some version of Visual Studio up and running - you can use the free version mentioned in Jon's answer (Express version for desktops).
  2. A working Arduino connected to your computer with the USB.
  3. Create a new Windows Forms Application and drop whatever controls you need onto the form
  4. Write your Arduino-connecting code into the events of the controls

That is the basic method of creating Windows Forms apps regardless of what you're doing. You create forms with controls and your custom code goes into the events of those controls. If you read the tutorial it explains how that code works, but here's a sample... (In the tutorial, they are doing a WPF app, which is slightly different from Windows Forms in how the controls are defined, but the code is basically the same). This is an event of the serial port - you respond to the event by displaying the received data into a text box. Very simple!

    void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) {
        string data = mySerialPort.ReadTo("\x03");
        myForm.myTextBox.Text = data;
    }


body:
The "best" software for me is the free Visual Studio Express for Desktops.

Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

![VS][1]
Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.

To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:

    XXXYYYZZ
    Where:
    XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
    YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
    //Pin number does not have to match the MCU port/pin designations
    //MCU will convert logical pin #'s 0-7 into the correct physical port+pin
    //For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
    ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

    00100100b = "Set pin 1 high"
    01001000b = "Toggle pin 2"
    10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

Additional commands can be created to tell the Arduino to reply with a specific variable or status.

    bool isRegisterRead = false;
    bool isMultiByte = false;
    while (true)
     if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
      if (isMultiByte) //Second byte received
      {
        if (isRegisterRead)
        {
          //We need to read and send the value of the register at the address in byteReceived
          ReadAndSendRegisterValueAtAddress(byteReceived);
          isRegisterRead = false;
        }
        else DoSomethingWith(byteReceived);
        isMultiByte = false; //Start over
      }
      else //First or only byte received
      {
        //Consider using a ZZ bit to indicate more data instead of listing them explicitly
        if (byteReceived == 0x80) //A multi-byte "read register" command
        {
          isMultiByte = true; //Next byte received is money
          //For my example we need to set a flag somewhere to indicate that we are reading a register
          //isRegisterRead should be set to true by DoSomethingWith
        }
        //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
        DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
      }

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


body:
3 votes for visual studio and a windows desktop, although I would chose WPF. Win32 (Winforms) is a slightly out of date architecture. WPF has a steeper learning curve, but worth it if you want to become proficient. If it is a one off application, don't bother, use winforms.

I'll add a couple of points.  Debugging Arduino sucks. I am being kind.  The Arduino IDE deploys on com port 1, and prints debugging messages on com port 1, so if you need to communicate un-interrupted by debugging and deployment, what do you use? Not com port 1 for sure. Look at software serial in the beginning and assign ports around its requirements.

Second, writing your own com stack is dumb, yet is done 99% of the time.  Look at MQTT if ethernet is available, MQTT-SN if it is not, [CmdMessenger][1] or [CommandSerial][2] or something similar or spend days designing, writing, re-writing and debugging your own, your choice.

  [1]: http://playground.arduino.cc/Code/CmdMessenger
  [2]: http://playground.arduino.cc/Code/SerialControl


message:
XBEE coordinator WITH or WITHOUT Arduino?

I am building a wireless system that has got an Arduino with a XBEE as the 'end user' and I need to acquire data/control that Arduino from a PC graphical interface.
As far as I'm aware there are two options to obtain the communication:

1. I could use another Arduino with XBEE (coordinator) that is connected to my PC (serial) to control the 'end user'. The code is stored in this Arduino which works as a bypass between PC and XBEE.

2. I could simply use a XBEE without Arduino (coordinator) connected to my PC to control the 'end user'. The code should be stored within the PC or the XBEE to establish communication and control data transmission to different end users (???)

As I am new to the Arduino world, would you please direct me to the best/easiest solution to obtain such thing?

body:
If you want just to control and receive data from your end user, option 2 is easy to implement.

You can use any programming language that supports serial communication such as python, node.js, etc.

What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.

After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).

Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.

I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.

But for you purpose, AT mode seems enough.


message:
Arduino over a Network

I am new to arduino programming. I want to sense temperature and send it to a server in my college. I am using Arduino Uno R3 board which has ATmega 328P micro-controller. I am able to get serial output on my PC but is there a way in which I can send temperature data to the server in a packet format using Arduino Programmer and not using Ethernet Shield ? Please answer in a less complex way.

body:
Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:

arduino->serial (usb)->[processing][1]->[internet][2]

This way you create the internet packet in processing using the temperature information received through serial from arduino.

see also https://processing.org/

  [1]: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing
  [2]: http://forum.processing.org/one/topic/how-to-access-internet-through-processing-application.html


body:
Use an [Arduino Yún][1]: it's a Leonardo coupled with a CPU running GNU/Linux (a flavour of OpenWRT).

Using the Bridge library, your sketch can delegate tasks to the linux side.

HttpClient example (Examples > Bridge > HttpClient) GETs a page from the Arduino web site, but the HttpClient class may POST whatever data to a server of choice.

There is also a nice example called [SendDataToGoogleSpreadsheet][2] (Examples > Bridge > Temboo > SendDataToGoogleSpreadsheet): it accumulates sensor readings on a google spreadsheet. I've used something like that on a [project of mine][3].

  [1]: http://arduino.cc/en/Guide/ArduinoYun
  [2]: https://www.temboo.com/arduino/yun/update-google-spreadsheet
  [3]: https://github.com/ffissore/badger


message:
Serial.read() vs. Serial.readBytes()?

I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.

For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1.  Basically I construct some byte arrays as instructions, send them over to the servo (with `Serial1.write()`), and then read back a reply.  I've actually gotten it to work pretty well if I use `Serial1.readBytes()`, specifying the length of the buffer (number of bytes I'm expecting).  I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).

However I don't understand the difference between `Serial.readBytes()` and `Serial.read()`.  If I do `Serial.read()` just prior to `Serial.readBytes()`, it comes back with -1, meaning no bytes to read... but then `Serial.readBytes()` gives me the byte stream I was expecting from the buffer!  What's going on here?

Similarly, `Serial.available()` seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with `Serial.readBytes()`. Additionally, I can do `Serial.readBytes()` after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.

I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless.  Any clues about the difference in how these operate would be much appreciated!

body:
readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.

Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.

This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).

  #define TIMEOUT = 3000;
  loop {
   char inData[20];
   unsigned long timeout = millis() + TIMEOUT;
   uint8_t inIndex = 0;
   while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
    if (Serial1.available() > 0) {
     // read the incoming byte:
     inData[inIndex] = Serial.read();
     if ((c == '\n') || (c == '\r')) {
      break;
     }
     Serial.write(inData[inIndex++]);
    }
   }
  }

Above code was quickly written and untested. But gets the idea across.


message:
How do I write a debugger for Arduino?

I want to write my own debugger.

I've found [Visual Micro][1] plugin for Visual Studio provides Arduino Debug.

So, does anyone have ideas how it works?

I just desire make the same plugin in Eclipse IDE.

  [1]: http://www.visualmicro.com/

body:
Assuming you have enough time and money to spend on this project. ($50 is a bargain for a debugger, believe me. About a decade ago I wrote an assembler/debugger suite for a very small niche market microcontroller, the Maxim Integrated MAX1464, using a combination of SciTe and Perl/Tk. Writing your own debugger is a great educational project, if you have the time and money to complete it.)

**Tools**

Assuming you already have all the standard Arduino debug tools, and just want to learn the process of making a debug tool.

Assuming you've used the standard Arduino debug tools before, and written enough programs (sorry, you Arduino guys call them "sketches" for some reason) so that you have some code you feel comfortable debugging on. Setting a breakpoint in a simple "blinking LED" program isn't very satisfying, better to set breakpoints in a test program that actually does something. You'll also want to have some branching logic pathways to test breakpoints, and some variables (counters perhaps) so you can test reading values through the debug interface.

Assuming you have a couple of spare Arduino boards, because very likely during development some bad debug commands may get sent. Ideally you should have a device programmer capable of restoring the Arduino bootloader image that normally resides in the Atmel AVR processor. Sending arbitrary commands to the debug interface could possibly erase or mess up the bootloader.

Assuming you have access to customary EE lab tools: DMM, oscilloscope, soldering iron, etc.

**Research**

Assuming you already know how to make an Eclipse IDE plugin... (if you don't, that would be a question to research on Google or StackOverflow.) I'm treating this the same as if you were writing a plain command-line debugger or a gdb driver.

I'm not really sure which debug protocol you need to implement. Sadly, `JTAG` doesn't seem to be supported by Arduino. The `ICSP` in-circuit system programming header might give debug access, though it would require attaching some hardware to the board that you're debugging. If I understand correctly, the Arduino IDE supports debugging through the USB port, which is a very attractive setup.

Assuming you plan to use Atmel's proprietary `DebugWIRE` protocol, which someone else has kindly attempted to reverse-engineer here: http://www.ruemohr.org/docs/debugwire.html  Ideally you'd get the real documentation from Atmel. The hazard of a reverse-engineered protocol like this (aside from possible IP infringement) is that the protocol could change without notice. Not having direct access to the team that designed the microcontroller, means you have to rely on whatever documentation you can find and whatever else you can discover experimentally.

Assuming you can use the USB bridge chip's `DTR#` to drive (and possibly sense) the RESET pin, to access DebugWire. If that USB bridge chip is an FTDIchip.com device, you'll want to use the bit-banging mode to drive and sense DTR#. (In normal "RS232 mode" this pin is not bidirectional.) Go to the FTDIchip.com website to get the D2XX programmer's guide and example code.

Since DebugWire is a protocol that uses one wire for all signalling, both directions, timing is absolutely critical. **You must use an oscilloscope** to observe the DebugWire signals on the RESET pin, otherwise you're "flying blind".

That should be enough to get you started. Initially, you'll have to figure out how to discover an attached Arduino, enter debug mode, set a breakpoint, and reset the part back into free-running mode. The "blinking LED" test program is good enough to see some results for this early stage.

Cheers


message:
Uploading new sketch to Leonardo-type boards when you've changed the HID mode

I have Sparkfun Pro Micro (Leonardo compatible board). I got it because I plan to build my own array of controls for use in flight/racing sims.

My starting point is LeoJoy, and I didn't have any trouble getting this up and running. Installed just fine, and I have a programmable HID joystick available in windows. It seems to work by modifying the RAWHID code in the default libraries to spoof being a HID joystick. However, my board was now stuck in joystick mode, with no available COM ports for uploading new sketches.

Resetting the board (by grounding the RST pin), enables the COM port, but very, very briefly. Not enough time to send new sketches.

After about an hour of trying different timing, I finally did upload an empty sketch to the board before it went into Joystick mode. So I'm good for now, but I'm a bit worried that I'm going to have to repeat this every time I want to make a change to my program.

Am I doing something completely noobish here? Is this the correct way to program a board that has been forced to act as a joystick? Is there a better way?

Perhaps there's some code I can put into my sketch that will delay the change of USB behavior for a few seconds. That way, it will allow me to recompile and submit my sketches after a reset without having to rush the timing.

body:
From Sparkfun's page [Pro Micro Hook-upGuide][1]

When a Pro Micro is externally reset (by pulling the RST pin low), it’ll only briefly (<750ms) start the bootloader before continuing on to the sketch. If you need the bootloader to run longer, resetting twice quickly will get the Pro Micro to enter bootloader mode for eight seconds.

Hope that helps! If not there are some other procedures you might want to look into.

  [1]: http://f


message:
Will a magnetometer give distorted values if there is a magnet near?

I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?

body:
> Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.

In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.

The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

 - At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.

 - Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of **about** 1 Tesla at a distance of  1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.


body: The IMU magnetometer is made to measure the magnetic filed of the earth, which magnitude is a few 10 - 60 uT (micro-Tesla). You cannot measure it near to a large magnet that may generate 1 T or more: the magnetometer will saturate.


message:
arduino program got error expected //primary-expression before ')' token error: //expected ';' before '}' token E

#include "pulse-sensor-arduino.h"
    #include "Arduino.h"
    #define PulseSensorbegin

    int pulsePin = 0;
    int blinkPin = 13;
    int fadePin = 5;
    int fadeRate = 0;
    volatile int BPM;
    volatile int Signal;
    volatile int IBI = 600;

    volatile boolean QS = false;

    void setup(){

      pinMode(blinkPin,OUTPUT);
      pinMode(fadePin,OUTPUT);
      Serial.begin(115200);

      PulseSensorbegin();

    }

    void loop() {

       sendDataToProcessing('S', Signal);
       if (QS == true)
       {
           fadeRate = 255;
           sendDataToProcessing('B',BPM);
           sendDataToProcessing('Q',IBI);
           QS = false;
       }

       ledFadeToBeat();

       delay(5000);
    }

    void ledFadeToBeat(){

        fadeRate -= 15;
        fadeRate = constrain(fadeRate,0,255);
        analogWrite(fadePin,fadeRate);
      }

    void sendDataToProcessing(char symbol, int data ){

        Serial.print(symbol);
        Serial.println(data);
      }

/// my  ccp program

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];
    volatile unsigned long sampleCounter = 0;
    volatile unsigned long lastBeatTime = 0;
    volatile int P =512;
    volatile int T = 512;
    volatile int thresh = 512;
    volatile int amp = 100;
    volatile boolean firstBeat = true;
    volatile boolean secondBeat = false;
    volatile boolean Pulse = false;
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;
    volatile int PulseSensor::BPM;
    volatile int PulseSensor::Signal;
    volatile boolean PulseSensor::QS = false;
    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      TCCR1A = 0x00;
      TCCR1B = 0x0C;
      OCR1A = 0x7C;
      TIMSK1 = 0x02;
      sei();
    }

    ISR(TIMER1_COMPA_vect)

    {
      cli();
      PulseSensor::Signal = analogRead(pulsePin);
      sampleCounter += 2;
      int N = sampleCounter - lastBeatTime;

      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3)
    {
        if (PulseSensor::Signal < T){
          T = PulseSensor::Signal;
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P)
    {
        P = PulseSensor::Signal;
      }

      if (N > 250){
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;
          PulseSensor::IBI = sampleCounter - lastBeatTime;
          lastBeatTime = sampleCounter;

          if(secondBeat){
            secondBeat = false;
            for(int i=0; i<=9; i++){
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){
            firstBeat = false;
            secondBeat = true;
            sei();
            return;
          }

          word runningTotal = 0;

          for(int i=0; i<=8; i++){
            rate[i] = rate[i+1];
            runningTotal += rate[i];
          }

          rate[9] = PulseSensor::IBI;
          runningTotal += rate[9];
          runningTotal /= 10;
          PulseSensor::BPM = 60000/runningTotal;
          PulseSensor::QS = true;
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){
        Pulse = false;
        amp = P - T;
        thresh = amp/2 + T;
        P = thresh;
        T = thresh;
      }

      if (N > 2500){
        thresh = 512;
        P = 512;
        T = 512;
        lastBeatTime = sampleCounter;
        firstBeat = true;
        secondBeat = false;
      }

      sei();
    }

//my header programing

    #ifndef PULSE_SENSOR_ARDUINO_H
    #define PULSE_SENSOR_ARDUINO_H

    #include "Arduino.h"

    class PulseSensor
    {
    public:
      static void begin(int pulsePin);

      static volatile int BPM;
      static volatile int Signal;
      static volatile int IBI;
      static volatile boolean QS;
    };

    #endif

body:
At the top of your program you have this:

    #define PulseSensorbegin

which defines `PulseSensorbegin` as nothing

Then later you have:

    PulseSensorbegin();

which the pre-processor turns into:

    ();

which is where the error is occurring.


message:
How to get serial data in Arduino from a barcode scanner?

I want to interface my barcode scanner with an Arduino using RS232. I have connected 2 (RX), 3 (TX) and 5 (GND) of the RS232 with the corresponding pins of MAX232. I am taking TTL outputs on Arduino pins 6 and 7.

This is the code of the Arduino program:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(6, 7); // RX, TX

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

    void loop() {
      // run over and over
      if (mySerial.available()) {
        byte x = mySerial.read();
        Serial.println(x);
      }
    }

I am not getting any output on the serial monitor when I scan a product.

body:
Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.

However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.

Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.

Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.


body:
RS 232 works on different voltage levels than Arduino, I believe the values you are getting on the screen will have no meaning whatsoever, If the scanner output is TTL then yes it would work, but in my own experience that logic is inverted and you have to add a 1 to software serial:

SoftwareSerial mySerial(6, 7, 1); // RX, TX

The first step is checking what voltage level is given by your scanner output.


body: I tried this as well, for some reason it is NOT WORKING on pins 6 and 7, but it works perfectly using pins 10 and 11 instead. Of course, you still need to add the `mySerial.begin()`.


message:
Board recommendations for GPRS/GSM for 'on the go'

I have been tasked to find a way of communicating to a webservice from my microcontroller - yay!

With little-no real grasp on sms/etc (due to not ever 'using' it before), it appears that my knowledge of GPRS is, well, none existent.

So, I've come here in hope that someone could tell me if there is such a way for a microcontroller to 'send data out' though, well, a 'sim card' via an sms message.

**********

This has left me a little lost If i'm honest.

My project involves 'tracking' a vehicle (still working on finding a GPS module for that), and then sending the coordinates back to HQ at hourly intervals (via text message).

So, My obvious question is this: *What GPRS sim card module will allow me to do this?*

I read [here](https://arduino.stackexchange.com/questions/1194/which-shield-to-use-for-gprs), although the accepted answer there for a chip requires external power, and so is of no 'true' use to me as the whole unit needs to be powered and left 'unattended' for long hours at a time.

seeing as I also need to 'monitor current location' of the board, I am also in need to obtain a GPS location.

I was thinking that mobile phones have both of these cababilitys - is this done with a 'sim card module', or is there a way of 'one module does both - send an sms AND can also gain current GPS location'?

**************
Sorry if this is too broad, but I'm certainly not 'gifted' in knowing too much about these technologies (esp. when all these acronyms use similar letters).

Any advice / input here would be very helpful.

body:
I have a project that have the same idea that yours.

I used Ublox NEO-6M GPS Module for GPS tracking, the module cost in a range from $6 to $13 USD(it depends from where the seller ships, china o USA) in EBAY. You can connect it via UART.

For the internet I used a SIM800L V2.0 5V Wireless GSM GPRS MODULE, you can buy it from EBAY too, it cost no more than $10.00 USD, and you can connect to internet or send SMS using AT commands.

I used a combination of arduino and Raspberry pi zero, also I send the GPS data to a webserver (I pay 5dllr/month for a VPS) and then I can track using google maps.

Thats the basic information, you can use it to start working.


message:
How to connect twenty different serial devices to an Arduino Mega?

I want to connect 20 serial devices to the same Arduino Mega.How to do this?I know that multiplexing is the way but how to do that

body:
You say that they are working on RS232 - which is an electrical standard.  You may mean that they use standard UART style asynchronous serial communications - perhaps at 0 to 5V electrical levels.

It depends on how fast you need to communicate, and how continuously you need to communicate.   If you can choose when to communicate with each device, you may be able to use Soft Serial with multiple pins.  Be aware that it cannot both transmit and receive at the same time (one or the other), and it can only communicate with one port at a time.  So it might work for you if you can communicate with one device for a while, then ignore it while you check with other devices, one at a time.

Otherwise maybe not.  For example, if you need to receive from many devices at times of their choosing so you need an always-on hardware UART for each device.  There are 4 hardware UARTs in the MEGA, so 4 would be your limit.

There are things like external UART peripherals, but managing that would likely be very hard for you.


body:
You can use the SoftwareSerial library and declare instances to communicate with your serial devices. I am not sure if you can declare 20 such different instances but if at all you do, use the function: [listen()](https://www.arduino.cc/en/Reference/SoftwareSerialListen) to switch between those serial devices. This, probably, is as close as it gets to multiplexing as you mentioned.

I've tried with 2 such SoftwareSerial instances for communicating with GPS module and GSM module and the listen() function worked flawlessly.

Cheers!


message:
6 + 1 motors connected to an arduino uno?

Is it possible to connect 6 dc motors and 2 dc servo motors to an Arduino Uno? I intend to control the Uno with a Raspberry pi connected through USB.

Assuming every motor to be bidirectional, how many L293 or L298 motor driver boards do I need? Is there any other better option than using multiple driver boards?

body:
Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.

In addition, each servo will need one output pin (typically 9 and 10 for both servos).

Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!

If you can wire all 6 enable pins together, then **you will need "only" 15 pins**.

Also, note that if you want to **control the speed of the DC motors**, you will need PWM pins, but then **you won't get enough with a UNO**.

Regarding drivers ICs (**L293 or L298**), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so **you will need 3 of them overall**.


body:
TI is only one of the many manufacturers who make some really nice motor control chips.  The  DRV8835 is one such device: it will drive two motors at voltages up to 11 Vdc at currents up to 1.2 Amps each.  Each channel requires two control lines: enable and direction.

[Pololu][1] sells this chip already mounted to a carrier board for a rational price.

You will need a total of (6 motors * 2 lines per motor) = 12 i/o lines PLUS two more lines to control your servos for a total of 14 i/o lines from your controller.

  [1]: https://www.pololu.com/product/2135


message:
Writing serial data, just once after read

I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.

I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.

    int led = 13;
    char incomingByte = 10;
    long randNumber;
    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
     Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {

    //  delay(1000);               // wait for a second

       if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = Serial.read();
                    // say what you got:
                  //  Serial.print("I received: ");

                    randNumber = random(1, 2000);
                    Serial.println('PL' + randNumber);
                      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
                      delay(1000);               // wait for a second
                      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW

    }

    }

body:
When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. `Serial.read()` only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.


message:
How to know which Arduino to choose: Nano, Micro or Pro Micro?

I'm puzzled at the moment with which one to choose.

 - Form-factor plays a significant role in my project, so I prefer the smaller boards mentioned in the title to fuller boards like the UNO, MEGA, etc.
 - I have an RC522 RFID read/write module and would like to use it without having to deal with level switching, as the RFID module requires 3.3V.

What can you advise?

Thank you in advance!

body:
I'm currently using inexpensive Arduino Nano boards running GRBL for a couple of little CNC machines.  The version I have uses an ATmega328 running at 5V and they work *very* well.

They may be available with 3.3V regulator instead of 5V - I don't know and I preferred to have 5V anyway.

The nano boards that I have look to be a complete Arduino: one side of the board has the ATmega and voltage regulator, the other side of the board has the USB interface chip and some LEDs.

You can purchase Chinese-made nano boards very inexpensively.  Look on eBay for sellers offering free International shipping.


body:
I have used the ProMicro and the nano for a few projects and they are both great boards.  I had a little bit of trouble getting the Pro Micro up and running but SparkFun has a great tutorial that should give you plenty of information to get that board up and running. If it's between those three boards, I would suggest the Pro Micro.

You could also consider the Pro Mini (https://www.sparkfun.com/products/11114).  You will need an FTDI programmer for it (https://www.sparkfun.com/products/9873) but don't be discouraged by that.  It's really straightforward to use.  The cost is about the same as the Pro Micro and there are no special drivers required to get your computer talking to the Pro Micro.  The Pro Mini with the FTDI basic "just works".  One disadvantage to the Pro Micro is that you won't be able to power it over USB unless you leave the FTDI attached to it...but like most Arduinos you can just power it over a pin with a wide range of voltages.

Really any of the boards you mentioned will do the job.

Another board that's even smaller than the ones you mentioned would be the trinket or pro trinket by Adafruit.  Similar to the pro micro, you need some additional drivers but Adafruit is really good about providing tutorials.

If you don't want to worry about external programmers and additional drivers and you want to power over usb get the Micro.  If you are powering off of a battery and need to wire it up anyway and are willing to do a little bit of configuration on your computer consider the Pro Micro or the trinket.


message:
Learning to use ATmel Studio - using BOSSA downloader

The basic question - is BOSSA the right SOFTWARE  "tool" to use in ATmel Studio to **connect / download to Arduino DUE AND NOT using VisualMicro**?

I cannot get BOSSA to AUtoScan for COM port.
Getting error "Could not find a device"
When I select my COM port ( COM4 ) which works in Arduino IDE
I get "Could not connect to device on COM4"

This tells me that ATmel Studio does not recognize my Due at all.

Could someone please advise me what did I missed in configuring the Studio?

I can use Studio to run Arduino IDE (VisualMicro ) but I need to get away from Arduino IDE environment.
Thanks for your time.

body:
The Arduino Due needs a patched version of Bossa, not the 1.2.1 version available on SourceForge. Supposedly the patched version is available on GitHub, or you can copy the version in the Arduino IDE.

Also, the Due USB port must be put into bootloader mode. Open then close the serial port at 1200 baud, and it will re-instantiate as a Bossa programming port.

To return to serial port mode, the only way I have found is to power cycle the Due.


message:
How to prevent the Serial Monitor from closing upon re-uploading sketch?

I'll be teaching a year 10 class on the Intel Galileo gen2 and there'll be a wide (but high-level) programming curriculum, which includes introduction to console printing, using `Serial`.

I'd like the students to be able to write their printing code in `setup()` so that it's only printed once and easily readable by them. However, it's impossible to be fast enough to upload a sketch and open the Serial Monitor (which flat out refuses to open before the sketch has started), and the Serial Monitor closes itself upon re-uploading code.

Without unnecessary (and potentially for the students, confusing) use of the `delay` function in `setup()`, it's impossible to read any output originating from `setup()`; only things printed in `loop()` (which are constantly re-printed) are ever discoverable.

So; is there a way to somehow keep the Serial Monitor open, or make it capture output from before it's opened, or delay the entire running of the sketch (rather than chucking in delays)?

We'll be using the standard Arduino IDE.

**EDIT**

This script was run in one of two conditions...

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

      // ensure Serial is ready
      delay(1000);

      for (int i=0; i < 10000; i++) {
        Serial.println(i);
      }
    }

    void loop() {
    }

When the Serial Monitor was opened **immediately** after upload, all numbers from and including 0 to 9999 were recorded in the monitor.

When the Serial Monitor was opened around 5s **after** upload, only numbers upward of 2243 were observed. This suggests the sketch WAS being re-run (else no numbers would have been captured; the sketch runs in significantly less time than 5s) but that all numbers between 0 and 2243 were not captured by the monitor; as if opening the Serial Monitor late enough to cause a re-run causes some monitor overhead.
This strange loss of numbers is NOT time dependent: increasing the initial delay from 1s to 4s (and waiting longer after upload before opening the Serial) did not at all vary the soonest number recorded, suggesting it is some 'line' based overhead
(but of course, how could anything fail for 2243 lines?!)

With that mystery aside, this negates the automatic re-running of the sketch upon Serial Monitor opening from being actually useful.

body:
I assume you are uploading the code over USB - the same USB that you want to monitor for output from the sketch? If so, the serial monitor has to release the port for the uploader to be able to use it, and vice-versa, as your computer's OS will only assign a USB port to one application at a time.

It may seem like the IDE is one application containing an uploader and a serial monitor, but the IDE is not much more than a "pretty face" that runs separate compiler and uploader applications on your behalf.

Several work-arounds are possible (although I think a `delay()` statement in `setup()` is the clearest of the choices):

 - Add a delay statement in the setup function. If you must this, you can put it in `main()` just before the `setup()` call, but you'd take away a learning opportunity.
 - Use a separate hardware or software serial channel for the monitor which you could leave connected and wouldn't interfere with uploading;
 - Use the `loop()` function instead, and put a forever loop at the bottom to prevent it returning, thus making it a runs-once function.


body: Have you tried hitting the reset button while the serial monitor is open?  I have done this on other Arduino boards to capture stuff in the setup loop that was occurring too fast.  Otherwise using Serial1 for output connected via a FTDI cable may be the way to go.


message:
Using an Arduino to switching a grounded load powered by a 12 Volt supply

I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.

This is what I have tried so far.

![led strip mosfet arduino][1]

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

The ***load must be between*** my ***mosfet*** and my car battery ***GND***.

body:
In your existing arrangement.

Swap to P Channel FET
Swap drain and source leads (right hand two).

This will work for up to 5V feed to LEDs.

To get 12v operation you will need to add a driver between the FET gate and the Arduino.
see circuit diagram below.

__________

To operate with FET on the HIGH (V+) side when V+ is greater than the rduino's supply voltage, the FET must either

 - Be P Channel with FET source to +12V and FET drain to load+ or

 - An N Channel with gate drive above V+.

   The gate drive to the FET must go to about +12V to turn it off.
The Arduino will only drive it to +5V.

As you are unlikely to want to provide an extra high side drive the P channel option is preferred. This could be eg:

 - A "jellybean" bipolar transistor or small FET worth a few cents) and a few resistors, or a small N Channel MOSFET and one resistor

or

 - An opto isolator.

__________________________

**Transistor driver:**

Bipolar transistor NPN (BC337 / BC817 or similar)(ANYTHING NPN will work).
R1 = 10k resistor Arduino out to base.
R2 = 10k FET gate to +12.

If an N Channel MOSFET is used for Q1 then R1 is not needed.

This could be a  [5LN01SP](http://www.onsemi.com/pub_link/Collateral/EN6559-D.PDF) IF you can get them - no stock Digikey.These have a very low Vgsth (turn on voltage)

Otherwise you can use a 2n2222, VN2222, BS108 or similar logic-gate N channel MOSFET.
eg [VN2222](http://www.onsemi.com/pub_link/Collateral/VN2222LL-D.PDF). Many variants of these are widely available and low cost.

<!-- 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/OQdAa.png)

<!-- End schematic -->


message:
Servo Buzz / millis()

I am having a problem with Servo Buzz that I have ascertained is from the `millis()` function using too much time for Arduino to generate a steady pulse for the servos.

I looked at this thread but was unable to figure out a solution from the code (I'm a novice)

[Stack Exchange Servo Buzz][1]

  [1]: https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking?newreg=bc15727ab5ef45e38e50d8f02faf70de

I am including my code even though it is very large, the only time I **need** to servos to run smoothly is in `case 4` of my `switch/case`.

    #include <Wire.h>
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <Adafruit_MotorShield.h> //LIBRARY FOR MOTOR DRIVER SHIELD
    #include "utility/Adafruit_PWMServoDriver.h"
    #include <Servo.h> //LIBRARY FOR SERVOS

    Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
    Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
    #define WHITE 0x7

    Servo pan;
    Servo tilt;//DECLARE SERVOS
    int yy = 0; //STEP COUNTER
    //declares ints
    uint8_t i=0; //BUTTON INPUTS
    int x = 1; //case statement movement
    int input_stage = 0;
    int time = millis(); //time from when the thing turned on

    //user inputs
    int total_hour = 0;
    int total_minute = 0;
    int slide_min = 0;
    int slide_max = 0;
    int pan_min = 800 ;
    int pan_max = 2200;
    int tilt_min = 800;
    int tilt_max = 2200;

    //Integers used for calculations for later
    int total_steps = yy;
    long total_time = 0;
    long step_duration = 0;
    int total_pan = 0;
    int total_tilt = 0;
    long pan_duration = 0;
    long tilt_duration = 0;
    long step_millis = 0;
    long pan_millis = 0;
    long tilt_millis = 0;
    int step_percent = 0;

    // Integers for real time program sliding action
    int cur_step = 0;
    int pan_pos = 0;
    int tilt_pos = 0;
    long run_dur = 0;
    long start_time = 0;
    int total_slide = 0;
    long display_refresh = millis();
    long display_dur = 1000;
    int d = 1;
    long end_time = millis();
    int m = 0;

    void setup(){
      lcd.begin(16, 2);
      lcd.setBacklight(WHITE);
      lcd.print("Welcome to LapsR");//initialize
      delay(2000);

      AFMS.begin();  //initialize motor shield
      pan.attach(10); //attach servos to pins
      tilt.attach(9);

      myStepper->setSpeed(30); // set speed

      lcd.setCursor(0, 0);
      lcd.print("By Doug E FresH!");
      delay(2500);
      lcd.setCursor(0, 1);
      lcd.print("Thanks to: Dave");
      delay(2000);
      lcd.setCursor(0, 1);
      lcd.print("Thanks to:  Max");
      delay(2000);
      pan.writeMicroseconds(1500); //set pan and tilt servos to centre ish
      tilt.writeMicroseconds(1500);
      delay(5000);
      pan.writeMicroseconds(1000); //Jitter Test
      tilt.writeMicroseconds(1000);
      delay(5000);
      pan.writeMicroseconds(2000); //Jitter Test
      tilt.writeMicroseconds(2000);
      delay(5000);
    }

    void loop(){
      uint8_t buttons = lcd.readButtons();  //read lcd buttons
      lcd.blink(); //set cursor to blink
      int limit1 = 4;  //declare limit switch
      pinMode(limit1, INPUT_PULLUP);  // sets pin mode to button

      //begin case statement
      switch(x){
      case 1:

       if(m==0){ //move slider backwards until it finds a limit switch
        if((digitalRead(limit1) == HIGH)){ // digital read reads the limit switch pin - HIGH means the switch is open
          myStepper->step(2,BACKWARD,DOUBLE);
          lcd.clear();
          lcd.print("stage 1");
          delay(10);
        }
        else{ //move to the next step
          myStepper->release(); //release motor
          m = 1; //set program to 2nd stage
        }
      }
      if(m==1){ // moving ahead jus a bit so there is some pad for innacuracy
        yy = 50; //step counter is initialized
        lcd.clear();
        lcd.print("stage 2");
        delay(1000);
        myStepper->step(50,FORWARD,SINGLE); //move forward 50 steps
        m = 2;//move to the next step
      }
      if(m==2){ //stage 3 dawg
        if((digitalRead(limit1) == HIGH)){//count steps til limit is hit
          myStepper->step(1,FORWARD,SINGLE);//move forward 1 step
          lcd.clear();
          lcd.print("stage 3");
          yy++; //step counter move up one
          delay(10);
        }
        else{  //display step percentage and total steps
          x=2;
          lcd.clear();
          lcd.print("step %");lcd.print((yy-100)/100);
          delay(5000);
          lcd.clear();
          lcd.print("total: ");lcd.print(yy-100);
          delay(5000);

          myStepper->step((yy - 50),BACKWARD,SINGLE); // reset to start position (minus 50 steps for pad)
          myStepper->release(); // release motor
          step_percent = (yy-100)/100; //make calculations
          total_steps = yy-100;
        }
      }

    break;

      case 2:

        if(input_stage == 0){ //enter duration
          if(d==1){
            lcd.clear();
            lcd.print("Total Duration?");//start asking for inputs - start with total overall duration hours
            lcd.setCursor(0, 1);
            lcd.print("H: ");
            lcd.print(total_hour);
            lcd.print("  M: ");
            lcd.print(total_minute);
            lcd.setCursor(3,1);
            display_refresh = millis();
            d = 0;
          }
          if (buttons & BUTTON_UP) {  //sets hour up - slight debounce delay
            total_hour = total_hour++;
            delay(250);
            d=1;
          }
          if (buttons & BUTTON_DOWN) { //sets hour down
            total_hour = total_hour--;
            delay(250);
            d = 1;
          }
          if (buttons & BUTTON_SELECT){
            input_stage++;delay(250); //select button moves to next stage
            lcd.clear();
            d=1;
          }
        }
        if(input_stage == 1){
          uint8_t buttons = lcd.readButtons();
          if(d==1){  //when d == 1 update display
            lcd.clear();
            lcd.print("Total Duration?");//ask for minutes
            lcd.setCursor(0, 1);
            lcd.print("H: ");
            lcd.print(total_hour);
            lcd.print("  M: ");
            lcd.print(total_minute);
            lcd.setCursor(9,1);
            d=0;
          }
          if (buttons & BUTTON_UP) {
            total_minute = total_minute++;  //set minutes
            delay(100);
            d=1;
          }
          if (buttons & BUTTON_DOWN) {
            total_minute = total_minute--; //set minutes
            d=1;
            delay(100);
          }
         if (buttons & BUTTON_SELECT){
           input_stage++; // select moves to next stage
           delay(250);
           lcd.clear();
           d=1;
         }
         if (buttons & BUTTON_LEFT){
           input_stage--; //back moves to previous stage
           delay(250);
           d=1;
         }
       }
       if(input_stage == 2){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.clear();
           lcd.print("Slide%start-fin");//ask for minimum slide percentage
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(slide_min);
           lcd.print("  F: ");
           lcd.print(slide_max);
           lcd.setCursor(3,1);
           d=0;
         }
         if (buttons & BUTTON_UP && slide_min < 100) {
           slide_min = slide_min++; // select start position in percentgae
           d=1;
           delay(100);
           myStepper->step(step_percent, FORWARD, DOUBLE); //move forward one percent - allows user to preview positions
         }
         if (buttons & BUTTON_DOWN && slide_min > 1) { // do not allow motor to move below 0 percent
           slide_min = slide_min--;
           myStepper->step(step_percent, BACKWARD, DOUBLE);//move forward one percent - allows user to preview positions
           d=1;
           delay(100);
         }
         if (buttons & BUTTON_SELECT){ //moves to next stage
           input_stage++;
           delay(250);
           lcd.clear();
           slide_max = slide_min; //sets ending position to set min position
           d=1;
         }
         if (buttons & BUTTON_LEFT){
           input_stage--;delay(250); // previous stage
           d=1;
         }
       }
       if(input_stage == 3){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.clear();
           lcd.print("Slide%start-fin");//ask for max slide percentage
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(slide_min);
           lcd.print("  F: ");
           lcd.print(slide_max);
           lcd.setCursor(9,1);
           d=0;
         }
         if (buttons & BUTTON_UP && slide_max < 100) {
           slide_max = slide_max++;
           d=1;delay(100);
           myStepper->step(step_percent, FORWARD, DOUBLE);  //shows set stepper position
         }
         if (buttons & BUTTON_DOWN  && slide_max > 1) {
           slide_max = slide_max--;
           myStepper->step(step_percent, BACKWARD, DOUBLE);
           d=1;
           delay(100);
         }
         if (buttons & BUTTON_SELECT){ //moves to next stage
           input_stage++;
           delay(250);
           lcd.clear();
           myStepper->step((step_percent*slide_max), BACKWARD, DOUBLE); //sets platform back to home position
           d=1;
           myStepper->release();
         }
         if (buttons & BUTTON_LEFT){
           input_stage--; //moves to previous stage
           delay(250);
           d=1;
         }
       }
       if(input_stage == 4){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.clear();
           lcd.print("Pan start-fin");//ask for min pan
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(pan_min);
           lcd.print("  F: ");
           lcd.print(pan_max);
           lcd.setCursor(3,1);
           d=0;
         }
         if (buttons & BUTTON_UP) {
           pan_min = pan_min + 10;  //sets displays pan parameters
           pan.writeMicroseconds(pan_min);
           d=1;
           delay(10);
         }
         if (buttons & BUTTON_DOWN) {
           pan_min = pan_min - 10;
           d=1;
           delay(10);
           pan.writeMicroseconds(pan_min);
         }
         if (buttons & BUTTON_SELECT){
           input_stage++;
           delay(50);
           lcd.clear();
           pan_max=pan_min; //sets max to min to not cause a brownout
           d=1;
         }
         if (buttons & BUTTON_LEFT){
           input_stage--;
           delay(50);
           d=1;
         }
       }
       if(input_stage == 5){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.clear();
           lcd.print("Pan start-fin");//ask for max pan
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(pan_min);
           lcd.print("  F: ");
           lcd.print(pan_max);
           lcd.setCursor(9,1);
           d=0;
         }
         if (buttons & BUTTON_UP) {
           pan_max = pan_max + 10;
           d=1;
           delay(10);
           pan.writeMicroseconds(pan_max);
         }
         if (buttons & BUTTON_DOWN) {
           pan_max = pan_max - 10;
           pan.writeMicroseconds(pan_max);
           d=1;
           delay(10);
         }
         if (buttons & BUTTON_SELECT){
           input_stage++;
           delay(250);
           lcd.clear();
           d=1;
         }
         if (buttons & BUTTON_LEFT){
           input_stage--;
           delay(250);
           d=1;
         }
       }
       if(input_stage == 6){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.clear();
           lcd.print("tilt start-fin");//ask for min tilt
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(tilt_min);
           lcd.print("  F: ");
           lcd.print(tilt_max);
           lcd.setCursor(3,1);
           d=0;
         }
         if (buttons & BUTTON_UP) {
           tilt_min = tilt_min + 10;
           d=1;
           delay(10);
           tilt.writeMicroseconds(tilt_min);
         }
         if (buttons & BUTTON_DOWN) {
           tilt_min = tilt_min - 10;
           tilt.writeMicroseconds(tilt_min);
           d=1;
           delay(10);
         }
         if (buttons & BUTTON_SELECT){
           input_stage++;
           delay(250);
           tilt_max=tilt_min;
           lcd.clear();
           d=1;
         }
         if (buttons & BUTTON_LEFT){
           input_stage--;
           delay(250);
           d=1;
         }
       }
       if(input_stage == 7){
         uint8_t buttons = lcd.readButtons();
         if(d==1){
           lcd.print("tilt start-fin");//ask for max tilt
           lcd.setCursor(0, 1);
           lcd.print("S: ");
           lcd.print(tilt_min);
           lcd.print("  F: ");
           lcd.print(tilt_max);
           lcd.setCursor(9,1);
           d=0;
         }
         if (buttons & BUTTON_UP) {
           tilt_max = tilt_max + 10;
           tilt.writeMicroseconds(tilt_max);
           d=1;
           delay(10);
         }
         if (buttons & BUTTON_DOWN) {
           tilt_max = tilt_max - 10;
           delay(10);
           tilt.writeMicroseconds(tilt_max);
           d=1;
          }
          if (buttons & BUTTON_SELECT){
            input_stage++;delay(250);
          }
          if (buttons & BUTTON_LEFT){
            input_stage--;delay(250);
          }
        }
        if(input_stage == 8){   //confirm parameters
          lcd.noBlink();
          uint8_t buttons = lcd.readButtons();
          lcd.clear();
          lcd.print("SL: ");
          lcd.print(slide_min);
          lcd.print(" - ");
          lcd.print(slide_max);
          lcd.setCursor(0,1);
          lcd.print("PN: ");
          lcd.print(pan_min);
          lcd.print(" - ");
          lcd.print(pan_max);
          delay(2500);
          lcd.clear();
          lcd.print("TI: ");
          lcd.print(tilt_min);
          lcd.print(" - ");
          lcd.print(tilt_max);
          lcd.setCursor(0,1);
          lcd.print("Dur: ");
          lcd.print(total_hour);
          lcd.print(":");
          lcd.print(total_minute);
          delay(2500);
          lcd.clear();
          lcd.print("Left for back");
          lcd.setCursor(0,1);
          lcd.print("Select to go");
          delay(2500);
          if (buttons & BUTTON_SELECT){
            x = 3; //if user is happy with set parametres - continue to run move program
          }
          if (buttons & BUTTON_LEFT){
            input_stage--;delay(50); // if user made a mistake they can press left to go back
          }
        }

    break;

        case 3:

        //calculate moving time durations
        total_time = total_hour*60;
        total_time = total_time + total_minute;
        total_time = total_time*60000;
        total_slide = slide_max - slide_min;
        step_duration = total_time/(total_slide*step_percent);
        total_pan = pan_max - pan_min;
        total_tilt = tilt_max - tilt_min;
        pan_duration = total_time/total_pan;
        tilt_duration = total_time/total_tilt;

        //display values for debuging
        lcd.clear();
        lcd.print("total time");
        lcd.setCursor(0,1);
        lcd.print(total_time);
        delay(5000);
        lcd.clear();
        lcd.print("total slide");
        lcd.setCursor(0,1);
        lcd.print(total_slide);
        delay(5000);
        lcd.clear();
        lcd.print("step duration");
        lcd.setCursor(0,1);
        lcd.print(step_duration);
        delay(5000);
        lcd.clear();
        lcd.print("total pan");
        lcd.setCursor(0,1);
        lcd.print(total_pan);
        delay(5000);
        lcd.clear();
        lcd.print("total tilt");
        lcd.setCursor(0,1);
        lcd.print(total_tilt);
        delay(5000);
        lcd.clear();
        lcd.print("pan duration");
        lcd.setCursor(0,1);
        lcd.print(pan_duration);
        delay(5000);
        lcd.clear();
        lcd.print("tilt duration");
        lcd.setCursor(0,1);
        lcd.print(tilt_duration);
        delay(5000);
        step_millis = millis();
        pan_millis = millis();
        tilt_millis = millis();
        pan_pos = pan_min;
        pan.write(pan_pos);
        tilt_pos = tilt_min;
        tilt.write(tilt_min);

        //sets pedestal to user input slide min position
        myStepper->step((step_percent*slide_min), FORWARD, DOUBLE);
        x = 4;
        start_time = millis();
        end_time = millis() + total_time;

    break;

        case 4:
        long remaining = end_time - millis(); //make a couple of run time calculations
        run_dur = millis() - start_time;

        if(millis() - step_millis > step_duration){ //take one step after step duration
          myStepper->step(1, FORWARD, SINGLE);
          cur_step++;
          step_millis = millis();  //resets step duration
          myStepper->release();
        }
        if(millis() - pan_millis > pan_duration){ //same as slide
          pan_pos++;
          pan.writeMicroseconds(pan_pos);
          pan_millis = millis();
        }
        if(millis() - tilt_millis > tilt_duration){//same as slide
          tilt_pos++;
          tilt.writeMicroseconds(tilt_pos);
          tilt_millis = millis();
        }
       if(run_dur > total_time){   //resets to top of user input once total duration runs out
         x = 0;
         input_stage = 0;
         myStepper->step(cur_step, BACKWARD, DOUBLE); //sets motor back to home position
         myStepper->release(); //release motor
        }
      }
    }

body:
You're calling `millis()` a lot in `case 4`. A very simple improvement would be to call it once at the start of `loop()`, storing the result in a variable. Throughout the rest of the function, simply use the value stored in that variable instead of calling `millis()` directly.

I doubt it will solve the problem entirely, but hopefully it will improve it a little.


message:
Sending large structs via nrf24l01 leads to cliping of some structs members

I started with building of the wireless temp/hygro/other values probes. I use 2 arduinos, both with nf24l01+ wireless transceivers, library used is rf24.h (https://github.com/maniacbug/RF24). Basically ping/pong test works for me - so each arduino communicates properly via nrf24l01+.
I added dht22 temperature sensor and just for testing I started with sending structure:

    typedef struct{
      int A; // just counter to see if receiving new data
      float B; // temperature
    } data;

    data payload;
I send it from Arduino1 like this:

    radio.write( &payload, sizeof(payload) );

Other Arduino2 receives the payload:

    radio.read( &payload, sizeof(payload) );

**This works perfectly and I am able to print the counter value as well as the temperature value** on the oled display o Arduino2. **The problem is when I add float C to the struct for sending/receiving hygrometer values.** Then Arduino2 does not receive/display any valid hygro value, but there is just value of 0.00.

I think I know where my problem is - nrf24.h has possibility to set payload size for nrf24l01+ - both Arduinos have to use the same payload size (default is 16, min is 8, max is 32). I use 8 - as this looks to be the most reliable value when using larger distances between Arduinos.
When I tried to set payload size to 32 on both Arduinos:

    radio.setPayloadSize(32);

Then it works and I can receive and display counter, temp, hygro values.
So it looks the nrf24l01+ sends a payload of either 8 or 32 bytes and when sending struct with INT, FLOAT, FLOAT - 8 bytes is not sufficient and 32 bytes of payload is needed. But when I will use many other values, I can reach also limit of 32 bytes payload.

I do not have much skills in C programming and also I do not fully understand how data packets are being transferred between nrf24l01+ modules- maybe I just need to adapt my send/receive code to handle sending of the larger structures. Maybe somebody could give me a hint.

body:
Your payload is too big. You will have to split it to smaller pieces.

NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.


body:
as stated above, it all has to do with the size of your payload. To clarify things, you need to keep in mind how many bytes a certain data type uses/needs:

char: 1 byte
int: 2 bytes
float 4 bytes

(above is based on the Arduino reference, see https://www.arduino.cc/en/Reference/Float )

Thus, if you set payload size to 8 bytes in the NRF24L01 and then try to send a struct with int, float, float you will have 2 + 4 + 4 = 10 bytes, which does not fit in the payload size.


message:
How to identify Arduino Mini Pro 5v vs 3.3v

I have many Arduino Mini Pro, every from different seller.
Few are 3.3v and most 5v.

I had to clean table for Xmas and now I do not have any idea how to identify 3.3v Arduinos.

They do not have any marks. I bought them on ebay.

I know 3.3v has 8mhz clock but only one my arduino has big crystal with 16.000-30.

body: Plug it in and measure the voltage on pin 4 of the MCU.


body: The only difference would be the regulator and crystal (8MHz on 3.3V). As @IgnacioVazquez-Abrams suggest supply power to the "raw" and measure Vcc.


body:
The regulator should be marked K850(5.0V) or K833(3.3V).

A 5 volt part has a 16MHz resonator may be marked with "A1" or "A'N"
A 3.3 volt part has a 8MHz resonator may be marked with "80'0"

As others have indicated, you can apply up to 12V at the RAW pin, and measure the output of the regulator.


body: AVR isn't specified to work at 16MHz at a 3.3V supply; it only can work at this high frequency at 5V supply. So you'll be able to tell them apart from reading the crystal. (It's possible, but unlikely, that you have a 5V version working with an 8MHz crystal. In any case 16MHz is safe for 5V.)


body:
Check the label of the voltage regulator, KB50 for 5V and KB33 for 3.3

![Voltage Regulator][1]

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


body: On my board, the voltage regulator is marked F34V.  On the back is listed "The Simple" and Arduino-Pro-Mini"  I purchased it as a 3.3 v board off e-Bay, and I assume it is.  I have not yet applied vcc to it and measured the output.


body:
The safe way (i tested it).
First connect to 3.3V USB-TTL output first (also 5V Mini can work with 3.3V).
Now prepare this sketch:

    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop() {
      digitalWrite(13, HIGH);
      delay(10000);
      digitalWrite(13, LOW);
      delay(10000);
    }

Choose "Arduino Pro/Mini" with 5v/16MHz board and upload sketch.
If you see that the blinking is correct (10 sec ON/10sec OFF) - you have 5V/16MHz Arduino. Otherwise it will blink at 5 sec intervals instead of 10 sec.


body:
On my board the regulator is marked L0UA which is the code for a 5V regulator type LP2985, L0UB is also 5V.

A 3.3V regulator would be marked L0RA or L0RB.


body:
**Consideration** (go down for the actual solution)

If you have a lot of different China-Arduino-clones, the easiest way will be to just test it. The cloned Arduinos use a lot of different voltage regulators and often you won't even be able to find datasheets for them on Google.

Someone here provided an Arduino sketch which helps you identify the frequency with which the Atmel is running and the comments say "it is the safest method". But why? It is complicated (you need to connect the USB-TTL-converter to each of the different Arduinos and sometimes they have different pinouts, so it's error-prone - you could easily fry your Arduino if you connect the wires to the wrong pins)...

---
**Solution**

I think the safest way is just connecting a voltage in the range of `6V-12V` to the `RAW`-pin and measuring the (regulated) output of the `VCC`-pin.

There is *no reason* why this would kill your Arduino (in case your Arduino isn't broken - which would be good to know anyway; and of course you shouldn't short anything).

I've done a short sketch of how you should connect your Arduino Pro Mini:
[![Connecting the Arduino Pro Mini][1]][1]

* `RAW` <---> `6V-12V`
* `VCC` <---> multimeter (`5V = 5V Arduino`, `3.3V = 3.3V Arduino`)
* One `GND` pins to the `GND` of the power source and one `GND` pins to the `GND` of the multimeter (you can take any of the Arduino pins labeled with `GND`)

Don't worry if your Arduino looks a little bit different, just look for the pin labels. For instance, one of my 5V Arduino Pro Minis looks like this, but also has `RAW`-, `VCC`- and `GND`-labels (just one of the `GND` pins is at a different position, make sure you check your Arduino pin-labels):
[![Different Arduino Pro Mini layout][2]][2]

---
**Alternative**

You don't want to use the method above for some reasons? Then you need sharp eyes and some luck that the following list includes you components (some of these are collected from the other posts, some of them from my Arduinos):

* 3.3V:
   * Voltage regulators: `KB33`, `S20K`, `F34V`, `L0RA`, `L0RB`
   * Oscillators: `80e.`, `80'0`
* 5V:
   * Voltage regulators: `KB50`, `L05`, `L0UA`, `L0UB`
   * Oscillators: `R160JAC6s`, `16.000-30`, `A1`, `A'N`, `A'a`

(no limit or warranty for these details...)

---
**More Suggestions**

Some of the Arduino Pro Minis come with `MHz` and `V` markings on the back. In my case, none of these were checked. Make sure you check them as your new Arduinos arrive, so you won't have any problems identifying them later!
[![Arduino Pro Mini markings][3]][3]

  [1]: https://i.stack.imgur.com/vRb0Y.jpg
  [2]: https://i.stack.imgur.com/gge9q.jpg
  [3]: https://i.stack.imgur.com/ZFngy.jpg


body: Some clones on ebay labeled "the simple" come with 4B2X. They are 3.3v but the maximum voltage is 10v instead of 12v so beware to not burn it out.


message:
How to control 19 RGB LED strips with one arduino?

I need to light up 19 RGB LED strips, which it seems would require 19*3=57 PWM outs and 57 transistors.  The transistors aren't an issue, but of course the 57 PWM's is.  Even if I hacked the digital IO ports to work as PWM, I still wouldn't have enough.

How can I do this more simply?  Is there some kind of device I can get that would let me just pass data to it, perhaps over I2C, and it would control many PWMs? Is there another solution I haven't considered?  Maybe whatever is used to control those 8x8 RGB LED dot matrixes?

Any help would be greatly appreciated.  Thank you!

body:
There are several ways you can do this:

Option 1 - the easy way: You can use a serial-in-parallel out. Google "Arduino SIPO", and you will find examples. You basically send out 8 bits at a time, to a SIPO chip, then "enable" the chip; this changes the 8 "output" pins of the sipo to combinations of high/low as per the 8 bits that went in. You can pwm the "enable" pin. The best part is that each SIPO chip has an overflow - if you put a ninth bit in, you will get the first bit out of the overflow pin, which you can hook up to the input pin of a second SIPO, and so forth.

This option uses about arduino 4 pins, for an unlimited number of output pins.

This also has the advantage that SIPO chips can normally carry much more power than an arduino. Check the spec sheet on the SIPO to see how many milliamps it can carry at once (maximum). An example of a SIP is 74HC595.

Option 2 - Control the common pin for each strip.
Basically, you will be using e.g. 3 pins to select the colour, 19 to select which strip - I think some arduinos have that many pins? To light up red on strip 3, you would put the red pin high (and green & blue low); then you would put the pin for strip 3 low, and all the others high. You would step through each pin you want to light, or you could light them in groups - first red goes high (green/blue low), and all the strips you DONT want red on have their cathode high, and those you DO want red on would have their cathode low. drop red down; then do the same for green and blue. This does mean that you can't light up leds more than 1/3 of the time. This can be combined with the SIPO chip above - it may be easier. This does mean that you need to break out the "common" (cathode, normally to ground).

None of these allow very fine-grained control like pwm - you can't just say "led 3, green, 40%"; you will have to do a lot more work. You may burn all your Arduino time just doing the LEDs; this may or may not be a problem. You have the option of offloading your work onto another AtMega chip, or even an AtTiny; I think I would use an AtTiny and three SIPOs - 4 pins of the AtTiny to control the SIPOs, and 4 for SPI to receive the new settings (e.g. send the AtTiny 57 half-bytes, would give you 12-bit colour depth). You would need to do your own "fake pwm", but you could devote the entire AtTiny to running the light show. The AtTiny is programmed the same way as an Arduino; you would use a USBISP to send the program. Just hook up the power and away you go! An AtTiny will set you back around $2, depending on how many you get and where you get them from.

ADDITIONAL!

What about using something like a TLC5940? I haven't looked at the specs, but I found a reference to Arduino code. 16 Channel, 12 bit duty cycle per channel; you would need 4 of them. Apparently they can be daisy-chained as well. http://playground.arduino.cc/Learning/TLC5940