text:
"No more addresses" when using multiple DS18B20 sensors
I want to build a scheme to get data from several DS18B20 sensors and write their temperature to serial. Before I connected them using parasite mode and using 2,7k resistor (because I didn't have 4,7k at home). Back then, it worked for 1 device, if I plug in another, it won't detect any of them (it writes "No more addresses"). Now I replaced 2,7k resistor with 4,7k and it doesn't detect any device connected. But if I do one little thing, which is replacing 4,7k resistor back with 2,7k, it will detect one device.
How to fix it?
Here is exactly how it is all connected now:

and here is the default sketch I am using:
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 2 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for ( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44);        // start conversion, use ds.write(0x44,1) with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

Is there anything I am doing wrong? Because I somehow managed to get it working some time ago.

Wow, switching the resistor to 620R worked. Guess I have a problem within my breadboard.

Have you tried without parasite power, or you have any particular reason for using parasite power?

Breadboard create a bit of capacitance on the data line. Try placing the second module right under first (so sharing the same breadboard "columns").

@Personagem it was just easier to connect, in my opinion. Is there any difference?

Some sources advise to not use with multiple devices ( http://openenergymonitor.org/emon/buildingblocks/DS18B20-temperature-sensing). However data sheet says it is possible as long a strong pullup is present. I would go with the normal power with 4.7k pullup. Be very carefull connecting vdd to correct PIN in sensor. It will burn in seconds if you reverse polarity.

A problem with what you are doing on the breadboard is that you show no bypass capacitors.
What makes the pull up "strong" is the ability to provide current to move the data line from zero back to one.  The load on the data line is its capacitance.  To move the data line from 0 to 1, you have to charge that capacitor.  Working on a bread board, you are correct that you have a larger capacitive load.  So you require more current to move the data line from zero to one quickly.
You are correct that the lower 620 ohm resistor will provide more current.  The large current will move the capacitance load of the data line more quickly.  But you are not paying attention to the other side of the resistor, the 5V rail.
The layout you have has inductance in the wires from the Arduino power supply out to the bread board.  An inductor has a voltage drop across it proportional to the rate of change of the current through it:
V = L  di/dt

The analogy is that inductance is a flywheel: if it is not spinning, it will take force to get is moving.  Similar, once it is spinning, it will take force to stop it.
So when the resistor starts conducting to pull up the data line, the inductance in the wires and breadboard cause a voltage drop.  The +5 side of the resistor voltage drops.  This inductance in the wires leading to the resistor prevents it from rapidly charging the data line back to 1.
That is the role of bypass capacitors.  You place 1 or 2 right at the resistor between the +5 and GND strips on the bread board.  Now when the resistor draws current, it initially pulls from the energy stored in the capacitors.  After a short time, the current will start pulling from the +5 wire.  Thereby, you have bypassed the inductance of the +5 supply, hence the name.
Add a 0.1 microFarad ceramic capacitor on your breadboard where the wires connect to the contact strips.  You will see this on schematics for anything that has a DC supply off board.  Right next to the power connector will be 2 or 3 capacitors, usually one big 2-10 uF tantalum and one smaller 0.1 uF or so.  Similar across circuit boards you see bypass caps placed at the supply voltage pin of every chip, commonly two: a 0.1 uF and a smaller 10 nF.
It might seem pointless to place a small capacitor in parallel with a larger capacitor.  The values just add, yes?  But again, the time response is different.  Capacitors are not perfect and have internal series resistance.  A big 10 uF electrolytic capacitor may store a lot of energy, but it is not fast in terms of how quickly it can start providing current.  A little 100 nF ceramic monolithic capacitor is very fast, but doesn't have much energy.
So with two bypass caps in parallel, you have the small one for the initial burst of current, the larger cap for the heavy lifting, and last and slowest the 5V wires and traces to supply to steady current.

0.1uF == 100nF.

A strong-pullup seems to be the key to having multiple sensors in parasitic mode, as described in the datasheet for the DS18b20 devices. Though they suggest using a MOSFET to pull up the 1-wire bus, I've had good results (3 meters of wire, 3 devices more than 2 meters out) by tying an output port directly to the 1-wire bus, bypassing the 4.7K resistor.
// One wire bus strong-pullup:
//
//    +------------+     +5v            +---------+     +---------+
//    |    MCU     |      |             | DS18b20 |     | DS18b20 |
//    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
//    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
//    | Pullup   > o------o               |  |  |         |  |  |
//    |            |      |               +--|--+         +--|--+
//    |            |      |               |  |            |  |
//    |    Data <> o------o---------------|--o------------|--o------ - - -
//    |            |                      |               |
//    +------------+                      V               V

Initialize the strong-pullup port by setting the port as an output and HIGH, the disable and enable it by changing the port mode, not the output value. (Setting the port mode to input floats it, rather than grounding it as setting it LOW would do. This technique was suggested to me by Dave Tweed in Electrical Engineering Stack Exchange.)


text:
Power 4 leds with max7219 and LedControl.h
So this is my first arduino (or embedded for that matter) project. I am trying to power 4 leds with max7219. Max7219 seems easy to use, but for some reason after I upload the code, nothing happens. I've looked over my breadboard, and the connections seem right. My confusion arises from the fact that all the projects I have found on google use matrices for the leds. I am using 4 separate leds. Does this even matter?
Here is the code I use:
#include "LedControl.h"

LedControl ledControl = LedControl(12, 9, 10, 1);

void setup()
{
    //should be waking ledcontrol
    ledControl.shutdown(0, false);
    ledControl.setIntensity(0, 8);
}

void loop()
{
    ledControl.setLed(0, 0, 0, true);
}

Could you add a image of your breadboard wiring and possibly a schematic of how you wired it.

Try setting all the leds to on, instead of just the first one.

No it shouldn't matter that you are using separate LEDs, but you will have to connect them in a way that is acceptable to the 7219, they will have to share either a common anode or cathode (can't remember which of the top of my head).
I find its always best to check the basics (Based on personal experience)

Have you got the LEDs the correct way around?
Are you using the correct voltage for everything?
Do the LEDs work when controlled directly by the Arduino, try "Blink"?
Have you tried changing the intensity?
Have you got the required resistors in?
Try inverting the index of the LEDs, i.e. led(x=0,y=0) might be wired (x=7,y=7)?

You loop() is not pausing, so all it is going to be doing is calling that one statement repeatedly.  Now that might not be a problem or the second call may be blocking the first from completing.  So I suggest add a delay for a second or so and see if that changes anything.  Also to prove you are running you Loop() code flash the LED on the board (pin13?).
Hope that helps.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Is there a way to power off external devices during deep sleep
I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.
Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.
So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?
Thanks!

To answer your question, yes, you can use a transistor to stop excess power draw. Or do you want to know how to do it?

I made a temperature and humidity sensor which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.
The power-control part of the circuit is here:

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

The full schematic is:

I think I've changed the batteries once since making it in 2013.

Nick, excellent and detailed information. A couple of years would be nice but I am shooting for at least 6 months and am using a 2500mAh LiPo battery pack. The reason only six months? I am using a wifi (ESP8266) device to connect and send on wakeups and the sensors draw a fair amount when awake. I am okay with 6 months though. Do you think I can use a PNP (2N3906) instead of the FET to switch on and off?

The FET has much greater capacity to handle larger currents (47A compared to 200 mA). When you say the sensors draw "a fair amount" I would take that into consideration. I had another project that powered a transmitter just using solar power.

you don't have to send each wakeup; w/o wifi, the esp only uses about 15ma...

@NickGammon, is there anything specific about FQP47P06 transistor you used? I'm looking for something more common (and perhaps cheaper)?

@TomekCejner Not particularly, that just happened to be one I was able to get at the time, or already had to hand.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
what is aref(analog reference)
what is the analog reference, I know that it can be used as a voltage reference, but not exactly what  it is all about please someone help.

It is the reference voltage against which all other analog voltages (analog inputs) are measured against.
By default it is the same as the chip supply voltage (5V on most Arduino boards), so the analog inputs can measure between 0 and 5V.
If you connect the AREF pin to a lower voltage, say to the 3.3V pin (for convenience) and set the analog reference to EXTERNAL, you can then measure between 0 and 3.3V.
This is good if you are measuring a smaller voltage and want to get as much resolution in the analog reading. If you leave it at 5V and are measuring only up to, say, 3.3V, you're wasting all the analog reading values between 3.3V and 5V that could go to getting you more sensitivity.

When the EXTERNAL is not selected, the first analogWrite selects the internal voltage reference. That voltage can be measured at the AREF pin with a multimeter. The Arduino Uno has inside the chip a voltage reference of 1.1V, that can be useful when the 5V is not exactly 5.0V, for example when the Uno is powered via the usb cable. Reference: https://www.arduino.cc/en/Reference/AnalogReference

@Jot You mean analogRead, not analogWrite ...

Oops, sorry, yes I ment analogRead.


text:
Why does the Arduino Due have a native and USB programming port?
According to the schematics, the Arduino Due has two USB inputs:

Native
Programming

Why is this? And when would I use the different ports?

Either port can be used for programming, but the native USB port lets you do other things:

It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To
  use these features, see the Mouse and Keyboard library reference pages.
The Native USB port can also act as a USB host for connected
  peripherals such as mice, keyboards, and smartphones. To use these
  features, see the USBHost reference pages. http://arduino.cc/en/Main/arduinoBoardDue

So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.

So, it would be possible to attach a mouse to USB native, and detect and Register mouse movements in the host laptop via the other USB input?

I think only the native one can do both of those things. The other one is for programming only.


text:
What purpose does the yellow and green LEDs have on the Arduino?
I have wired up a small project with a shift register (see below), but depending on how I put the 74HC595 IC (8-bit shift register with 3-state output register), the green and yellow LEDs of the Arduino stop shining.
What are these LEDs for? Do they tell something about a possible damage of the IC/short circuit in the setup?

The green LED is marked with ON, and it indicates that the Arduino has power.
The yellow LED is marked L and is just connected to pin 13. So when you set pin 13 to HIGH the LED lights up. You can however still use pin 13 for other things.
When the green LED stops shining you most likely have a short somewhere. As the short will drain all power away, so the Arduino has no power left to light the LED(s).

Or if you draw too much power from the +5V, the thermal protection circuit on the voltage regulator will trip and the whole Arduino will shut down.

Also be warned that the L LED (the one activated by pin 13) may light up if pin 13 is high-impedance (set to input), and is not connected to anything.
On my Uno, a trivial sketch like this lights up the L LED:
void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

This is because the LED is not driven directly by pin 13, but by an op-amp (U5B) which -- if the pin is configured as an input -- may pick up enough stray voltage to activate and light up the LED.
This can be confusing because you might look at your board and think "huh? I didn't command that LED to come on".

What, an op-amp on the L LED? Uh, you are right. They added it in Rev3. It was not there on the Uno Rev2.

I suspect that driving the LED directly was influencing the pin when it was being used for other things (like SPI). So inserting a high-impedance driver (the op-amp) minimized that. And you are right, it was a moderately new addition, but I didn't have the energy to find exactly which board had it, so I left that unsaid. ;)

This is a new "feature" in Uno R3 boards.

Also note that there is the TX and RX pins on Uno (orange/yellowish) are for the USB connection. When the LED labeled TX is lit up, the Arduino is transmitting data to the computer. When the RX is lit up, it is receiving data from the computer.

Just wanted to re-iterate that On the MEGA 2560 Revision 3 you can't change the L led pin 13 due to the op-amp like Nick Reported.
Spent a couple hours on this scratching my head only to find this out


text:
Error: Function not declared in the scope
I want to make a timer library. The cpp file I have written is:
#include "avr/interrupt.h"
#include "Arduino.h"

#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
    TIFR1 |= _BV(OCF1A);
    TCCR1B = 0X00;
    digitalWrite(13,!digitalRead(13));
}

