message:
Reset Arduino Uno R3 from Serial when it freezes (stops looping)?

I have an Uno that loops processing serial commands and reading from a DHT11 sensor. For whatever reason, the device often stops responding. I put an LED on a pin and gave it a blink to see whether the loop is running, and sure enough the loop() stops running (the LED stays ON or OFF, depending on when it froze). I enabled the watchdog at 2 seconds, but it does not reset the device [it still stays frozen, even though wdt_reset() is called at basically the same time as the blinking LED is toggled].

I then tried various combinations of BaudRate=1200 (or 9600), Open(), Close(), DtrEnable=true [on both the Uno and the Mega], yet none of the combinations would make the device reset. The device *will* reset, however, if I re-upload the sketch using the Arduino IDE. I would like to emulate this resetting functionality from my own program's code. Reading on the official site, it sounds like the Baud=1200 reset feature is available only on certain models (not the Uno or Mega).

My code is by no means simple as I am no beginner when it comes to programming. This is the first time, however, that I have had a finicky unit that freezes all the time (say between 10 minutes and 2 hours into running). I merely want to reset the unit from the PC using code, like the Arduino IDE does. On the other hand, if the watchdog worked correctly, that would be fine as well. At the same time, I am not that experienced with electronic circuits, so making a circuit that would "press" the "reset" pin when the LED stops blinking is not something I am quite ready to do. Plus, I do not want to add a bunch more components if the job can be done through code.

On a side note, the Serial connection appears to be fully functional the whole time. The LED on the unit that indicates receiving from the PC continues to function whenever I send data to the device. I can connect and reconnect without any apparent issues. Plus, the Arduino IDE has no problem uploading new sketches and resetting the device. Naturally, no data is received from the device after it freezes (until it gets reset, of course).

**Update 1**: I made a simple sketch (see below) that would run for about 20 seconds and then let the WDT watchdog timeout do its thing. Result:
(a) Running the code on an Arduino-brand Mega 2560, the device simply resets every 20 seconds and keeps blinking;
(b) Running the code on a generic (made in China) Uno R3, at timeout the L light turns on and the device becomes completely unresponsive (not even the reset button or the Arduino IDE can save it); It must be unplugged to reset it.
(c) Running the code on an Arduino-brand Uno R3 works as expected, just like on the Mega 2560.

    #include <avr/wdt.h>
    void setup() {
      wdt_reset();
      wdt_enable(WDTO_2S);
      wdt_reset();
      pinMode(A5, OUTPUT);
      delay(1);
      Serial.begin(125000);
    }
    unsigned int LoopCount = 0;
    bool TestLED = false;
    void loop() {
      if(LoopCount % 300 == 0){
        TestLED = !TestLED;
        digitalWrite(A5, TestLED ? HIGH:LOW);
        if(LoopCount < 20000)
          wdt_reset();
      }
      delayMicroseconds(1000);
      LoopCount++;
    }

Nevertheless, I still would like if someone could provide a solution in terms of resetting a frozen generic Uno from Serial in .NET code -- not the WDT frozen, but the normal frozen (of unknown origin). I may be the one coding, but I'm unfortunately not the one deciding which units are put into production.

**Update 2**: I switched the EasyDriver to its own power source, where the only things in common with the stepper and the Arduino were the ground and the two signal wires. The generic Uno board ended up being even more problematic, going into a new freeze mode (after just a minute or two, pretty reliably) where the L light would blink very quickly. I'm not sure whether it had anything to do with toggling of the DtrEnable property, but I decided to stop messing with the generic board for the time being. The name-brand Uno appeared to freeze occasionally or malfunction as well with the original wiring, but the Watchdog did its thing and reset it straight away every time. Also, I tried toggling the RtsEnable property with the generic board, but it didn't seem to make a difference. The board would become unresponsive and unrevivable, even from the Arduino IDE.

Some more background: The reliability problem only really started to surface when I hooked up the DHT11 temperature sensor, *even though* the freezing would tend to happen only when the stepper motor was running. I have the DHT11 hooked up exactly as advocated by Adafruit, and it tends to read correctly most of the time.

**Update 3**: I was thinking maybe the SainSmart Mega2560 would be different from the no-name generic I was using. After getting one and hooking it up, I have found it to have the exact same problem. The SainSmart CPU crashes between 5 and 15 minutes into running. The serial chip (or module) keeps going as you can still see the serial lights change when you send to it. However, the on-board reset button does nothing, and the Arduino IDE cannot upload to the device or reset it. Only a power cycle can save it.

body:
You can reset the Uno over the serial link by toggling the DTR line. How you do that depends on what platform and language you are using. There is a capacitor between the line and the reset pin, so the toggle must last a minimum ammount of time. 0.5 seconds works.

This is ok for just a quick fix hack, but probably better in the long run to (1) figure out why the code is crashing, and/or (2) figure out why WDT is not working.


sender: user

sender: assistant

body:
Since we don't know the nature of the freeze-up, and the clone-board behaves differently than an Arduino-brand board but we don't know how or why, there's not much more we can offer beyond suggesting you recommend a higher quality board to your management. You surely have reason enough to do so.

The last remaining thing I can think of, and it's kludgey work-around (shame on me) is:

You know the board will come back after a power-cycle. Kludge up a 555 timer circuit that powers-down the board for a second or two, and trigger it from the DTR line. This is really a broken fix for a broken board!

If my management or a client was intent on shipping a product built with these, I'd have to speak up about potential damage to the company's reputation - and possible liability, if a failure could have real consequences someone - and if necessary, write my objections to the next three levels above me. This board should not be shipped in a product.


message:
Can I use 5V 1A Adapter to power Arduino UNO?

I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).

My question is can use any of these to power my Arduino UNO with a barrel connector?

What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.

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

If we look at [technical specifications][2], it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (**never go above 20V**). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.

  [1]: https://i.stack.imgur.com/Ep3D4.jpg
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardUno


message:
ATtiny85 SPI with Timer 0

Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.

What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.

    #include <avr/io.h>

    int main(void){
     DDRB = (1 << DDB2) | (1 << DDB1); // USCK & DO Output
     DDRB &= ~(1 << DDB0); // DI Input
     PORTB |= (1 << DDB0); // Pullup Resistor for DI

     TCCR0A = (1 << WGM01); // Timer 0 in CTC Mode
     OCR0A = 0xFF; // Timer 0 Compare A
     TCCR0B = (1 << CS02) | (1 << CS00); // Prescaler / 1024

     USICR = (1 << USIWM0); // USI 3 Wire Mode
     USICR |= (1 << USICS0); // Timer 0 for USI 4-bit Clock Source

     USIDR = 0x7F; // Why you no go? :c

        USISR |= 0x08; // Set Counter to 8
        USISR = (1 << USIOIF); // Clear Counter Overflow

     while(1);
     return 0;
    }

body: Did you forget to load the counter and clear flags in USISR?


message:
Measuring acceleration in g's

I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial.
I have two questions, which are;

 - Can I measure fractional values, like .8 in acceleration due to gravity?
 - when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?

I am using analog pins and 3.3V power supply from Arduino to power the sensor.

body:
If you read the [datasheet](http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL335.pdf) you can quickly find that the output of the device is 300mV per *g*.  That means:

1. Read the analog value
2. Convert it to millivolts
3. Divide it by 300

The result is the *g* value.  If you do it using floating point then yes, you get fractions of a *g* resolution.

For instance:

    float mv = analogRead(0) / 1023.0 * 5000.0;
    float g = mv / 300.0;

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step.  Divide that by 300 and you get a resolution of 0.01628g

As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down.  It's all in the [datasheet](http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL335.pdf) - it makes for good reading, I suggest you take a look.


message:
How can I use arduino board for AC mains?

I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.

Is it possible to do this?

If yes, how?

body:
The quick and dirty answer is that you need something that will safely handle the mains voltage that you can control with the Arduino (which is running at 5 (or 3.3) volts). There are two issues you need to consider:

1. Safety – keeping the mains voltage separate from the Arduino and the other low voltage components so that nobody gets hurt.

1. Capability of components – avoiding damage to the Arduino and related components due to the mains voltage.

A common way of achieving the second goal is with either a relay or a solid-state component like a triac.

The first goal is often accomplished by using an optocoupler – a device that isolates the low-voltage circuitry from the higher mains voltage by means of an LED and a photo transistor in a common housing.

The circuitry around the relay and optocoupler aren't all that complicated but it isn't trivial either. You might look on e-bay – a search for "arduino relay" will find you lots of modules that will do the job for you.