void AllTimer::setTimer(void)
{
    TCNT1 = 0x0BDC;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
}

ISR (TIMER1_OVF_vect)
{
    dofun();
}

And the header file:
#ifndef AllTimer_h
#define AllTimer_h

class AllTimer{
public:
    AllTimer();
    void setTimer(void);

private:
    void dofun(void);
};

#endif

While compiling the file i am getting the following error:
sketch_jan05a.cpp: In function ‘void __vector_13()’:
sketch_jan05a.cpp:34:9: error: ‘dofun’ was not declared in this scope

You know its time to go home when you make this mistake. readTouchscreenParamsGeneric in header vs readTouchScreenParamsGeneric in cpp. Generates the same error message. Doing a search all, case-insensitive, led me to believe I had made no typos.... when in doubt, also turn on case-sensitive search.

Answering here because I do not have enough rep to comment.
At each iteration, the value in the timer counter must be reloaded.
Either the ISR or dofun are responsible to reload TCNT1.

Because in the call:
 dofun();

you should put from which class you are calling that function.
In your case:
AllTimer::dofun();

in that case your function must be declared as static method.
EDIT:
Thanks to the comment:
I'm not pretty sure if your code reflects what you want to do. Because you can create your timer after defining the class:
Alltimer mytimer;

and call the method as a normal function (it must be declared as public):
ISR (TIMER1_OVF_vect)
{
    mytimer.dofun();
}

But it is hard to say since I m not sure what you want to do.

That will work only if dofun() is modified to be a static method. It must also be made public:.

dofun() is currently declared as a private member function, meaning you can't call it directly. It can only be called internally by an instance of the AllTimer class.
It looks like you probably want to declare it as a public static function instead. To do that, remove the private specifier from the class declaration, and put static before the function declaration. Your header should look something like this:
class AllTimer
{
public:
    AllTimer();
    void setTimer(void);
    static void dofun(void);
};

You will then need to change the ISR to include the class name in the call:
ISR (TIMER1_OVF_vect)
{
    AllTimer::dofun();
}

How do i define dofun in cpp file?

@user3929110 The existing definition should be fine.

The code compiled well but the timer isn't working. The LED is remaining ON only.


text:
RGB fade program
I'm working on a function to fade RGB LEDs smoothly from one color to the next, so I thought I'd use a for loop  to increment each RGB value according with the set value. I've made the for loop as following:
for (redFadeCurrent, greenFadeCurrent, blueFadeCurrent;
   ((redFadeCurrent != redFadeTarget)&&
   (greenFadeCurrent != greenFadeTarget)&&
   (blueFadeCurrent != blueFadeTarget));
   redFadeCurrent = redFadeCurrent + redStep,
   greenFadeCurrent = greenFadeCurrent + greenStep,
   blueFadeCurrent = blueFadeCurrent + blueStep) {

    analogWrite(ledRedPin, redFadeCurrent);
    analogWrite(ledGreenPin, greenFadeCurrent);
    analogWrite(ledBluePin, blueFadeCurrent);
    Serial.print("Red: ");
    Serial.print(redFadeCurrent);
    Serial.print(" Green: ");
    Serial.print(greenFadeCurrent);
    Serial.print(" Blue: ");
    Serial.println(blueFadeCurrent);
    delay(3000);

    if (redFadeCurrent>redFadeTarget) {
        redStep = -1;
    }
    else if (redFadeCurrent<redFadeTarget) {
        redStep = +1;
    }
    else {
        redStep = 0;
    }

    if (greenFadeCurrent>greenFadeTarget) {
        greenStep = -1;
    }
    else if (greenFadeCurrent<greenFadeTarget) {
        greenStep = +1;
    }
    else {
        greenStep = 0;
    }

    if (blueFadeCurrent>blueFadeTarget) {
        blueStep = -1;
    }
    else if (blueFadeCurrent<blueFadeTarget) {
        blueStep = +1;
    }
    else {
        blueStep = 0;
    }

Problem is, when one of the values hit the target the code leaves the for loop.
I'm guessing the condition ((redFadeCurrent != redFadeTarget)&&(greenFadeCurrent != greenFadeTarget)&&(blueFadeCurrent != blueFadeTarget)) does not work.
Is there any way to work around this?
Thanks is advance.

Your code sample is incomplete the end of the loop is missing }.

You are correct, the problem is the condition inside the for statement.
Let's examine what happens when the red LED hits its fading target, which is, say, 100 (for the sake of the example, I will fabricate the other values):
for (...; (100 != 100) && (90 != 100) && (80 != 100) ; ... )

(100 != 100) -> FALSE
(90 != 100) -> TRUE
(80 != 100) -> TRUE

FALSE && TRUE && TRUE -> FALSE
The condition inside the for evaluates to FALSE, therefor the loop will exit.
If you want the loop to continue as long as there is at least one LED which hasn't hit the fading target, you should change the AND to OR:
((redFadeCurrent != redFadeTarget) || (greenFadeCurrent != greenFadeTarget) ||
   (blueFadeCurrent != blueFadeTarget))

Let's examine what happens now with the same values:
for (...; (100!=100) || (90 != 100) || (80 != 100) ; ...)

(100 != 100) -> FALSE
(90 != 100) -> TRUE
(80 != 100) -> TRUE

FALSE || TRUE || TRUE -> TRUE ==> The loop will continue.
And what will happen when all the colors hit the fading targets?
for (...; (100!=100) || (100 != 100) || (100 != 100) ; ...)

(100 != 100) -> FALSE
(100 != 100) -> FALSE
(100 != 100) -> FALSE

FALSE || FALSE || FALSE -> FALSE ==> The loop will stop since the condition will not evaluate to TRUE.

...That's kind of embarrassing!
Gotta do some exercises on my logic. :p
Thank you very much!


text:
Fading from color to color using for-loop FastLEDs
I'm attempting to fade a strip of ws2812 7 pixels in length. Below I am using a for loop to increment the color red. I can fade it to red (from blue) but it will do it one pixel at a time or it just stays blue, depending where I move my r for-loop to. I need it to fade from color to color all 7 LEDs at once.
I get no errors.
I don't understand the process of getting NUM_LEDS leds all into x then proceeding with my color changing. Seems like I'm grabbing one pixel, fading it to red, then another...
fastLeds 3.03 library, arduino 1.0.6
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100
int r;
CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
}

void loop(){
  for(int x = 0; x < NUM_LEDS; x++){
    delay(10);
    leds[x] = CRGB(r,g,b);
  }
  FastLED.show();
  delay(10);

  //-------------------------

  for(int x = 0; x < NUM_LEDS; x++){
    for(int r = 0; r < 254; r++) {

if NUM_LEDS is holding the number 7 why can't I just do it like this below: leds[NUM_LEDS]?
      leds[x] = CRGB(r,g,b);
      FastLED.show();
      delay(100);
    }
  }
}

If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}

Hi bigjosh. Thank you for taking the time to look over and edit my code. But it isnt working. It just lights up red. no blue. no fading. was I suppose to add anything or is it complete above?

Doh! Misplaced parenthesis. Edited- should work now. Sorry!

AHHH! Thank you bigjosh. Im embarrassed to say how long ive been trying to fade my led strip. Thanks again man, Youve been a big help.

Here is the initial 0-255 rainbow.  I dunno if this is what you are trying to achieve but i took initiative from @bigjosh's answer.  This just cycles thru each rgb from 0-255. @bigjosh does start red at 0-255 allowing for more for red colors.
void loop(){

//start from red
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

  int r = 255;
  int g = 0;
  int b = colorStep;

  // Now loop though each of the LEDs and set each one to the current color
  for(int x = 0; x < LED_COUNT; x++){
      leds[x] = CRGB(r,g,b);
  }

  // Display the colors we just set on the actual LEDs
      delay(10);
      FastLED.show();
      }

    //into blue
      for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = colorStep;
      int g = 0;
      int b = 255;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(10);
  FastLED.show();
  }

//start from blue
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

      int r = 0;
      int g = colorStep;
      int b = 255;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(10);
  FastLED.show();
  }

//into green
  for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = 0;
      int g = 255;
      int b = colorStep;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

//start from green
  for( int colorStep=0; colorStep <= 255; colorStep++ ) {

      int r = colorStep;
      int g = 255;
      int b = 0;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

//into yellow
  for( int colorStep=255; colorStep >= 0; colorStep-- ) {

      int r = 255;
      int g = colorStep;
      int b = 0;

      // Now loop though each of the LEDs and set each one to the current color
      for(int x = 0; x < LED_COUNT; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
  delay(wait_time);
  LEDS.show();
  }

} //end main loop


text:
Timer function without the use of a library
Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.
unsigned long previousMillis1 = 0;
unsigned long currentMillis1 = millis();
unsigned long previousMillis2 = 0;
unsigned long currentMillis2 = millis();
unsigned long previousMillis3 = 0;
unsigned long currentMillis3 = millis();

bool timer1(int preset){
  unsigned long currentMillis1 = millis();

  if(currentMillis1 - previousMillis1 >= preset ){
    previousMillis1 = currentMillis1;
    return true;
  }
  else{
    return false;
  }
}

bool timer2(int preset){
  unsigned long currentMillis2 = millis();

  if(currentMillis2 - previousMillis2 >= preset ){
    previousMillis2 = currentMillis2;
    return true;
  }
  else{
    return false;
  }
}

bool timer3(int preset){
  unsigned long currentMillis3 = millis();

  if(currentMillis3 - previousMillis3 >= preset ){
    previousMillis3 = currentMillis3;
    return true;
  }
  else{
    return false;
  }
}

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

void loop() {
  if(timer1(1000)){Serial.println(1);}
  if(timer2(2000)){Serial.println(2);}
  if(timer3(3000)){Serial.println(3);}
}

What is a "timer function"?

Do not store times in signed numbers! Your computation of currentMillis1-previousMillis1 is prone to signed integer overflow, which in C and C++ yields undefined behavior. Meaning it's always incorrect, even if it luckily works with your current compiler. millis() returns an unsigned long.

edited for the unsigned. Thanks for that.

Actually, signed longs are just as fine, as long as you compare T2 - T1 > duration. What is actually prone to integer overflows is T2 > T1 + duration. That is, assuming T2 is always "later" than T1 and the difference between them fits in the type.

Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.
Here it is easy: the only difference between your timer functions is
that they use a different previousMillis variable. Also, the name of
the currentMillis variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a reference to
the relevant PreviousMillis.
bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

And you use it like this:
void loop() {
  static unsigned long previousMillis1;
  static unsigned long previousMillis2;
  static unsigned long previousMillis3;

  if (timer(previousMillis1, 1000)) Serial.println(1);
  if (timer(previousMillis2, 2000)) Serial.println(2);
  if (timer(previousMillis3, 3000)) Serial.println(3);
}

I took the liberty of making all the previousMillis local to loop(),
since they are only used there. Making them static means their values
are remembered between call to loop(), much like global variables.
In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are explicitly manipulating
addresses, while this is implicit with references:
bool timer(unsigned long *last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - *last_time >= period) {
    *last_time = now;
    return true;
  }
  return false;
}

void loop() {
  /* [...] */
  if (timer(&previousMillis1, 1000)) Serial.println(1);
  /* [...] */
}

The next step in code modularity would be to wrap this timer function,
together with the associated data (last_time and period), inside a
class:
class Timer
{
public:

  Timer(unsigned long _period)
  : period(_period), last_time(millis()) {}

  bool shouldRun() {
    unsigned long now = millis();
    if (now - last_time >= period) {
      last_time = now;
      return true;
    }
    return false;
  }

private:
  unsigned long period;
  unsigned long last_time;
};

Then, you would use it like this:
Timer timer1(1000);    // period = 1000 ms
Timer timer2(2000);    // period = 2000 ms
Timer timer3(3000);    // period = 3000 ms

void loop() {
  if (timer1.shouldRun()) Serial.println(1);
  if (timer2.shouldRun()) Serial.println(2);
  if (timer3.shouldRun()) Serial.println(3);
}

Thank you for the input. It is very helpful. I understand classes and objects, but not so much pointers. The main reason I have 3 separate timer functions is because I tried with one single function, however, it would not work correctly, as it only printed the one second timer. Can you at least explain how pointers would work to get around this and allow all 3 timers to function properly? Also, if you don't mind, I would like to see how you wrote the class

If your single function version did not work, that was a bug. You may want to post that buggy code here if you want people to explain what was wrong. If you do not understand pointers, well, this is a big topic that requires some good book or tutorial, some patience, and careful study. Not the kind of thing that can be easily explained here. I edited my answer to include a version with pointers and a class.

I have experience using industrial controllers. Can i ask, is it similar to "indirect addressing" or "indexed addressing"?

I have no experience with industrial controllers, but pointers are related to “indirect addressing”, in the assembly sense of the term.

You can simplify a lot by using arrays. The example code below just uses a single variable (array) to store all the time intervals you are interested in.
const int NUMBER_OF_TIMERS = 5;

unsigned long intervalStarted [NUMBER_OF_TIMERS];

void resetTimer (const int whichTimer)
  {
  if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
    return;   // sanity clause
  intervalStarted [whichTimer] = millis ();
  }  // end of resetTimer

// interval in milliseconds
bool timeUp (const int whichTimer, const unsigned long whatInterval)
  {
  if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
    return false;   // sanity clause
  return  millis () - intervalStarted [whichTimer] >= whatInterval;
  }  // end of timeUp

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting ..."));
  }  // end of setup