body:
You can use a relay shield like these:
[Relay Boards - eBay][1]

Be sure to check the amp draw of the relays. Sometimes you need a transistor, but I don't think you should for these shields. Just be careful working with mains voltage.

  [1]: http://www.ebay.com/bhp/arduino-relay-shield


body:
Try the [PowerSwitch Tail II][1].

This is suitable if you are living in the USA (120VAC power).
You will find 240VAC versions as a kit on that web page as well.

  [1]: http://www.powerswitchtail.com/Pages/default.aspx


body:
If you want to switch it on/off, there is a simple solution using a relay and an optocupler (safer option) or transistor. Here is a [schematic][1]:

[![Schematic][2]][2]

but if you want to control intensity of light, then you have to use triac control, which you have explained here: [AC Phase Control][3].

  [1]: http://yourduino.com/p/OptoRelayChannelData-575.jpg
  [2]: https://i.stack.imgur.com/9NFDA.jpg
  [3]: http://playground.arduino.cc/Main/ACPhaseControl


message:
Arduino UNO inconsistent I2C register reading from ArduCam

I have an [Arducam][1] hooked up to an Arduino UNO.  The code I am running looks like this:

    #include <Wire.h>
    #include <ArduCAM.h>
    #include <SPI.h>
    #include "memorysaver.h"

    const int CS = 10;

    ArduCAM myCAM(OV5642, CS);

    void setup() {
      uint8_t vid, pid;

      Wire.begin();
      Serial.begin(115200);
      pinMode(CS, OUTPUT);

      SPI.begin();

      //Check if the camera module type is OV5642
      myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
      myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);

      if ((vid != 0x56) || (pid != 0x42))
        Serial.println("Can't find OV5642 module!");
      else
        Serial.println("OV5642 detected.");

    ...

and the rdSensorReg16_8 function from the library:

    //I2C Write 8bit address, 16bit data
    byte ArduCAM::wrSensorReg8_16(int regID, int regDat)
    {
     Wire.beginTransmission(sensor_addr >> 1);
     Wire.write(regID & 0x00FF);

     Wire.write(regDat >> 8);            // sends data byte, MSB first
       Wire.write(regDat & 0x00FF);

     if(Wire.endTransmission())
     {
      return 0;
     }

     delay(1);
       return(1);
    }

The problem I am experiencing is that sometimes I will receive the "Can't find OV5642 module!" message, and other times everything is fine and I receive "OV5642 detected" (I have the OV5642 module hooked up, so it should always be returning detected).

I have tried using different cables to connect the camera to my UNO.  I have tried swapping out my USB cable.  I have tried using a 12v wall adapter to power the UNO. None of these options permanently solved my problem - I still receive both messages interchangeably.

One thing that *seems* like it is adding consistency is when I change which USB port on my computer the cable is plugged into.  Every time I switch the USB port I am using, it seems like for the first run I'll receive the successful "OV5642 detected" message, but after reseting the Arduino or re-uploading my sketch, I go back to the "Can't find OV5642 module!" message.

Can anyone help me troubleshoot why I am getting inconsistent readings?  Thank you.

  [1]: https://github.com/ArduCAM/Arduino/tree/master/ArduCAM

body:
I would start by adding a short delay before SPI.begin() and verifying that the power drawn does not exceed 500 mA.

The product description describes the power on sequence. [OV5642][1]

  [1]: http://www.uctronics.com/download/cam_module/OV5642DS.pdf


message:
Multiple rgb control plus calculation help

Hi me and a friend is making a computer shelf with leds in the woodwork, were using a special glue for the plexiglass in the shelf which means we're using individual rgb leds, four leds for each window (3 windows) and what I need help with is, amount of voltage, ampere, code and how to connect all this up. I've used 123d.io to sketch something up but I'm struggling with getting proper strength in the leds.

![Sketch](https://puu.sh/lI6IU/0aca425cce.png)

(code https://puu.sh/lI6PC/e214028b07.txt)

Aswell as some of them change colors as the picture here shows:
![On](https://puu.sh/lI7h4/980d8e7a00.png)

I'm very new at these things so I really appreciate all help and advice (and from an earlier post, reason for not using strips is purely based on the method of build, the shelf will not sit correct if the strips were in use)

body:
It's not advised to connect leds in parallel, with only one common resistor. Slight difference in forward voltage of the leds will create big current differences. This will make some leds appear brighter that neighboring leds. It can also damage the brighter led since too much current can flow through them. So you need to add a resistor to each led, and common the other side of these resistors to the transistor.

Second bigger error is that there isn't any resistor between the arduino pin and the base of the transistor. Without it there is nothing limiting the current going into the base, which could fry the arduino pin.


body:
There's a lot to unpack here, this is actually several questions.

First of all, the way your circuit is designed currently, your data pins are connected via the transistors to ground. This means if you set a pin high, or use analogWrite(), the Arduino will pump as much current as it can get, directly into the ground. This can damage the Arduino. Put a resistor between the pin, and the transistor.

The first point is that you are using several LEDs. If you want to control them separately, you will need 3 pins per colour. AnalogWrite() only works on PWM pins - if you look at your Uno, you can see that some of the pins are marked with a ~ (pin 3,45,6,9,10,11) - these are the only ones you can (easily) use. Since there are 6 of them, you could only run 2 LEDs this way. You could either run the project on multiple arduinos (1 Arduino per 2 "windows"), or you can get a chip to do the heavy lifting for you. I am working on a similar project, and am using a TLC5940 - there is a thorough tutorial at http://playground.arduino.cc/Learning/TLC5940 - they also save you from having all the resistors and transistors, and each TLC5940 will run up to 16 LED-pins (3 per LED, so you can run up to 5 "windows"). They are also designed to daisy chain, so if you need more, you can just add another chip; no extra Arduino pins to worry about. 3 of them can run all 12 of your LEDs independently.

The next item to be aware of is that there is a limit to how much power (in Amps, or milliAmps) you can draw from a given power source. Each part will use a certain number of millAmps. The spec sheet for your parts should tell you how many. LEDs are generally around 20mA (per colour), but this varies - check the datasheet. An Arduino uses about 50mA. This means that if all 12 of your LEDs are bright white, you will be drawing 50mA+(20mA * 12 * 3) = 770mA.

How does this affect you? Well, if your project draws less than the power source can provide, you're golden! You can't provide "too much current" to a component - it will draw what it needs. When you draw more than the supply can supply, you get one of two results. If it runs on the mains, it will overheat, and eventually either burn out, or catch fire (there are exceptions to this, but you'd better be sure of your facts before risking it!). How long this takes, depends on how much current you are drawing, and how much margin there is on the power supply. In the case of a battery, the battery will drop in voltage, and will also heat up (but is much less likely to catch fire). I suspect this is happening here. If you have a multimeter, you can hook up your circuit to batteries, and then measure the voltage between + and - on the batteries.

P.S - +1 to @Gerben - you need one resistor per LED leg (except common). If you use the TLC5940, you would need 3 TLC5940s; as I said before, you can daisy-chain them. This does, however, mean that you can control each LED individually.


message:
Interfacing Arduino with matplotlib animation

I've also asked this question over on stack exchange so I'll link the actual question [here][1].

The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use `flush()`. I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.

Edit: Here's a snippet of the code.

    void loop() {
      // put your main code here, to run repeatedly:
      val1 = analogRead(0);
      val2 = analogRead(1);
      Serial.print(val1);
      Serial.print(" ");
      Serial.print(val2);
      Serial.print("\n");
      //Serial.flush();
      delay(50);
    }

  [1]: https://stackoverflow.com/questions/34074697/interfacing-matplotlib-with-arduino

body:
On the Arduino side, `flush` simply waits until the last byte has been fully transmitted.  It says nothing about how quickly it is being read by the PC.

The general problem you are having is called "flow control".  It has been solved with many different techniques, like "handshaking".  For example, the PC could send a character when it has received the last byte of a data set (a line, as returned by `readline`):

    line = self.ser.readline()
    self.ser.write("!"); // Tell Arduino line was received
    line = line.split()

While the PC proceeds to parse the line, the Arduino will eventually receive the handshake character:

    void loop()
    {
      // Send a line
      Serial.println( ... );

      // Wait for handshake character
      bool gotHandshake;
      do {
        while (!Serial.available())
          ; // wait for chars
        char c = Serial.read();
        gotHandshake = (c == '!');
      } while (!gotHandshake);
    }

Then the Arduino can proceed to send the next data set (i.e., a line).  The OS on the PC will buffer characters from the Arduino until the python program receives them with `readline` and sends another handshake character.  No `delay` required.


message:
Read gyro output values with other programming languages

I have a large quantity of gyro values and I read them through the Arduino serial monitor. I'd like to know how I can use these values in other programming languages (such as C/C++/Java) after the values are read. Are there particular  libraries for the Arduino that could help me in this way?

body: If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.


body:
Yes, of course you can.

In C/C++ there are different libraries depending on your operating system - that is if you even really need a library to help you at all (in Linux you certainly don't - you just use standard system calls - open, read, etc).

In Java there are a few different ones.  RXTX is a common (though not very good) one.  Personally I ise JSSC(Java Simple Serial Connector) since it contains the JNI files for all the main platforms - you don't have to get the right separate library packages for your specific OS like you do with RXTX.

Then of course there's things like PySerial for Python, Device::SerialPort for Perl, and whatever nonsense Microsoft have created for C# and their .NET stuff.

So in general: pick a language you are comfortable with, then ask Google how to use the serial port in it.


message:
One LED being constant and another blinking

I have just started my first project. I got through with 2 periodically blinking LEDs. Now I want one LED (blue) to be lit constantly and the other (red) to be blinking as before. Can anyone help me with this?

This is my code for blinking LEDs.

    int red_led = 4;
    int blue_led = 3;

    void setup() {

      pinMode(red_led, OUTPUT);

      pinMode(blue_led, OUTPUT);

    }

    void loop() {

      digitalWrite(blue_led, LOW);

      digitalWrite(red_led, HIGH);

      delay(1000);

      digitalWrite(blue_led, HIGH);

      digitalWrite(red_led, LOW);

      delay(1000);

     }

body:
The wonderful thing about the Arduino is that it hides a lot of the programming "noise" and lets you concentrate on the code that is actually doing the work. Part of the joy of programming is starting to "own" the code and being able to make it do what you want.

The answer here isn't too hard, and I'm sure that many could answer your question – but I think you might enjoy the experience more (and you would earn more respect) if you make a stab at it yourself first. Or if you already have, tell us what you've tried and what happened when you tried it. That will help us help you to see not only the steps necessary, but the concepts that will enable you to branch off on your own.

Do you know what is causing the LEDs to blink in your current code?


body:
Remember that the setup() function runs once, and then the loop() function runs forever.  So to keep the blue LED light, simply turn it on, but never off.  The code for the red LED remains unchanged.

    const int red_led  = 4;
    const int blue_led = 3;

    void setup()
    {
        pinMode(red_led, OUTPUT);
        pinMode(blue_led, OUTPUT);

        digitalWrite(blue_led, HIGH);  // LED On
    }

    void loop()
    {
        digitalWrite(red_led, HIGH);  // LED On
        delay(1000);
        digitalWrite(red_led, LOW);   // LED Off
        delay(1000);
    }


message:
What is better: one sprintf() or multiple strcat() and itoa()?

I was creating Arduino function which sends two `int` and additional `char`s between them and at the beginning and end of `char` array - then print that array to the serial port in almost real time. (For example "X50Y100T".)

I don't want to use `String` object in Arduino and I found two possible solutions:

 - Using `sprintf()`:

        char sendBuffer[16];
        void dataSend(int first, int second) {
          sprintf(sendBuffer, "X%dY%dT", first, second);
          Serial.println(sendBuffer);
        };

 - Or something like this:

        char sendBuffer[16];
        void dataSend(int first, int second){
          char convert[6];
          sendBuffer[0] = 'X';

          itoa(first, convert, 10);
          strcat(sendBuffer, convert);

          sendBuffer[strlen(sendBuffer)] = 'Y';

          itoa(second, convert, 10);
          strcat(sendBuffer, convert);

          sendBuffer[strlen(sendBuffer)] = 'T';

          Serial.println(sendBuffer);
          memset(sendBuffer,0,sizeof(sendBuffer));
        };

My question is - which one is better from technical point of view?

The `sprintf()` looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of `sprintf()`? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of `char` array?

body:
As a general principle code that is easy to read and modify is "better" – the problem here is that there are many "betters" to consider:

 - Readability
 - Maintainability
 - Space efficiency
 - Time efficiency

There is no universal answer to which of those is the most important. My personal bias is to start with code that is easy to read and obvious in its function. Then if time or space are an issue to start looking for ways to improve.

In your code, you could also do something like this:

      itoa(first, sendBuffer[1], 10);

Which would save you a function call and perhaps some space.

Also keep in mind that the cost of `sprintf()` in terms of space may get amortized over many uses, so it might not be as bad as it initially seems.


body:
Why do you feel you need to use either method? Neither are needed. Just print the individual parts:

    Serial.print('X');
    Serial.print(first);
    Serial.print('Y');
    Serial.print(second);
    Serial.println('T');

No intermediate buffers, just sending the data direct out to the UART.


body:
Here's a method that for some reason uses slightly fewer bytes of flash memory than Majenko's does, while producing the same output:

Add `#include <Streaming.h>` at the beginning of the program, and replace the five statements shown in Majenko's answer with the following line:

    Serial << 'X' << first << 'Y' << second << 'T' << endl;

That is, use the `Streaming.h` [contributed library](https://www.arduino.cc/en/Reference/Libraries), which adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size.  You can install it via [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

When the `#if`-delimited sections in the program shown below are selected individually (by changing two of the three 01's at a time to 0's), I got the following compiled-code and RAM figures, running the program on a Nano, where all three ways appear to give the same output:

          Bytes  Bytes
    Alt.  Flash   Ram    Note
     1    2,204   182    Five Serial.print stmts
     2    3,384   190    Using snprintf()
     3    2,176   182    One Streaming stmt

I don't know whether this slight decrease (from 2204 to 2176 bytes of flash) is replicable, but the method probably is worth trying in your situation.

The program:

    #include <Streaming.h>
    void setup() {
      Serial.begin(115200);
    }
    void loop() {
      int first=50, second=100;
      //enum { first=50, second=100};
    #if 01
      Serial.print('X');
      Serial.print(first);
      Serial.print('Y');
      Serial.print(second);
      Serial.println('T');
    #endif
    #if 01
      char sendBuffer[16];
      snprintf(sendBuffer, sizeof sendBuffer, "X%dY%dT", first, second);
      Serial.println(sendBuffer);
    #endif
    #if 01
      Serial << 'X' << first << 'Y' << second << 'T' << endl;
    #endif
    }

Note, I used `snprintf()` rather than `sprintf()` because it's easier to avoid buffer overruns with `snprintf()` than with `sprintf()`.


body:
The sprintf() function has a memory cost because of the library import at compile time.  But it only costs that once, no matter how many more times you use it.  Unless you're running out of space, memory used is not a big deal.  There's no point keeping some memory unused on an Arduino.

I think it's better to use sprintf() because:

 - sprintf() produces code that is more readable, since the final output string can be easily visualised - obviously with only place holders for the variable parts.
 - Making minor changes to the output is quicker, since there's not lines of output generator functions to re-organise.
 - You end up with less code.  Less code is is easier to debug and maintain.

I would however, encourage you to use snprintf().  This function differs from sprintf() by taking the maximum buffer size as an argument.  This will help prevent problems with buffer-overruns (i.e.: accidentally putting more data into a string than in can hold)

Sprintf on Arduino does not include support for floating point numbers though.  This is quite a drawback.  One needs to use additionally use dtostrf().

The real takeaway point is this:  Only optimise your program when you need to.  [Donald Knuth][1] said: "Premature Optimisation is the root of all evil".

  [1]: https://en.wikipedia.org/wiki/Donald_Knuth


message:
Flash Arduino Due via UART

I would like to write code in Arduino language, compile it in the Arduino IDE, grab the resulting binary code, and flash it to the Due via the TX/RX UART pins, bypassing both the USB Programming Port and Atmel16U2 chip. Before the UART flash, I am manually toggling the Erase and Reset pins on the Due to initiate a hard reset of the SAM3X chip, and SAM-BA now waits for the code. I would like to know: can I directly grab the binary code compiled by the Arduino IDE and give it to SAM3X via UART or is there extra code baked into that binary by the Arduino compiler that would cause this method to fail?

body:
It depends
==========
This may not have been the answer the question was originally asked, but now it appears to be: it depends on which revision of the Due you have.

The V03 [schematics][1] on the website show a 74LVC1G125DCK part designated IC10 that is being used to translate the 5V TXD signal from the ATMega16u2 (being used as a serial transceiver) to the 3.3V logic needed for the ATSAM3X8.  As drawn the TXD line is connected to the buffer/level converter input but it is also connected to its active-low output-enable line.  In effect, they're not just using it to convert logic levels, they are also converting the signal to a kind of open collector signal.  Looking at the ATSAM3X8 datasheet shows that, yes, there is an internal pullup in the pin receiving the signal.

**If your Due is of this design,** then yes, you can program the chip by attaching a USB->logic-level-serial adapter to D0 and D1 (USART) pins and program using the SAM-BA protocol. You need to make sure you are not sending over the on-board serial transceiver while this is happening so as to not have it wired-ORing its data with your adapter. The ATMega16U2 has code in it that controls the ATSAM3X8's erase pin, as well as reset pin, by request of the PC via serial-over-USB's DTR and RTS.  Since the erase signal is not routed to outside of the Due (on its headers), you would need to use the erase button, barring some modification to the board.

**However, not all Due are of this design.** Some DUE boards have the output-enable of 74LVC1G125DCK hard-wired active rather than connected to the transceiver TXD; so on these designs it does **not** behave as open-collector, and the ATMega16u2 serial transceiver is actively driving the line when idle.  This destroys the ability to program the board over UART via pins D0 and D1.  It does however make cleaner rising edges.  Without modifying the board, no, you can't do it with this design.

Identification
--------------

So far as I can tell, whether or not your ATMega16U2->ATSAM3X8 connection is open collector/UART-programming-friendly follows the location of the buffer part.  The chip is an SC70 package, a small 5-pin thing that looks a bit like SOT23-5.  If it is located off the ATMega16U2 itself it seems you have a open-collector configuration, again so far as I've been able to tell.  If it is located next to D0, between D0 and the "COMMUNICATION" header, then you have one that drives-high.

If you have a scope, you can put it on D0 and watch the edges generated when you send traffic from the PC over the ATMega16U2 at higher baud rates.  You will either see characteristic open-collector rising edges or you won't and that will answer the question.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf


message:
Arduino Uno data logger shield recording nonsense time

I'm using an Arduino Uno with the Adafruit Data Logger Shield powered by a Voltaic 5V 2A battery pack. When writing to an SD card, the time stamp never changes (always reports the same now.unixtime). However, when powered from a laptop, the time stamp is correct and everything seems to be working.

The input voltage from the battery is confirmed to be just over 5V and not substantially lower the the laptop usb port.

Has anyone seen this before? Any ideas?

body:
Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.

You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.


body: If you are putting just over 5V into the Vin, it goes through the on-board regulator and needs a 7v minimum per https://www.arduino.cc/en/Main/ArduinoBoardUno  The Adafruit Data Logger Shield doc at https://learn.adafruit.com/downloads/pdf/adafruit-data-logger-shield.pdf shows a 9V battery pack.


body:
The problem was indeed a question of voltage.

I was using the battery to supply 5 volts to the DC power port, which as suggested by the comments needs 7 volts or more. The problem is fixed by using the battery, which supplies a stable 5V, to give power to the USB port (or, presumably the 5V pin, though that is not available in my application).


message:
Can I work with larger numbers than an unsigned long long in Arduino?

I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

body:
There are many ways to use numbers bigger than an `unsigned long` on Arduino. The right one depends on the application.

**Floats and Doubles**
`float`s and `double`s types on Arduino can hold exact integers up  `2^53`. That is a very large number. They are built into the Arduino compiler.

**uint64_t**
The `uint64_t` type can hold exact integers up to `2^64`. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.

**BigNumber (or bc)**
The `BigNumber` type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...

https://github.com/nickgammon/BigNumber

Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find `BigNumber` compatible functions for things like printing and serializing.


message:
Control the ethernet shield with Chrome and Safari

I am trying to communicate with ethernet shield. When I enter the IP in Chrome the job is done (simply an LED turns off and on with IP/$1 and IP/$2) but with Safari it is not. Any idea what the difference is?

body: I had the same problem. I forgot to complete the `client.println` with a newline (`\n`).


message:
How to make 2 LEDs flash in a 5/4 Polyrhythm?

Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.

<!-- language: c -->

    //Making a 5/4 Polyrhythm with 2 LEDs
    const int LED13 = 13;
    const int LED7 = 7;
    int i = 5;

    void setup() {
       pinMode(LED13, OUTPUT);
       pinMode(LED7, OUTPUT);
    }

    void loop() {

      for(i=0; i<5; i++)
      {
         digitalWrite (LED13, HIGH);
         delay(500);
         digitalWrite (LED13, LOW);
         delay(800);
      }

      for(i=0; i<4; i++)
      {
         digitalWrite (LED7, HIGH);
         delay(500);
         digitalWrite (LED7, LOW);
         delay(1000);
      }
   }

body:
See https://arduino.stackexchange.com/a/17929/6628 with code like:

    const int onTime = 500;
    const int measureTime = (int) (60*1000/10);  // 10 BPM, or 1500*4ms/measure
    const int off4 = measureTime/4 - onTime;  // take care these don't go negative
    const int off5 = measureTime/5 - onTime;  //
    unsigned long next5;
    unsigned long next4;

    ...
    loop(){
      unsigned long now;
      now=millis();
      ...
      if(next5 < now) {
         if digitalRead(LED13) { next5 = now+off5;   digitalWrite(LED13,LOW );}
         else                  { next5 = now+onTime; digitalWrite(LED13,HIGH);}
      }
      if(next4 < now) {
         if digitalRead(LED7)  { next4 = now+off4;    digitalWrite(LED7,LOW );}
         else                  { next4 = now+onTime ; digitalWrite(LED7,HIGH);}
      }

    }


body:
I generally calculate whether the led must be on or off, based on the current time.

    //Making a 5/4 Polyrythm with 2 LEDs
    const int LED13 = 13;
    const int LED7 = 7;
    int i = 5;

    void setup() {
       pinMode(LED13, OUTPUT);
       pinMode(LED7, OUTPUT);
    }

    void loop() {
        // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
        // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
        bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
        bool led7on  = (millis()/750)%2!=0;
        digitalWrite (LED13, led13on);
        digitalWrite (LED7, led7on);
        delay(10);
    }


message:
Interleave Assembly and Source for avr-objdump

Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)

[Original Makefile][1]

Here's my current Makefile:

    PREFIX=avr-
    CC=${PREFIX}gcc
    OBJCOPY=${PREFIX}objcopy

    BIN=knightrider
    MCU=attiny85
    OBJS=../src/tinySPI.o src/knightrider.o

    PROG?=atmelice_isp
    PORT?=usb

    CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
    LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

    ${BIN}.hex: ${BIN}.elf
     @mkdir -p bin
     ${OBJCOPY} -O ihex -R .eeprom build/$< bin/$@

    ${BIN}.elf: ${OBJS}
     @mkdir -p build
     ${CC} ${LDFLAGS} -o build/$@ $?

    install: ${BIN}.hex
     avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq

    clean:
     rm -f build/*
     rm -f bin/*

    fuses:
     avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq

What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?

  [1]: https://github.com/AshlynBlack/tinySPI/blob/c0748ee5fe1d5b85813ac7b4628bb84014d4a0d4/examples/Makefile

body:
First make sure you add `-g` to all your compilation commands.

Then you can run `avr-objdump -S build/spi.elf` (for instance).

Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.

Here is a makefile I use:

    PREFIX=avr-
    CC=${PREFIX}gcc
    CXX=${PREFIX}g++
    LD=${PREFIX}ld
    AS=${PREFIX}as
    OBJCOPY=${PREFIX}objcopy
    OBJDUMP=${PREFIX}objdump

    BIN=blink
    MCU=atmega328p
    OBJS=blink.o

    CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
    CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
    LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

    ${BIN}.hex: ${BIN}.elf
     ${OBJCOPY} -O ihex -R .eeprom $< $@

    ${BIN}.elf: ${OBJS}
     ${CC} ${LDFLAGS} -o $@ $?
     ${OBJDUMP} -S $@ > ${BIN}.dis

    install: ${BIN}.hex
     avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
     -qq

    clean:
     rm -f *.o *.elf *.hex

    fuses:
     avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
    fuse:w:0xd6:m -U efuse:w:0x05:m -qq


message:
Array of Strings and Callbacks

I am trying to create an array of structs that contain pairs of Strings and Callbacks the problem I am having is assigning the callback function. I have the following code:

    #define UI_ROUTINE_ITEMS 10

    struct MenuItem{
     String label;
     typedef void (*callback)();
    };

    class MenuSystem{
       MenuItem routineMenu[UI_ROUTINE_ITEMS];

       MenuSystem(){
          routineMenu[0] = {"Test", &Test::TestCallback};
       }
    }

    class Test{
       void TestCallback(){
          Serial.println("Callback called");
       }
    }

When I try to compile this I get:

    error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

I know this is a Syntax issue I just can not figure out how this should be done. I have looked at several examples but I can't figure out how to do this with Classes without using free/malloc, what am I doing wrong?

----------
**EDIT**

----------

I finally got this working, the problem was that the function that I was trying to call was not static and the declaration in the structure was not quite right. Below is the corrected example:

    #define UI_ROUTINE_ITEMS 10

    #include <Arduino.h>

    struct MenuItem{
        String label;
        void (*callback)(void);
    };

    class MenuSystem{
       MenuItem routineMenu[UI_ROUTINE_ITEMS];

       MenuSystem(){
          routineMenu[0] = {"Test", &Test::TestCallback};
       }
    }

    class Test{
       public static void TestCallback(){
          Serial.println("Callback called");
       }
    }

body:
Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.

You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.

There is a [Menu][1] system in Cosa. Please see the [example sketch][2]. This implementation follows the [MVC][3] design pattern.

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Menu/Menu.hh
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/LCD/CosaLCDmenu/CosaLCDmenu.ino
  [3]: https://en.wikipedia.org/wiki/Model–view–controller


body:
Your system works in pure C too:

    typedef struct _MenuItem
    {
        const char *label; // or String if you like
        void (*callback)();
    } MenuItem;

    void testCallback()
    {
        Serial.println("testCallback() Called");
    }

    MenuItem menu_system[10];
    void setup()
    {
        menu_system[0].label    = "Test";
        menu_system[0].callback = testCallback;

        ... # more menu definitions with callbacks
    }

    void loop()
    {
        unsigned int user_menu_selection;

        ... # some menu code, user selection in <user_menu_selection>

        menu_system[user_menu_selection].callback();  // TODO: error checking
    }

It might be a good idea to store any static Menu Strings into [PROGMEM][1].

  [1]: https://www.arduino.cc/en/Reference/PROGMEM


body:
A pointer to a member instance function **is** possible:

    void (Some_class::*Some_fnc_ptr)();

And in order to call different classes than just "Test" you'd have to play some games with templates and probably virtual functions.  It would get pretty involved, but doable.


body:
I know that you've resolved your dilemma, but I just wanted to show you a trick: personally, I _**hate**_ the pointer-to-function mechanism that everyone uses, when there's a perfectly good alternative.

Here's a function that takes an `int` and returns a `char`:

    char SomeFn(int i);

Here's a `typedef` describing that function as a type:

    typedef char Fn(int i);

Looks pretty similar, huh? What's the point? Now that you've got a type, you can use that instead:

    void SetCallback(Fn *fn);

`SetCallback` takes as a parameter a pointer to a function of type `Fn`. The `*` is necessary, and (to me) makes more sense than trying to barrel the pointer-ness inside the type itself - which is what leads to the parenthesis overload. You can call it like this:

    SetCallback(&SomeFn);

What could be easier? If `SomeFn` was a `static` member of a class, you could just as easily use that:

    SetCallback(&Class::SomeFn);


message:
Trinket: Battery + USB at the same time?

Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?

I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

body:
From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.

If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.


message:
Is there any way I can turn off the 5V pin?

I'm trying to find a way I can toggle the 5V pin to turn on/off. I want the voltage to pass to another wire at a certain point. It should be off and then when something happens, the 5V should turn on.

How can I do this?

body:
There isn't programmatic control of the 5V pin, it is hard wired to the USB or the output of the Vin Voltage regulator.

You might try something from https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b to control the low side of the external device.  If you need high-side control, maybe an opto-isolator would be a good solution.


body: You don't really want to do that. The 5V pin is on the power bus of your Arduino board. If it *were* possible to turn it off, the entire Arduino would shut down.


body:
If I'm understanding you correctly, you want a 5 V output that is under programatic control. Do you know how much power you want to pull from the pin?

If the demand is fairly low, you could use one of the digital pins directly – they will supply about 40 mA on an "official" Arduino.

If you need more power, then you could use the pin to switch an external device such as a transistor or a relay.


body:
For energy-efficient switching (along with relatively high-current capability), I recommend using a *Darlington* transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call  pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:
[![enter image description here][1]][1]

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.

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


message:
max current while using a shift register

In arduino's official page about ShiftOut https://www.arduino.cc/en/Tutorial/ShiftOut, a drawing with two 74HC595 powered by the arduino board, is displayed.

Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.

So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?

Thank you

body:
0.20A is *not* the maximum current for an Arduino device.  0.20A is the maximum current for *the chip that is on the Arduino*.  Thus it is only relevant to devices that are *directly* connected to the Arduino's IO pins (that connect direct to the chip).

The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board.  Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.


message:
Trinket Pro 5V red light flashing when battery attached

I am using [Trinket Pro 5V][1] to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position.
It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.

Is the power source not sufficient - 9V?

Has anyone faced a similar problem?

  [1]: http://www.adafruit.com/product/2000

body:
Please consider reading the ["https://learn.adafruit.com/trinket-gemma-servo-control/wiring"][1] tutorial.

It says

> It is suggested you use an external wall or battery supply and not
> power the servo via the regulator. servos can draw up to 500mA and the
> Trinket regulator can only source 150 milliamps (USB power generally
> 500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, use a better power source.

Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".

The ["Adafruit 16-Channel Servo Driver with Arduino"][2] tutorial says:

> Good power choices are:
>
> * [5v 2A switching power supply][3]
> * [5v 10A switching power supply][4]
> * [4xAA Battery Holder][5] - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
> * 4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other [Battery holders][7] that hold lots of AA batteries in a convenient package.

Related:
["How to get high current from 9 volt batteries"][8]
and
["What is the max current I could draw from a 9V battery?"][9].

  [1]: http://learn.adafruit.com/trinket-gemma-servo-control/wiring
  [2]: http://learn.adafruit.com/16-channel-pwm-servo-driver/hooking-it-up
  [3]: http://www.adafruit.com/products/276
  [4]: http://www.adafruit.com/products/658
  [5]: http://www.adafruit.com/products/830
  [6]: http://www.adafruit.com/products/449
  [7]: http://www.adafruit.com/category/135
  [8]: https://electronics.stackexchange.com/questions/73169/how-to-get-high-current-from-9-volt-batteries
  [9]: http://forum.arduino.cc/index.php?topic=132106.0


message:
Weird stepper motor behaviour on RAMPS in arduino

Following this tutorial:

http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS

I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:

<!-- language: c -->

     //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

     #define DEFAULT_AXIS_STEPS_PER_UNIT {215.12,215.12,8034.69,196.52}

     // #define DEFAULT_MAX_FEEDRATE          {300, 300, 5, 25}    // (mm/sec)

     #define DEFAULT_MAX_FEEDRATE {100, 100, 2, 25}

     // #define DEFAULT_MAX_ACCELERATION      {3000,3000,100,10000}    // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot.

     #define DEFAULT_MAX_ACCELERATION {200,200,50,5000}

     #define DEFAULT_ACCELERATION          100    // X, Y, Z and E acceleration in mm/s^2 for printing moves

     #define DEFAULT_RETRACT_ACCELERATION  100    // E acceleration in mm/s^2 for retracts

     #define DEFAULT_TRAVEL_ACCELERATION   100    // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves

I put a [video at vid.me](https://vid.me/vd6Q) (hopefully with sound) showing stepper behaviour when I press +1mm,-1mm,-1mm,-1mm,-1mm,-1mm,-1mm,+1mm,+1mm,+1mm,+1mm  on Pronterface software.

body:
The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.

Recalculate your steps/mm values and slow down the feed rate to get something reliable.

For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.

Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:

    #define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


message:
May I use both USB-serial and tx/rx pins at the same time?

I am building a CNC machine based on GRBL code on a uno. I also have found a script to read data on a N64 controller. I know there is not enough pins available to do both codes running on the same arduino, so I was wondering if I could have my GRBL arduino connected to a computer thru USB, and at the same time, have a second arduino reading data from the n64 joystick, create Gcode accordingly, and feed that Gcode to the GRBL arduino through the tx/rx pins of each of them.
I guess I'll have to put a on-off switch on the tx/rx wife to avoid "noise" when I actually send Gcode to the GRBL arduino from the computer.

Does this all make sense?

body:
The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the [SoftwareSerial][1] library or the [Wire Library][2] or investing in a better board with more than one serial port.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: https://www.arduino.cc/en/Reference/Wire


body:
Low impedance circuits connected to the TX/RX pins would cause distortion in the serial signal and would interfere with communication.

A switch would help here. Alternately, you could use a Mega 2560 with more IOs, or if you are breadboarding it, use a 1284p chip.

You could also use SoftwareSerial to communicate with the other Arduino on another set of pins.


message:
How to interface with generic IR RGB LED controller?

I want to hook up an arduino to one of those generic RGB LED controllers, you see them everywhere, they are these little white boxes with power input and RGB strip plug and an IR LED lead. Is there a way to take to the IR + and - and connect them the arduino? Then spoof an IR signal to control the control module? I want to do it this way because I already own both the arduino and control module and that module handles the power for the LEDs. All I am hoping I have to do is send the controller the hex value for the IR command through the the arduino in order to control it. Here's a link to what the module looks like and the remote it comes

https://www.amazon.com/dp/B00ASHQQKI/ref=cm_sw_r_cp_awd_htMywb1W85962

body:
The [IRRemote Library][1] is a good starting point, but you'll probably need a RAW mode.   I've got a couple IR controllers from different companies, and they use different codes for the same things.

  [1]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html


message:
Migrating from ATMega2560 to ARM based -- Teensy vs Due?

I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.

Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.

I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.

So my QUESTION is:
Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.

Any other considerations/suggestions/advice will be appreciated.

Thank you.

body:
If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.

That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.

There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.


message:
Using more than 8 digits using the sevseg library

I am using [sevseg][1] and i can't get more than 8 digits to work.  I really need 15.  Does somebody know what I can do to get this?

Shown is the original example

This is using Gabriel Staples example in the sevseg library:

    #include <SevSeg.h>

    SevSeg sevseg; //Instantiate a seven segment controller object

    void setup()
    {
      byte numDigits = 4; //<<---I am wanting 15, but doesn't work after 8------
      byte digitPins[] = {2, 3, 4, 5}; //Digits: 1,2,3,4 <--put one resistor (ex: 220 Ohms, or 330 Ohms, etc, on each digit pin)
      byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

      sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    // Note: 100 brightness simply corresponds to a delay of 2000us after lighting each segment. A brightness of 0
    // is a delay of 1us; it doesn't really affect brightness as much as it affects update rate (frequency).
    // Therefore, for a 4-digit 7-segment + pd, COMMON_ANODE display, the max update rate for a "brightness" of 100 is 1/(2000us*8) = 62.5Hz.
    // I am choosing a "brightness" of 10 because it increases the max update rate to approx. 1/(200us*8) = 625Hz.
    // This is preferable, as it decreases aliasing when recording the display with a video camera....I think.
      sevseg.setBrightness(10);
    }

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= 4; //rollover back to 0 once variable gets to 4; To anyone wondering: the % is called the "modulo" operator; see here for explanation & example: https://www.arduino.cc/en/Reference/Modulo

      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

[1]: https://github.com/DeanIsMe/SevSeg

Using the following code, I can't get the 3rd set of 5 numbers to display.  I have changed the sevseg.h file to 15, but that shouldn't matter:

    #include <SevSeg.h>

    SevSeg sevseg1;//Instantiate a seven segment controller object 1
    SevSeg sevseg2;//Instantiate a seven segment controller object 2
    SevSeg sevseg3;//Instantiate a seven segment controller object 3

    void setup()
    {

      Serial.begin(9600);

    byte segmentPins[] = {22, 23, 24, 25, 26, 27, 28, 34}; //Segments:     A,B,C,D,E,F,G,Period

      byte digitPins1[] = {29, 30, 31, 32, 33};
      sevseg1.begin(COMMON_CATHODE, sizeof(digitPins1), digitPins1,  segmentPins);
      sevseg1.setBrightness(10);

      byte digitPins2[] = {35, 36, 37, 38, 39};
      sevseg2.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins2, segmentPins);
      sevseg2.setBrightness(10);

      byte digitPins3[] = {40, 41, 42, 43, 44};
      sevseg3.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins3, segmentPins);
      sevseg3.setBrightness(10);

    }

    void loop()
    {

    static byte decPlace = 2;

      sevseg1.setNumber( 12345, decPlace );
      sevseg2.setNumber( 12345, decPlace );
      sevseg3.setNumber( 12345, decPlace );

      sevseg1.refreshDisplay();
      sevseg2.refreshDisplay();
      sevseg2.refreshDisplay();
    }

body:
You can change the pre-defined maximum number of digits at the top of the `SevSeg.h` header file to as many as 10, if you use `long` or `unsigned long` when you call `setNumber`.  It is defined [here](https://github.com/DeanIsMe/SevSeg/blob/master/SevSeg.h#L27), on line 27:

    #define MAXNUMDIGITS 8 //Increase this number to support larger displays

This the version referenced from the [Arduino Playground SevSeg](http://playground.arduino.cc/Main/SevenSegmentLibrary).  Be sure to use the same number in your modulo, too:

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= 10; //rollover back to 0 once variable gets to 10

`decPlaces` is mostly useful for floating-point numbers: it specifies how many digits after the decimal point should be displayed.  For integer values, it specifies how many leading zeroes will be displayed.

However (as you discovered), you cannot call `setNumber` with anything larger than a `long`, so you are limited to 10 or fewer digits for `MAXNUMDIGITS`.  (There is no byte overflow -- it's just limited to the number of decimal digits in 232-1.)  This is a limit of one SevSeg instance.  You could have *two* instances of `SevSeg` like this:

    #include <SevSeg.h>
    SevSeg sevseg1;
    SevSeg sevseg2;

    void setup()
    {
      byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

      byte digitPins1[] = {2, 3, 4, 5, 22, 23, 24};
      sevseg1.begin(COMMON_ANODE, sizeof(digitPins1), digitPins1, segmentPins);
      sevseg1.setBrightness(10);

      byte digitPins2[] = {14,15,16,17,18,19,20,21};
      sevseg2.begin(COMMON_ANODE, sizeof(digitPins2), digitPins2, segmentPins);
      sevseg2.setBrightness(10);

      sevseg1.setNumber(  7654321UL, 7 );
      sevseg2.setNumber( 87654321UL, 8 );
    }

    void loop()
    {
      sevseg1.refreshDisplay();
      sevseg2.refreshDisplay();
    }

The first instance handles 7 digits, and the second instances handles 8 digits.  Note the use of "UL" to force and `unsigned long` call.

## Update 11-DEC-2015

>Using the following code, I can't get the 3rd set of 5 numbers to display. I have changed the sevseg.h file to 15, but that shouldn't matter:

First, the `MAXNUMDIGITS` is the maximum *per instance*, so you could set it to **5** to save some precious RAM.

Second, you have a copy and paste error:

    sevseg1.refreshDisplay();
    sevseg2.refreshDisplay();
    sevseg2.refreshDisplay();   <--  Oopsies!  :)

Third, I assume the `setNumber` calls are placeholders for what you're really going to use.  Since they always set the same value, they could be in `setup`.  In your final program, there must be some input that will be used to calculate a number to display with `setNumber`.


body:
Looking at the [sevseg README file on GitHub][1] I find this:

> If you wish to use more than 8 digits, increase MAXNUMDIGITS in SevSeg.h.

Have you done that? Seems like that might be the problem.

As @slash-dev said, be sure to also modify the `loop()` code as well:

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= numDigits;

I think it makes more sense to use `numDigits` rather than a hard coded constant that you have to remember to change whenever you change the number of digits in your display. It would be worth checking the code for any other hard coded constants. If space is an issue, it might be worth checking to see if using a `#define` results in smaller code than using a variable – in any case do something to avoid needing to understand what "magic numbers" are doing. This is especially important when the same numeric value (e.g., 4) is being used for multiple reasons. Then it gets hard if you need to change the value as you have to understand the purpose behind each use.

[1]: https://github.com/DeanIsMe/SevSeg


message:
Erroneous sensor reading while connecting extra load

I'm making a **speedometer using arduino**. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also **using the same battery to use a horn**. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an **erroneous reading.** The only common thing between the arduino and the horn is the battery supply.

body:
If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.

It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.

To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.

Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.

To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.

A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.


message:
Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?

I am planning to buy a low cost and low weight laptop with an Atom Processor.

I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?

body:
The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.

If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.

The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.


message:
Relay to Mains lightswitch

So I purchased a 4 channel Relay which handles AC250V 10A ; DC30V 10A.
But am I able to connect this to replace a light switch so I can automate it?  My bedroom runs on 15 amps.

[![relay board][1]][1]

http://amazon.com/gp/product/B00VHVIBAM?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00

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

body:
All mains electrical work should be performed by a fully qualified electrician.

Yes, this relay board will easily switch a light bulb.

A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).

You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.

A [similar question][1] was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is [Cybergibbons answer][2] where he recommends using the [PowerSwitch Tail][3] as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.

  [1]: https://electronics.stackexchange.com/q/33312/104097
  [2]: https://electronics.stackexchange.com/a/33366/104097
  [3]: http://www.powerswitchtail.com/


message:
Issue with simple project

I'm new to Arduino and today I have a problem with this code:

    int led_1 = 10;
    int led_2 = 11;
    int led_3 = 12;
    int button = 3;
    int time = 0;
    byte val = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(led_1, OUTPUT);
      pinMode(led_2, OUTPUT);
      pinMode(led_3, OUTPUT);
      pinMode(button, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      val = digitalRead(button);

      if (val == HIGH){
        time = millis();
        while (digitalRead(button) == HIGH) {
          if (millis() - time < 1000) {digitalWrite(led_1, HIGH);}
          else if (millis() -time > 1000 && millis()-time <2000) {digitalWrite(led_2, HIGH);}
          else if (millis()-time >2000) {digitalWrite(led_3, HIGH);}
        }
      } else {
        time =0;
        digitalWrite(led_1, LOW);
        digitalWrite(led_2, LOW);
        digitalWrite(led_3, LOW);
        }
    }

The code should work like this: If I press the button less than one second, `led_1` will turn on. If I press it between one and two seconds, `led_2` will turn on; and if I press the button more than 2 seconds, `led_3` will turn on. If I don't press a button, the LEDs remain off. The `time` variable is used to take the time when I start to press the button and then the control `millis()- time` should give how long I press the button.

It works for a while, then after a random time (I think) if I push the button, only the `led_3` turns on. Why?

body:
`time` should be an `unsigned int`.  As soon as `millis` reaches 32768, it will be stored as -32768 in `time`, and your comparisons will not work. This happens after 32.768 seconds.  Here's a short sketch to illustrate:

    int time = 0;

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

    void loop() {
        time = millis();
        if (time % 1000 == 0) {
          Serial.println( time );
          delay( 2 ); // let millis() increment
        }
    }

To see the difference, just change the first line to

    unsigned int time = 0;

Note how `time` rolls over to 0 after 65535 (well, only 65000 is printed).

I would recommend using unsigned constants by adding a "U" after the digits: `1000U`.  In your `if` statements, you must cast the `millis` to the same (smaller) type: `(unsigned int)millis()`.  Also, parentheses make the expression more clear:

          else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}


body:
Your code seems inefficient and there is a `tempo` variable that doesn't appear elsewhere.

      if (val == HIGH) {
        time = millis();
        while (digitalRead(button) == HIGH) {
          int time0=millis();
          if (time0 - time < 1000) {
            digitalWrite(led_1, HIGH);
          } else if (time0 - time < 2000) {
            digitalWrite(led_2, HIGH);
          } else if (time0 - time > 2000) {
            digitalWrite(led_3, HIGH);
          }
        }
      }

Note that this code will turn on all LEDs, one by one. If you want to turn off the other, you'll have to had code for that in the tests.


message:
Looking for help with WiFi modules

I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me.
Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.

I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.

Before anyone asks, yes, it is critical for it to work over wifi.
Has anyone done something like this? What gets the best results?

body: I cant comment so I'm going to post as an answer.  Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it.  As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.


message:
Best way to implement score board logic using Arduino and Shift Registers?

I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.

**Score - 888 (3 Digits)** - I have implemented this logic using shift registers.  Three pin used from Arduino Uno and this is working fine.

**Overs - 88 (2 Digits)** - Need to find a best way to implement it

**Wickets - 8 (1 Digit)** - Need to find a best way to implement it

Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

1.  One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.

2. The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers.  There are only few pins.

***Please Note: I need to print this design in PCB***

This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

body:
You could use a 16x2 LCD to display the information; then you wouldn't need so many separate lines from the Arduino, the PCB would be simple and compact, etc.

However, if you need a big high-power display that is not multiplexed, you could use one 74HC595 per digit, assigning one bit per segment with 7-segment LED displays, with a driver transistor on each output.

The six '595s would be in series, which would use only two output lines from the Arduino: clock and data.

Another approach is to build your display from 84 or 126 WS2811 or WS2812B LEDs (2 or 3 per segment, and 7 segments times 6 digits).  About $10 to $15 on Ebay.  This would use one data pin from the Arduino to drive the whole display and would supply bright RGB light.


body:
There isn't really a *best* way (and such questions are usually discouraged as they can easily descend into argument).

Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.

From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.


message:
Connecting and Programming LinkSprite Camera to Arduino

I recently bought the LinkSprite color jpeg camera:
https://www.sparkfun.com/products/12804
And the Arduino Wireless SD Shield:
https://www.arduino.cc/en/Main/ArduinoWirelessShield

I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.

body:
Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on [wiki][1].

Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc.

  [1]: http://linksprite.com/wiki/index.php5?title=JPEG_2M_Pixel_Color_Camera_Serial_Interface(TTL_level)


message:
arduino SD card saving to file

Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield

I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me

My code is;

<!-- language: c -->

    #define redled 10
    #define greenled 11
    #define echoPin 12
    #define trigPin 13

    unsigned long interval=60000; //interval = 60 seconds
    unsigned long previoustime=0;
    int minutes = 0; //global variables

    void setup() {
      Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(greenled, OUTPUT);
      pinMode(redled, OUTPUT);
    }

    void loop() {
     //-----------------------------------------------------------
      unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
      if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
        previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
        minutes = minutes + 1; //Add 1 minute
      }
      unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
      //-----------------------------------------------------------
      long distance = ultra_sensor(); //call function that now returns the distance
      //-----------------------------------------------------------
      if (distance < 4) {            // If distance is less than 4cm
        digitalWrite(redled,HIGH);   // Turn on Red LED
        digitalWrite(greenled,LOW);  // Turn off Green LED
      }
      else {                          //If distance is greater than 4cm
        digitalWrite(redled,LOW);     // Turn off Red LED
        digitalWrite(greenled,HIGH);  // Turn on Green LED
      }
      //-----------------------------------------------------------
      if (distance >= 200 || distance <= 0){
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.print("cm");
        Serial.print(" after ");
        Serial.print(minutes);              //Printing distance and time to serial monitor
        Serial.print(" minutes ");
        Serial.print("and ");
        Serial.print(time);
        Serial.println(" seconds");
      }
      //-----------------------------------------------------------
      delay(2000); //Get reading every 2 seconds
    }

    long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
      digitalWrite(trigPin, LOW);  //Set Trigger to idle
      delayMicroseconds(2); //Wait 2 microseconds
      digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
      delayMicroseconds(10); //Send the wave for 10 microseconds
      digitalWrite(trigPin, LOW); //Turn the trigger to idle
      long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
      long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
      return dis; //Send the distance to function call
    }

body: Looks like your sketch (pin usage) is in conflict with the SD shield (SPI pins). Try using other pins.


message:
glediator + PL9823 (WS2812B) + teensy = fail?

here is what I got:

* teensy++ 2.0 with code below
* Glediator configured for Glediator_Protocol/Single_Pixels/HL_TL/RGB/B_1000000
* led matrix with the PL9823 leds (80 of them)

I first off have to set the code to 160 on the teensy just to get it to                     at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.

Code

    #include "FastLED.h"
    #define NUM_LEDS 160
    const int dataline = PIN_B4;
    CRGB leds[NUM_LEDS];

    void setup()
    {
        digitalWrite(6,LOW);
        Serial.begin(1000000);
        LEDS.addLeds<WS2812B, dataline>(leds, NUM_LEDS);
        for (int p=0;p< NUM_LEDS;p++)
        {
            leds[p] = CRGB::Black;
            FastLED.show();
        }
    }

    int serialReadBlocking()
    {
        while (!Serial.available())
        {
        }
        return Serial.read();
    }

    void loop()
    {
        while (serialReadBlocking() != 1)
        {
        }
        for (long i=0; i < NUM_LEDS; i++)
        {
            leds[i].r = serialReadBlocking();
            leds[i].g = serialReadBlocking();
            leds[i].b = serialReadBlocking();
        }
        FastLED.show();
    }

https://www.youtube.com/watch?v=H6OuMWKtbmo

body:
G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with `FastLED.h` but is the `serialReadBlocking` how it deals with the input data? Not that it's wrong, just not what I was expecting.

Two things to look at:

 1. Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.

 1. I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td_uart.html


message:
Low power + Logging motion detection

Scenario: I would like to monitor my closet's door as I highly suspect a family member is opening and using my items without permission. To respect privacy and also because my closet is nowhere near a power mains, I don't need video nor audio recording. I also do not need indicator lights etc because I intend to turn it on when I go to work and check the logs on the SD card when I return home. A typical day would require the device to run for 12 hours minimally.

Aim: Is it possible for Arduino to achieve the following,

1. Run on batteries for at least 1 month

2. Detect motion

3. Logging the detection motion onto a text file in a SD card

Or do I have to look elsewhere for this functionality?

Current understanding: I am aware Arduino can run on batteries though I've never been able to get it to last more than 3 hours. Probably has to do with me not using the low power mode or something and that my batteries were being stepped up. I also know that Arduino has some PIR motion sensors though I don't quite remember how power hungry these sensors are. I have NEVER tried logging onto an SD card using Arduino. This sums up my experience with Arduino.

Any advice would be much appreciated. Thank you.

body:
It is possible to modify an Arduino Pro Mini (clone or original) to less than 1 mA and give at least a month on standard batteries (1000 mAh). Basically you need to remove the Power indicator LED and use low power mode in the sketch.

You could start simple by just lighting a LED when motion is detected and add the SD log later.

There are several techniques to detect motion. Advanced accelerometers such as [ADXL345][1] but also simple [wire sensing][2]. The standby power requirements for these have a large variation.

  [1]: http://www.analog.com/en/products/mems/mems-accelerometers/adxl345.html
  [2]: http://www.interlogix.com/intrusion/category/wired-sensing


body:
For low-power, just some tips (link references)

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

claim the below results,

    LED off, without the JeeLib library: 6.7 mA
    LED on, without the JeeLib library: 8.8 mA
    LED off, with the JeeLib library: 43 uA (!)
    LED on, with the JeeLib library: 2.2mA

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

Detailed step by step tutorial.

For sensing PIR will depend on exact components; using SMD low-leakage components will do the trick but cost would increase. There are very-low-power RTC on the market and maybe SD logging will be more difficult as can consume up to 200 mA per reading/writing operations.


body: The PIR sensors are actually pretty cheap: http://www.ebay.com/itm/like/171338717482?ul_noapp=true&chn=ps&lpid=82


body:
You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state.  Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.

An SDcard is neither necessary, nor a good idea.  If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card.  They will also be simpler to support in software.  Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.

Your main power consumption win however will be sensors.  If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption.  Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened.  Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.


message:
Script stops functioning after calling irsend() function in irlibrary!

I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.

    /*
     * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
     * An IR detector/demodulator must be connected to the input RECV_PIN.
     * Version 0.1 July, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     */

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    IRsend irsend;

    decode_results results;

    int intValue;
    String strValue;
    String str3;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        intValue = results.value;

        Serial.print("Integer value : ");
        Serial.println(intValue);

        strValue = String(intValue);
        Serial.print("String str : ");
        Serial.println(strValue);

        Serial.print("Length : ");
        Serial.print(strValue.length());
        Serial.println();

        if(strValue.length() <= 1){
          str3 += strValue;
          Serial.println(str3);
           // Receive the next value
       }

        delay(200);
        irrecv.resume();
      }
      //Serial.println(str3);
      if(str3.endsWith("770")){
        powerOff();
        str3 = "";
      }
      else if(str3.endsWith("769")){
        powerOff();
        str3 = "";
      }

      else{}
      //powerOff();
    }

    void powerOff(){
        irsend.sendRC6( 0xC0000C, 24);
        irrecv.resume(); // Receive the next value
    }

body: Apparently you should be calling `irrecv.enableIRIn()` after sending, not `irrecv.resume()`. Sorry for suggesting the wrong thing on IRC before :-)


message:
minIMU 9 and Arduino reading Gyro angle

I'm using minIMU-9 https://www.pololu.com/product/1268 and I want to read pitch, roll and yaw angles. I applied this library https://github.com/pololu/minimu-9-ahrs-arduino but there is a slope when sensor is not moving or vibrating. How can i fix or compensate this. The y axis is angle in degree and x axis is time in seconds

Pitch

[![Pitch][1]][1]

Roll

[![Roll][2]][2]

Yaw

[![Yaw][3]][3]

  [1]: https://i.stack.imgur.com/Us5BU.png
  [2]: https://i.stack.imgur.com/9oRC2.png
  [3]: https://i.stack.imgur.com/dzEgx.png

body:
I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.

What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.

Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.

Below the L3GD20's mechanical characteristics

[![Gyro's mechanical characteristics][1]][1]

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


message:
MG2639 & Arduino Uno not GPS-ing?

is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.

body:
Try sending a command that sets the GPS baud rate to something a little lower:

    altss.write( F("$PMTK251,38400*27\r\n") );
    altss.end();
    altss.begin( 38400 ); // change to match above command

Are you sure you're having trouble *reading*, because there are many other things you may be doing in your sketch that cause input buffer *overflow*.  Please post your code and some sample output for us to examine.  It may be failing for a different reason.

For example, you may just be losing data because you're trying to do too many things in `loop()`.  Please take a look [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md#trying-to-do-too-many-things).

To solve this kind of problem, I have posted a modified version of `AltSoftSerial` on github, [here](https://github.com/SlashDevin/NeoICSerial), that let you process GPS data in the background (i.e., during interrupts).  When coupled with [NeoGPS](https://github.com/SlashDevin/NeoGPS), it can save you quite a bit of program space, RAM and execution time.  There is an interrupt-driven example [here](https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEA_isr/NMEA_isr.ino).  Just change which include is uncommented on lines 30-31:

    #else
      // Only one serial port is available, uncomment one of the following:
      #include <NeoICSerial.h>
      //#include <NeoSWSerial.h>
    #endif
    #include "GPSport.h"

...and the baud rate below, on line 140:

      // Start the UART for the GPS device
      gps_port.attachInterrupt( GPSisr );
      gps_port.begin( 115200 );
    }


message:
Can you connect ACS712 sensor to digital input of Arduino?

I have a home automation project and am looking to use multiple current sensors (ACS712) for multiple appliances. I just need to know whether current is present or not instead of the current value. Is it possible, that I connect the ACS712 sensor to the digital input of Arduino, and get HIGH or LOW via `digitalRead()` function. If not, please suggest an alternative to detect ac current is present or not with digital input i.e. HIGH or LOW that can be read via the `digitalRead()` function.

body: Use a comparator for an adjustable threshold and feed the output into the arduino digital pin.


body:
Considering an ATMEGA with a 5V VCC we have:

    LOW  = < 0.3*VCC = 0,3*5V = 1.5 V
    HIGH = > 0.5*VCC = 0,5*5V = 2.5 V

You can connect directly to the Arduino if the output of your sensor is higher than 2.5 volts whether current is present or below 1.5 volts if not. This would translate to HIGH or LOW output from `digitalRead()` function respectively.

You need to recalculate this values for the 3 volt version of Arduino, probably in this case is better the comparator solution to ensure up to 3 volts max logic level.

Example circuit as follow, just need to set voltage divider to desired threshold (note this is for 5v case),

[![Comparator][1]][1]

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


body: It seems like you could do this with a transistor (if "faking" a digital signal from the ACS712 doesn't work). A simple circuit where the VIOUT of the ACS712 drives the base of a switching transistor connected to a digital pin on the Arduino with an internal pull up might do the trick (assuming that the ACS712 give you a voltage on VIOUT that is proportional to the current).


body:
The Arduino/AVR (for instance [ATmega328p, chap. 22][1]) has an analog comparator (D6/AIN0, D7/AIN1 or any analog pin). This could be used with the correct reference voltage.

Cheers!

  [1]: http://www.atmel.com/images/doc8161.pdf