void loop ()
  {

  if(timeUp(0, 1000))
    {
    Serial.println(1);
    resetTimer (0);
    }  // end of if timer 0 up

  if(timeUp(1, 2000))
    {
    Serial.println(2);
    resetTimer (1);
    }  // end of if timer 1 up

  if(timeUp(2, 3000))
    {
    Serial.println(3);
    resetTimer (2);
    } // end of if timer 2 up

  }  // end of loop

I have allowed for 5 "timers" in the code but only used 3 to be consistent with the original post. You can see that you can have as many as you want (until you run out of RAM) with only an overhead of 4 bytes per "timer".
Two functions are provided. One checks if a nominated interval is up, the other one "resets" the timer by setting its start time to now. The checking function should work correctly even during millis() wrap-around, providing you are not trying to time more than 4294967296 milliseconds in one hit (49.71 days).
Note that the timer numbers are zero-relative, so the first timer is timer 0. You could make them one-relative if you prefer that with a slight adjustment to the two functions.
You could also, if you chose to, put the resetTimer function call inside the timeUp function (if the time is up) so that the timer automatically resets. I didn't do that because I think starting timing, and detecting the end of a period could be two different things. For example, when you boil an egg, you start timing from the time the egg goes onto the boil, not from when you last cooked an egg.

I do not think an array significantly simplifies the code unless you are going to loop through it... which you could do if you attach a callback to each “timer”. Anyway, +1 for providing a rollover-aware example!

Happened across this page which explains Arduino timer interrupts with out using any libraries.  The Atmel timer hardware is discussed and the sketches not only control the hardware directly but also include the actual interrupt service routine.  So addresses the OP's question very well.

It depends on what kind of efficiency you want. In coding we can often between better execution speed and less memory required. And in the case of Harvard-architected machines such as the AVR devices, which have separate memories for code and data, there may be a further balance between those, too.
But it looks like you're trying to reduce your code space requirement. So notice how alike your three timer functions are. I'd combine those into one, and pass another argument that indicates which timer value to operate on.
Secondly, (and this is probably a bug more than an inefficiency), you have three globals that are not being used (in your example, anyway): long currentMillis1, ..2, & ..3. You have redeclared each of those names as a local variable in the respective timer function, which, within that function over-rides (hides) the global declaration. There is no code that uses those globals.

Those lines like
currentMillis1;
are completely useless
You do not really have "timers", especially if your goal is to be more efficient. What you have done is to create some convoluted way to perform a test that could be done as:
int PERIOD = something;
for (int target = millis() + PERIOD; millis() < target;);
If you really care about efficiency and timed actions, check some library that deals with timer interrupts.
Start reading the code of existing libraries and try to understand it.
Chances are that who wrote them knew a great deal more than you know. You will learn much more from first reading the code than trying to accomplish something that is clearly too much beyond your current knowledge (the fact you think what you did is an optimization proves it).

First of all, yes, I took the lines that are useless out.
Second of all, I am highly offended by your last comment. You obviously did not read my statement and question above ASKING if there was a way to optimize it. I never stated that I optimized anything.
Lastly, isn't this what stack exchange is for? To ask questions? Not everyone is a professional at programming.

I really didn't mean to offend you.But to me, your question shows that you are lacking some concepts. Interrupts, for example. Writing your own optimised ISR would be a way to optimize for real. But is it worth? What you did is likely to be used in a busy loop, doing polling on millis().
Not very optimized, generally speaking. Is it good enough for you? You are the only one who knows, until you say more. So you get the same answer: check if any of the existing libraries works for you, understanding what it does. If it doesn't work for you, come back explaining why it doesn't work for you.

Your single line example not only does something completely different from the OP's code, its also broken: think about what happens when the first call to millis() yields something bigger than INT_MAX.

I agree with @EdgarBonet here - your answer is incorrect and even offensive, for no good reason.

authors: الاسم الاول اية


text:
Library files multiple users
I want to place all of my libraries on the server. Currently the sketches work fine and as far as I know the libraries are coming from the individual linux mint machines using cinnamon, releases vary depending on machine. I can move the libraries etc but what do I do to the IDE 1.8.18 and 1.8.19? to make it follow that path.

How about placing all libraries at a network share and then mount this share on each linux machine to the libraries folder?

The server is already mounted as far as I know. In the GUI I select the server then the appropriate folder. It shows as "network:///"  I then pick the server20 and get this "smb://server20.local/" then I pick my target folder "smb://server20.local/documents/" at this point any of the subfolders open and files are accessible such as opening a sketch etc and they will compile without a problem. I have used Linux for many years and appreciate its power but I definitely do not fully understand it.

If you type the command "mount" into a command line terminal it will list all mounted directories. But to mount a network share at a specific directory you most likely will have to learn how to mount them. There are many tutorials on the mount command and the fstab file for permanent mounts

How does that allow the IDE to access libraries on the server or other drives? From what I understand I have to change the default path in the IDE. If this is correct how?

It would allow to access the files, because with a mount the OS will make the files reachable inside the normal directory structure. With a mount you can choose the directory, where the network files should be visible. That is called a mount point. I currently cannot test, if using an smb:// URL in the preferences for the sketchbook location would work. So please test that first. When you have confirmed that this doesn't work (what I would guess so), then I will write an answer describing the mount solution

Arduino IDE can use libraries only from 3 locations.

libraries folder in sketchbook folder
libraries folder of selected board's platform
libraries folder in IDE installation folder (only IDE 1, not IDE 2)

There is no option to configure other paths and absolute or relative paths don't work in #include directive with the Arduino build process.
The only way to use libraries from a different location is to link with means of the operating system the folder with the library into one of the searched locations.

and question about how to link local or remote folders is off-topic on Arduino SE. you can ask it on other Stack Exchange sites. https://askubuntu.com/, https://unix.stackexchange.com/, https://superuser.com

Thanks, that is all I have been able to do. It does work with "libraries" in the sketch folder but I did not know I could add a libraries folder in the sketch folder, that is a great help. A real big thanks:-)

@Gil I am sure there is a libraries folder in your sketchbook folder. Arduino IDE installs libraries there too. libraries folder in the sketch folder will not work.

You are correct there is and many times I do not want to use them. There are no libraries in my other "sketchbook" folders (I have several with different names) other then the one the IDE created. I like to put the 'hardware' libraries in the actual sketch folder such as "LiquidCrystal_I2C.h" ,as many times older program files will not compile because of library changes that have occured. Many of the sketches are on the server and compile just fine from several different machines with the library in the same folder as the .ino file.

There are files such as home.h which has definitions for all the hardware, address etc in the home automation system. I only one one copy. I can include it from anywhere on a single machine but not the server.

@Gil home.h can be a library too

You are Correct now you know the problem, how to keep it in one place for several different computers where the only common thread is the server which they all use. Currently I keep it in one location and copy it to the others, very prone to errors. Thanks for the help.

@Gil why not just have the sketchbook folder on a shared network drive?

Let us continue this discussion in chat.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Generating a PWM frequency greater than 125 kHz using Arduino Uno

I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
  delayMicroseconds(900);
}

Update
On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.
My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.
Second sketch:
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output (but cro measures only 125 kHz)
   TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
   TCCR2B = _BV(WGM22) | _BV(CS20);
   OCR2A = 63;
   OCR2B = 0;

  // Set up the 8 MHz output
   TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
   TCCR0B = _BV(WGM02) | _BV(CS00);
   OCR0A = 1;
   OCR0B = 0;

  // Make the 250 kHz rolling
  while (1) {
    _delay_us(5);
    if (OCR2B < 63)
      OCR2B += 5;
    else
      OCR2B = 0;
  }
}

The rolling part made it difficult to see on my scope, getting rid of that and setting OCR2B to 30 I seem to get a 250Khz waveform. Strange.

I made it and it works, what i noticed is that there is no 0 % duty cicle available. How can i make 0 % duty cicle?

It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM

I fully agree with your advice, but I would consider this kind of timer programming perfectly within the "normal Arduino capabilities".

microtherion, what I meant was it's outside the "Arduino language" set of functions that will work across many varients of AVR (such as delay, digitalWrite etc.) and instead delving into registers that will likely be specific to a given AVR chip.

My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

According to my measurements, it is. Using this slightly modified version of your code:
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5 µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output
  TCCR2A = bit(COM2A1) | bit(COM2B1) | bit(WGM21) | bit(WGM20);
  TCCR2B = bit(WGM22) | bit(CS20);
  OCR2A = 63;
  OCR2B = 31;

  // Set up the 8 MHz output
  TCCR0A = bit(COM0A1) | bit(COM0B1) | bit(WGM01) | bit(WGM00);
  TCCR0B = bit(WGM02) | bit(CS00);
  OCR0A = 1;
  OCR0B = 0;
}

I get the predicted 8 MHz output on pin 5:

And the 250 kHz output on pin 3:

To your original question: You can reduce the delay, but there's a limit to how small the delay can be.
Two reasons: Firstly, the loop() function does have some overhead, and secondly the code that you write takes time to execute. This is why the hardware PWM timer is valuable - it generates the pulses without much software intervention.

I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation).

This is really just to add to Nick's answer...
(To understand what's going on, you need to refer to the datasheet. Based on your questions, I'm assuming you haven't stared at it long enough.)
In the first case: 125 kHz.
I am not sure if you're aware, but you're using a special mode of "Fast PWM" which is slightly different from the analogWrite() provided in Arduino.
In this mode, your PWM period is determined by the time it takes your timer counter to match the value in OCR2A register. This means that with a 16 MHz clock, and your output is toggled at a rate of 16 MHz/63 = 250 kHz (roughly).
So far so good, but what does the CRO see? The CRO considers a period to be made up of both high and low signal. It takes TWO 250 kHz cycles to toggle the signal up and down. Hence, the reading shows 125 kHz.
As to why the rolling would make your reading difficult: Think what kind of wave will appear when OCR0B = 0. ;-)
Case 2: 8 MHz
The same applies in the seccond case, and you should expect a 16 MHz cycle that toggles the signal up and down (which gives a 8 MHz reading on the CRO). As to why you are getting 1.6 MHz - that's an odd case. Can you post your CRO reading?

The CRO considers a period to be made up of both high and low signal. - indeed. The original code had such a short pulse that a scope might have interpreted each pulse as half a period, and thus halved the reported frequency. It might have missed the very short on cycle, which is why I adjusted the duty cycle up to 50%.

Yes, you can reduce the delay.
From the documentation:

This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times.

Note that, there are a few cycles between the delays, so as you get shorter timeperiods, you will get less and less accuracy.
You could hand-code the delay. I would imagine you could get up to 1 MHz, but with little control over the duty cycle (at that frequency).You would need to disable interrupts, and you could do nothing else at all.
If you want still more, you could set a fuse on the ATmega, and get your native clock speed out on of pin 14 CKO (this shows up as digital pin 8 on the Arduino board) - I would expect a 50% duty cycle; you will have NO control over - you can't switch it on or off, or affect the duty cycle. It can be used to run multiple chips off the same clock.


text:
Powering Arduino with car batteries
Presumably, one powers an Arduino board with car batteries for long-term operation away from the power grid.
How can this be done, and what are the most (1) economic, and (2) reliable ways to do this? Specifically, do any additional risks to short the board with an extraneous discharge exist?

car batteries are 12.5V most arduinos can take 12.5V, add a fuse/surge protector and you're set

Auto batteries are 13.8v optimal, but the actual voltage can vary on its charge condition, physical condition, and power load. While the built-in regulator on most Arduino boards can step this down, it may result in high temperatures (if no heatsink on the on-board regulator); and the electrical noise from the vehicle ignition/devices may cause havoc on data transfers to/from the Ardiuno. A suitably rated buck converter with appropriate filtering would probable be the best choice.

@ratchetfreak I agree with Ron. It'll probably overheat, especially in the summer.

@Ron I agree. One thing to note: IIRC the onboard Uno regulator has some sort of heat sink build into the PCB that's designed to cool it from beneath.

Use a switching regulator such as the LM2596. You can get a ready board from eBay for about US$1.

Just set the output voltage to 5 V and feed the Vcc input of Arduino; this bypasses the onboard regulator.
The benefit is that unlike the linear onboard regulator, a switching regulator is very efficient which means less consumption and less generated heat on the regulator. An additional benefit is that it can withstand a higher input voltage (about 35 V for the specified regulator), just in case the circuit is used in a vehicle that has 24 V batteries.
The regulator has already several protections like for short circuiting, overheating, etc.

10 for 11$ right now on eBay. Sounds good to me.

@0xF2 You can get single ones for $0.99 so don't fall for than "cheap" ten piece package

While a better idea than a linear regulator, bear in mind that LM2596 switchers have a quiescent current of around 5ma (possibly more in a given implementation) which is a many times the power consumption of a sleeping or even slowly clocked ATmega.

I'm a big fan of USB car chargers for things like this, or USB buck converter boards that you get from ebay.

Can you please elaborate a bit more about how to attach one of the two or how they work/what they do?

A usb car charger normally has a bullet connector (thats what I have always called it) that goes into the cigarette lighter (12v accessory) socket on the car.  And it converts it to 5v and you can plug in a usb phone charger or in this case Arduino cable.

"Practical Arduino book" has a very interesting circuit for this purpose: http://www.practicalarduino.com/projects/vehicle-telemetry-platform
Here is how I've recreated it:

It uses LM2940CT and huge electrolytic cap - even if supply voltage drops, you'll have about a second to shut down your Arduino gracefully (close files on SD properly, and so on).
"Arduino Cookbook" (2nd ed.) has a chapter with examples on how to reduce Arduino's power consumption to absolute minimum - have a look at it, too.

A linear regulator is a poor choice - between this and the one on the Arduino itself, over half of the consumed energy will simply be wasted as heat.  All that is really being accomplished here is (possibly) some input protection and moving some of the heat dissipation off board rather than concentrating it all in the on-board regulator.

There is also the higher-end Akafugu breadboard power supply - takes input from 7V all the way to 35V, but costs 11$ apiece in the bargain.

Akafugu

Two more options - battery pack with convenient pre-made screw holes for Arduino, Raspberry.PI, and Beagle Board:

Smart Power Base
Kicking it up a notch - using a cordless drill's 18V battery.  The project is meant for R.PI, but it would work just as well on Arduino, as the power supply is USB

Portable PI Power

images are broken

Standard car batteries are 12.6 volts there are 6 2.1V cells.  AGM batteries (i.e. Optima batteries, some interstates, and many other brands make AGM), in my experience with AGM batteries they are around 12.8 volts (I do not know the technical voltage).  Without the car running you do not need to worry about voltage spikes AS LONG AS THE WIRES TO AND FROM THE BATTERY ARE SHORT.  When the car is running the serpentine belt turns the alternator which is an AC generator.  The alternator is connected to a rectifier to change it back to DC and the unit has a voltage regulator.  When the car is running the alternator runs the electrical system and charges the battery.  When you connect to the battery while the car is running you are actually connected to the alternator.  When connected to the alternator there is a ton of electrical noise, voltage spikes, etc.
I have always had success connecting straight from the battery to the Arduino through its barrel jack connector, I have not tried any analog read function when the car is running.  On the Arduino website it recommends 7-12V, however the limits (as listed on the Arduino website below the recommended) are 6-20. I have actually experienced problems with lower input voltages.  If you feel uncomfortable just buy a 5 volt regulator and power through the usb.


text:
How cold or hot can my Arduino Uno get?
The Arduino Uno Page doesn't say the temperatures that it can operate in. I'm thinking about placing it outdoors. How can I make sure my Arduino Uno is safe in weather that can reach -20 to 105 degrees Fahrenheit? (-26 to 40 degrees Celsius).

Importantly, have you considered that the temperatures quoted in weather reports is a shade air temperature? If you place an Arduino in the sun, the temperature according to the weather report might be 40ºC, the board could get up to 80,100 or even 120ºC.

@Cybergibbons Most projects outdoors would be placed in an enclosure that doesn't allow sunlight.

How does an enclosure stop sunlight? The enclosure will get hot instead of the board, but you can get extreme temperatures.

@Cybergibbons It would still help and serve as insulation as long as it wasn't opaque. For my situation though, it's in a garage.

so what is the conclusion? is Raspberry pi suitbale or arduino at such high temperatures?

It's not that big of deal. The ATmega 328p datasheet states this:

Temperature range: -40 to 85 degrees celsius.

The same goes for the USB chip on the Uno (ATmega 16u2 for UNO R3).
That's inside your limits. It probably could go a bit colder than mentioned, but it'll shorten the length of the board a little bit.
However, there are some things that may go wrong:

EEPROM might not be stored as long in extreme temperatures. Keep this in mind if you're storing critical data.
The voltage regulator may not perform as well in hot conditions
The crystal oscillator may not produce exact values. However, I would imagine that a few hertz more or less wouldn't affect a 16 MHz processor. The tolerance is actually a little less than 1%. You may have some issues with serial (baud rate not correct). I would look into any communications like I2C also. (I don't know exactly how the clock line works... it might be fine for I2C.)
Resistors/capacitors may not produce the exact values. I'd imagine that the tolerance won't be more than 8% on resistors: most resistors are rated at 5% for normal temperatures. It does depend on the manufacturer. Capacitors do have a bigger tolerance, but their main purpose is to "smooth" a signal.
Extreme cooling/warming may cause minor expansion problems. (Note: it's fine once in a while, but not on an hourly basis of dropping 30 degrees.)
Other components (LCDs, etc.) should be kept in mind also when looking at the viability of keeping it outdoors.

So as long as all the other components not on the board will happily run in the temperatures that you need, you should be fine. Also, as with all engineering, values often have added "padding" built in. (i.e. 5% tolerance is often 3-4%, maximum 12V it can run on 12.5V, etc.)*
*What I mean by that is your Arduino won't explode when it's -41 degrees C. It's not great for it, but most likely you should be fine as long is it isn't a regular occurrence.

Values from datasheets commonly mentioned under "Absolute maximum" are absolute maximum, there is no engineering tolerance there. The manufacturer will not guarantee operation outside those boundaries and anything can happen if you do operate the device outside them. You may be lucky, but why wouldn't they mention the higher spec in the datasheet? Wider spec means wider possible application than competing components and possibly more revenue.

Capacitors vary a lot more then 8%, particularly if they're a cheaper tempco dielectric. Y5V/Z5U are specified to -22 % to +56 % over the range of 10 °C to 55 °C, and they're probably only 20% accurate parts to begin with (precision capacitors are expensive, and why bother when it's for decoupling). Also, the Uno uses a resonator, not a crystal (PN: CSTCE16MOV53-R0), which  has ±0.5% initial accuracy, and ±0.3% over -20 to +80°C. While the ATmega328P can operate up to 20 Mhz, this can potentially cause baud-rate error issues.

Probably the biggest issue with cold temperatures is the fact that almost all battery chemistries completely crap out in the cold. Similar problems are also likely to happen with the electrolytic capacitors, which are likely only 0°-85° parts.

@jippie All I'm saying is that going -41 degrees isn't going to kill your chip. It's not great for it, but if you go only a few degrees under specs a few times a year, it should be fine. I'll clarify my answer.

@FakeName Most projects out in the cold [for capacitors] won't need that much precision, especially for the main use on the Arduino. However, you are right. I'll add that to my answer. Also for the batteries, that is included under the other components not on the board will happily run in the temperatures. However, you are right.

Like everyone mentions, as long as you're in the shade, hot temperature probably doesn't matter too much as it's within the limits of the components.
I'm more worried about condensation in the mornings.  Water vapors will condense on electronics just like it does on grass.  You could try electrical epoxy to cover the circuit.  The Arduino doesn't run very hot, so the epoxy doesn't do much in terms of preventing it from cooling down.  But epoxy does keep water vapor condensation from being a problem.

You can spray or brush the board with Conformal Coating to prevent moisture problems.  Cover any connector openings first to prevent contact problems. https://www.mouser.com/Search/Refine.aspx?Keyword=conformal+coating

For hot temperature, just follow the datasheet.
For low temperature, I remember someone last year trying to overclock a UNO with liquid nitrogen so I guess you won't ever meet any problems with low temps :-)
In his blog, that person shows that he could run his UNO at 65 MHz by reducing temperature to -196°C.
Of course, the process was more complex than just reducing the temperature and checking what happens: a lot of improvements were performed on the board.
The blog explains very well how various components can react to cryogenic temperatures; the major issues seemed to be capacitors which capacitance dramatically reduces under low temperatures.

Wow. 65 MHz on the Uno.

If you must place your device outside, I would suggest a diecast box. The main heat generating component is probably the regulator (Think about it - at 12V, the reg drops 7V, where the micro runs on 5V or maybe 3V3). So running the lowest voltage into the arduino is recommended, I think its good to 7V (for a 5V unit). If you can connect a heat pathway from the chip surface to the case, good (Use heavy guage - at least 2mm thick). Take care you do not connect to the reg tab - use mica or thin mylar and heatsink paste (Avoid galvanic interations). Normal finned heatsinks on the outside of the box actually do the job of shedding heat to the atmosphere. This whole thing should be in a slatted wooden white painted container (A stevenson screen) so direct sun (and rain/dew) dont hit the containing box.
This would be a solution for extreme environments.
Remember that any heat build from the board must get to the box internal environment - using trapped air you get a very poor thermal contact. Then it has to get through the box and into the air again.
Dont forget that current sinks you use on the chip generate some (small) heat in the process.

I agree with the advice to read the data sheets, but here is a personal answer to the question.
I installed a Raspberry Pi in an enclosure in which the existing Arduino survived last summer.
Even though they have the same overall temperature limits (except the communications section) it was the Pi that stopped working first.
The good news is that bringing it inside it booted right back up.
The temp/humidity went up to 140 F (like a hot car in Phoenix).
So in the end, the data sheet was right in terms of survival.  But I would suggest a more conservative approach, such as placing them into a white-painted enclosure to minimize the effects of the sun.
After removing the pi, the Arduino woke up like nothing happened, still outside.
These things are very resilient.


text:
Arduino fast start not working properly
I have an Arduino 328p (custom) and I can program it using a FTDI header.
However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.
If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.
What could be the cause of this behavior?
Can it be an issue with optiboot fast start?
PS: FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the MCP1703 regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
PPS: The Arduino is running at 16MHz

I didn't think arduino would run @16MHz on 3.3V

@JaromandaX Just to be sure, I switched the arduino to 8Mhz with the internal oscillator and the results are the same. Fuse settings are: -Uefuse:w:0xFD:m -Uhfuse:w:0xDC:m -Ulfuse:w:0xE2:m

If you provide a higher voltage to the reset pin, you might make it enter high-voltage-programming-mode.

@Gerben        I thought the AVRs only went into HV mode if the voltage was over 12V, I think if it worked the other way round it would cause issues.

The reason for this issue is to do with SPI.
Basically in my custom arduino I have a 4Mbit flash and it communicates over SPI.
It seems that when the RST pin is connected it also automatically initializes the SPI protocol.
When the arduino is powered from RAW + GND directly from an external power source you need to initialize SPI manually.
In your sketch you need to:
    #include <SPI.h>

    void setup() {
        SPI.begin(); // this needs to be invoked before any SPI device gets initialized

        // initialize and use SPI devices
    }

You need to initialize the SPI before use regardless.


text:
Why is Serial.begin(9600) interfering with my multiplexor functioning?
I have an Uno hooked up to a sparkfun 8 channel multiplexer (https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide). I have it wired up like this:
Arduino0 --> S0
Arduino1 --> S1
Arduino2 --> S2
Arduino3 --> Z
Arduino 5v --> VCC
Arduino GND --> GND

I'm running a simple code to blink two different LED's, one attached to Y7, and one attached to Y6.
//Define MUX pins
int pin0 = 0;
int pin1 = 1;
int pin2 = 2;
int zOutPut1 = 3;

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

    // Set controll pins
    pinMode(pin0, OUTPUT);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(zOutPut1, OUTPUT);
}

void loop() {
    samplerStarter();
}

void samplerStarter() {
    sample(1); // Takes sample for 5 min
    delay(1000);
    sample(2);
    delay(1000);
}

void sample(int noidNum){
    //MUX 1
    if(noidNum == 1) {
        digitalWrite(pin0, HIGH);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y7
    }
    else if (noidNum == 2) {
        digitalWrite(pin0, LOW);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y6
    }
    delay(500);

    //Set everythign back to Low
    digitalWrite(pin0, LOW);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(zOutPut1, LOW);

    delay(500);
}

But when I run this code, only the first LED attached to Y7 blinks. But if I remove the Serial.begin(9600) line:
//Serial.begin(9600);

Everything works fine. So I have no idea why this one line dealing with Serial Communication is affecting my multiplexor.

(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.
With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.
Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.


text:
Comparing time_t values within an if statement
I am using an UNO with a RTC to control a light board. I'm using a simple control structure to decide when to turn things off and on. It's my understanding that a time_t value is just a number (number of seconds since 1970), and that I should be able to compare these time_t values as I would any integer- in this case comparing two time_t values to see which one is larger.
#include <Wire.h> // Needed for I2C protocol (RTC uses I2C)
#include "RTClib.h" //Good Library for RTC functions
#include <Time.h> // Needed for time_t variables and tmElements

RTC_DS3231 rtcVM; // From the RTClib library for use with an DS3231 RTC. Creates an object called rtcVM

DateTime nowVM; // Declare a Date Time object that will be used to hold the current time
time_t nowUniVM;// Declare a time_t object (Unix time) which is a float value (good for straight comparisons) to hold current time
time_t starter;// Declare a time_t object for the start time (time_t)
tmElements_t MagStart; // Declare a tmElement_t object to manually input the start Time

//FILL OUT START TIME AND DATE FOR FIRST SAMPLE (NO LEADIN ZEROS--"8" not "08")
byte startHour = 17;
byte startMin = 58;
byte startSec = 0;

byte startDay = 12;
byte startMonth = 10;
int twoDigYear = 16; // Enter last two digits of year

byte startYear = twoDigYear + 30 ; // This is a little confusing. This is the year offset from 1970 (AKA 2016 should be input as 46. Or just add 30 to last two digits).

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

  Wire.begin();
  rtcVM.begin();

  // Creates a tmElement by putting together all of Maggies Start Time and Dates
  MagStart.Hour=startHour;
  MagStart.Minute = startMin;
  MagStart.Second = startSec;
  MagStart.Day = startDay;
  MagStart.Month = startMonth;
  MagStart.Year = startYear;

  // Takes the tmElement and converts it to a time_t variable. Which can now be compared to the current (now) unix time
  starter = makeTime(MagStart);

  // Start message
  Serial.println("Start time is: ");
  Serial.print(hour(starter));
  Serial.print(":");
  Serial.print(minute(starter));
  Serial.print(":");
  Serial.print(second(starter));
  Serial.print(" ");
  Serial.print(month(starter));
  Serial.print("/");
  Serial.print(day(starter));
  Serial.print("/");
  Serial.println(year(starter));
  Serial.println("****************************");
}

void loop() {
  nowVM = rtcVM.now(); // get current time and hold in "nowVM"
  time_t nowUniVM = nowVM.unixtime(); // Calculate current time in Unix time

  samplerStarter();

  // RTC Get and Display
  DateTime now = rtcVM.now();// Getting the current Time and storing it into a DateTime object

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  delay(3000);

  //Use these 2 to check the numerical values for comparisons
  Serial.println(starter);
  Serial.println(nowUniVM);
}

void samplerStarter() {
  if (starter < nowUniVM) {
    //if (1 < 2) {
    Serial.println("Start Time");
   }
}

I've included my entire test code here, but it's the last if statement that puzzles me. The idea behind that last statement is that it should print out "Start Time" when the start time is reached. The statement works if I compare something simple like (1 < 2), and the statement gets printed. So I assumed it would work if I did the same thing but with two different time_t values.
But if I input an appropriate start time under the "Fill Out Start Time" section, the print statement is not triggered when the start time comes to pass (AKA- when the start time (starter) is less than the current time (nowUniVM).
Is there something about time_t values that does not allow them to be compared like this? Or is there something in the way I'm creating my values that is messing up the comparisons?
My output to the serial monitor shows the actual time_t values, and they look like normal integers to me when they print out, so I'm not sure whats going on here. Why doesn't that last if statement print out when the start time is reached?

Please edit your question and state what error, if any, you are concerned about.   As is, your question provides some general background but it doesn't say what is wrong, or what is different from what you expected.

Thanks for the feedback, I made a few edits to further explain what I'm looking for.

Where did you get this Time.h?

Version 1.5 from the IDE Library downloader

You have two variables called nowUniVM. The fist one is a global
declared at the top of your program, and implicitly initialized to zero
by the compiler. Since you never update it, it is always zero. The
second one is local to loop(): it shadows the global variable inside
loop() and is updated periodically.
The function samplerStarter() only sees the global variable, which is
zero. Thus, the comparison boils down to
if (starter < 0)

But since time_t is an unsigned type, the test can never be
true.

Scope! Bad practice on my part

Though a quick question on scope in this matter. I defined the "starter" variable in my "setup" function. How is it that the "void loop" and "sampler starter" functions can see this "starter" variable, if void functions don't return any values?

You defined starter at global scope. You initialized it in setup(), which is perfectly fine.


text:
MFRC522 minor problems
I'm working on a small project for a presentation. My goal is to read the UID of multiple Mifare Classic cards and compare it to a hardcoded list for different actions. All is well (the reading and comparing part that is) but 2 small problems that I have encountered are:

The first (maybe up to three, since the reader is a little bit on the fast side) read after uploading my code will return a UID of just 0s and a wrong PICC type.
After reading a PICC and then trying to read another, the reader prints the UID / PICC Type of the reader before, which is kinda not helpful when trying to light LEDs based on UID.

Here is my sketch:
/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
  String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

Can you please elaborate on - "the reader prints the UID / PICC Type of the reader before"? It looks like you are doing that in your code, not the reader

/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
// String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
// byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();
     // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
 String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
 byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}

An answer with just code, without any explanation is not sufficient! Could you please clarify what you have changed in OP source code?


text:
How to detect high/low signal from a DC servo motor using arduino?
I am a newbie to Arduino.
What I am going to do is to change my roll to roll printer to flatbed printer.
Rather using print roller, I decided to move the bed from a stepper motor.I know how to run the stepper motor for specific distance using arduino.
So I need to cheat printer to think that its roller is working and media is going through it.But actually what I am going to do is to monitor the printer motor running or not from arduino input and if the printer motor is running stepper motor will turn or if motor stops stepper motor must stop.
What my problem is how can I read that the dc servo motor status? How would I need to wire arduino input to servo motor to get the status.
Please show me some light on this.Sorry if this is a newbie question.
Thank you.

Any particular servo?

@IgnacioVazquez-Abrams sorry for posting external link.servo motor like this http://www.aliexpress.com/item/Hot-leadshine-dc-servo-motor-100W-24V-5-9A-2500r-min/862541888.html

Do you have the datasheet for it?

No I haven't.Can't we just check whether power comes or not?

How you will run the servo? With arduino? if so you can do software check

Is it a servo or a regular dc-motor? Does it have 2 wires, or 3?

@Martynas No it is run by my printer driver.when the printer is working I just need to hack the motor line get whether the motor is running or not.If motor runs I need to run stepper motor from arduino

This may not work very well. If it is an actual servo motor, it will run to close the error and achieve position, while your stepper just gets a "step".   You might be able to detect each "pulse" of movement and advance a line, but the simplest solution would be to use that motor for your flatbed mechanism.  If you can't do that, you could consider putting an encoder wheel on the motor and driving your stepper from those signals, either with some clever logic or a micro controller - effectively "electronic gearing"

I would definitely use an Opto-Isolator between the motor and the Arduino for these reasons.
You will have a problems with the grounds as the motor reverses.
The 24V supply.  If you get something slightly wrong then it will take out the Arduino and the PC connected to it.
The motor will generate large voltage spikes( circa 50..300Volts) under certain condions.  The Arduino and the PC connected to it will complain, but not for long!

Thanks alot for your answer.Since I am new to electronics I don't know how to connect those between arduino and motor.Can You explain it little bit deeper?

This would normally be handled with a series resistor and a diode clamp, potentially a bidirectional one.  That lets the Arduino sit at the ground potential of the motor driver and determine direction by watching the two sides of the motor.

Do you need to check if it is stalled? Or simply running?
Either way, you could check the voltage with an analogue input, compare against a threshold (empirically set) & use that. Take the voltage reading from the non-commoned side of the motor, after any driver circuit.
If you want stalled, a small resistance would help, if just running then you could get away with a digital input.
If the voltages aren't matched then a resistance divider chain would be necessary.

Thanks for the answer.No I just Need to check motor running or not.


text:
Where can I see the output of printf?
I would like to know where I can see the output when I use the command printf. I am programming using the Arduino interface.
Update
I'll add a few lines of code for better understanding:
#include <stdio.h>

int main(void)
{
    printf("Hello World");

    return 0;
}

your goal is to print something out in your console of the Arduino IDE?

there is no main in Arduino. You have the setup for initialization and the loop for the continuing loop

@letsjak there is a main in Arduino, but it is hidden http://www.seeedstudio.com/wiki/Where_is_Main_Function

If you're working with the standard Arduino environment and libraries then printf() won't display anything anywhere. The reason is that microcontrollers could be connected to any number of different output/communication devices in any way. stdio would have no idea how or where to send the data.
The most common approach to outputting text from an Arduino (particularly during development) is to send it to the primary UART port using Serial.begin() and Serial.print(). If the Arduino is connected to your computer via USB then the Arduino IDE's serial monitor should display the result.
If you really want to use printf() though then it is possible to make it work (or implement similar functionality). A full explanation is on this page:

http://playground.arduino.cc/Main/Printf

In setup(), start serial and choose your speed:
Serial.begin(9600);

Wherever you want to write to serial:
Serial.write("write this");

Wherever you want a newline:
Serial.println();

example
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.write("Hello World");

}

void loop() {
  // put your main code here, to run repeatedly:

}

my question is actually where am I printing if I don't define Serial in void setup() and just type printf in void loop()?

@ironzionlion if you read the printf documentation.. you will find it...

@ironzionlion it's an LCD... tadaaaaaaa http://playground.arduino.cc/Main/Printf


text:
Where do serialport names come from?
I'm currently writing a tool that automatically detects connected arduinos and provides a one-button solution for flashing new firmware.
I've got a couple of arduinos at home (Diecimilla, Uno R3 SMD and some nanos from china) and each type presents with a different serial port name.
Questions

Can someone explain where these port names come from?
Can I assume that /dev/cu.usbserial-A9UPDRZB is, atleast in most cases, an arduino nano?
Are there other ways to identify the type of the board?
Is the name of the serial port some kind of hash generated from informations retrieved from the device?

They come from your OS.

You might get a lot of useful information from this question https://arduino.stackexchange.com/questions/3680/in-linux-how-to-identify-multiple-arduinos-connected-over-usb

Thanks, but this doesn't really answer my questions.

It does tell you where you can find them though.

It doesn't. It tells me where to get more information about the connected hardware. But that doesn't answer the questions about how the names are generated.

http://apple.stackexchange.com/

That answer does tell you how to make linux create names you want, or, if you prefer, to invoke programs when you plug in specific devices. You might want to indicate which OS you want to use, of course.

You cannot assume anything about serial port names. It's a choice of the operating system, and even if you find the algorithm, there's no guarantee it won't change in the future.
As a reference implementation, the Arduino IDE 1.5.x uses VID (Vendor ID) and PID (Product ID) to identify a board.
Because accessing such information depends on the underlying operating system, the IDE uses three strategies: on windows, it runs a program called ListComPorts.exe, on macosx it uses CLI tool /usr/sbin/system_profiler, on linux CLI tool udevadm


text:
What is the physical location of the U1A symbol on Arduino Uno?
I'm trying to find an easy way to allow an Arduino Uno to determine if it's being powered from USB or the DC barrel jack. In this thread, one user recommends wiring the output of the on-board comparator op-amp (U5A pin 1) into the digital input pin.
I couldn't find U5A on the current schematic, but I think he's actually referring to U1A pin 1. Is this correct?
Unfortunately, I'm not sure where on the physical Arduino that device is located. I have one in front of me, and almost none of the parts are labeled on the silk screen. How do I find out where it is? I've googled for Arduino Uno part placement schematics, but all I'm finding are blurry unlabeled low-res images.

The op-amp is a LM358 so you can look at the ICs themselves. Also it's a dual comparator with 8 pins. On my example image below you can see it below the crystal. I can't comment if that's the correct way to sense what you need, but it seems the comparator output should be 1 if there is external power applied. You could check with a multimeter.


text:
Reading a varying voltage into Arduino
Using an Arduino Nano and a current transformer  (CT), I'm trying to sense the current flowing through a 120 V 60 Hz line.
Circuit
CT outputs 0-1 V according to its specifications. This output is biased AREF/2 = 2.5 V.

analogRead Values
The x-axis represents the index number of the ADC sample, while the y-axis represent the ADC value (0-1024). Sampling rate is about 9 kHz. Peak-to-peak difference is about 1026 samples.

Is this waveform what you would expect from the CT? Why are there regions where the values are flat, rather than varying continuously?
Furthermore, if we look at the curve part of the plot, why is Arduino reading values both above 512 and below 512 alternately? It reads a value above 512, then a value below 512, then a value above 512 and so on.
Time taken for an analogRead was measured to be 110 microseconds for my setup and there are 1026 samples between the waveform peaks. That means there will be about 9 peaks in 1 second, although I would expect 60 peaks since we are sensing a 60 Hz line. What do you make out of this? There's a capacitor, C1, in the circuit, would it have anything to do with this?
Are these analogRead values suitable to be used to calculate the RMS voltage, and hence the RMS current passing through the wire being sensed? The final goal of this is to calculate the power usage after determining the RMS current flowing through the wire.
Sketch used to get values for plot
void setup() {
    Serial.begin(9600);
}

void loop() {
   double sensorValue = analogRead(1);
   Serial.println(sensorValue)
}

Actual analogRead data points in the bump regions
487
534
487
535
488
537
484
536
487
538
486
536
484
540
484
539
485
540
483
540
484
541
481
539
481
540
484
540
480
543
484
539
481
540
484
541
486
542
485
538
485
538
488
535
489
534
491
530
491
529
493
531
492
526
498
526
499
524
499
520
503
518
502
518
507

Plot of analogRead values
The analogRead values are now stored in a buffer before being transmitted over Serial. There are now 55 ADC datapoints making up 1 period. Considering the analogRead time is 110 µs, each cycle takes 6.05 ms, giving us a frequency of 165 Hz! What may have gone wrong?

void loop() {
    double sensorValue = analogRead(1);
    char buf[32];

    dtostrf(sensorValue, 8, 2, buf);
    value = buf;

    if (stop == 0) {
        if (i < 10000) {
            message += ',';
            message += value;
            i++;
        }
        else {
            stop = 1;
            Serial.println(message);
        }
    }
}

Can you post your code? This doesn't look right at all. When you say "Assuming that 100ms passes", why do we assume that?

@Cybergibbons Posted the code used to generate values for the plot. Sorry, I've just measured the time taken for an analogRead() and found it to be 110 microseconds. Updated the question.

What is the load you are using for the mains. Ideally you want something fairly stable like an incandescent bulb. If you have something complex like a laptop switchmode power supply which may have a varying load you might expect a complex result.

The bulk of the time in the loop will be spent sending serial at 9600bps. You will only shift 960 char/s i.e. each reading takes 4ms.

@Salixalba The load is a desktop computer with a switching power supply. I will try measuring a different load, such as a heater.

Looking at a plot of the data, you might be seeing beat frequency from two very close frequencies possibly 60Hz and 61Hz.

@Cybergibbons Thanks for the hint. Now I'm storing the analogRead values in a buffer before sending it over Serial. Updated the question with the new plot. The ferquency is now 165Hz!

@Salixalba Updated question with a plot that's probably more accurate, changed based on suggestion by Cybergibbons. What would the interpretation of the plot be now?

Maybe it is a switch mode device which is drawing current only part of the time. The first 25 ticks no current, then its switched on for 7 tick, off for 25 tick, on for 7 ticks.

It might actually be quite a clever device, timing its on and off states to coincide with the cycles in the mains and balancing things so you get a top half of a cycle and a bottom half of a cycle. In effect its switched so its drawing current 1/5 of the time. Try doing some heavy processing with 100% CPU and see what happens.

A switch mode power supply is a bad place to start. Use a purely resistive load to see if things are working.

Regarding your measurements, I would completely disregard the first set with Serial.println() in the loop. I would exepect the timing of this to be unreliable.
Your second set of data that you captured in a buffer looks correct, but your Frequency Estimation / timing may be wrong. I would invert a Digital Output at each loop iteration. You can measure the frequency of that with a Multimeter and your ADC sample rate would be twice that value.
For a PC or laptop power supply that's quite a common current waveform.
Without effective Power Factor Correction the current signal shown below would be quite typical (source: http://www.nlvocables.com/blog/?p=300)

You will need to calculate RMS values and it would be wise to filter the signal.
Here's an instructable I wrote on how to build and code an Arduino Yun based Electricity Monitor with Cloud Support / Temboo and Google Drive. It should be of some help to you.

Thank you! The CT you've used outputs -1V to 1V. To make use of the 10 bit ADC, will you amplify the SCT output by 2.5 using an opamp? Or set your AREF to 2V and bias your CT signal by 1V

No I did not amplify it or change the Aref.

How could you get this graph plot? With what software?

if you are measuring a resistive load I would say that the burden resistor you have chosen is wrong, there are some cheap CT's on ebay (SCT-013-xxx) that have versions with and without the burden resistors, these work well for their price but you must read the datasheet. the SCT-013-000 requires a 20R resistor to get 1V out with a 100A load, if this resistor is wrong you can get a severely distorted waveform when measuring higher currents (similar to those you have provided), you would expect the signal to distort more the lower the burden resistor value but this is not the case with CT's.