text:
What is better: one sprintf() or multiple strcat() and itoa()?
I was creating Arduino function which sends two int and additional chars between them and at the beginning and end of char array - then print that array to the serial port in almost real time. (For example "X50Y100T".)
I don't want to use String object in Arduino and I found two possible solutions:

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

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

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

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

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

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

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

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

Why do you feel you need to use either method? Neither are needed. Just print the individual parts:
Serial.print('X');
Serial.print(first);
Serial.print('Y');
Serial.print(second);
Serial.println('T');

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

It really does the same thing? Great. If it has the same or better performance I will use this :)

When you send to the serial it all gets put into a circular buffer for sending using interrupts. It makes no sense putting it into your own buffer first to then transfer that buffer to the serial buffer. It's more efficient to just fill the serial buffer directly.

Thanks. It makes sense :) I will use this solution from now. Probably my solutions are better for in-sketch operations.

Here's a method that for some reason uses slightly fewer bytes of flash memory than Majenko's does, while producing the same output:
Add #include <Streaming.h> at the beginning of the program, and replace the five statements shown in Majenko's answer with the following line:
Serial << 'X' << first << 'Y' << second << 'T' << endl;

That is, use the Streaming.h contributed library, which adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it via Streaming5.zip from arduiniana.org.
When the #if-delimited sections in the program shown below are selected individually (by changing two of the three 01's at a time to 0's), I got the following compiled-code and RAM figures, running the program on a Nano, where all three ways appear to give the same output:
      Bytes  Bytes
Alt.  Flash   Ram    Note
 1    2,204   182    Five Serial.print stmts
 2    3,384   190    Using snprintf()
 3    2,176   182    One Streaming stmt

I don't know whether this slight decrease (from 2204 to 2176 bytes of flash) is replicable, but the method probably is worth trying in your situation.
The program:
#include <Streaming.h>
void setup() {
  Serial.begin(115200);
}
void loop() {
  int first=50, second=100;
  //enum { first=50, second=100};
#if 01
  Serial.print('X');
  Serial.print(first);
  Serial.print('Y');
  Serial.print(second);
  Serial.println('T');
#endif
#if 01
  char sendBuffer[16];
  snprintf(sendBuffer, sizeof sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
#endif
#if 01
  Serial << 'X' << first << 'Y' << second << 'T' << endl;
#endif
}

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

Hmm... I've never seen the streaming library. It looks great from both memory and readability point of view. Thanks for your answer :)

Excellent! I wished I have known this long ago.

I'm working on an attiny, and removing all calls to .print and .write, replacing them with << streaming syntax, saved me about 400 bytes. Very useful.

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

Readability
Maintainability
Space efficiency
Time efficiency

There is no universal answer to which of those is the most important. My personal bias is to start with code that is easy to read and obvious in its function. Then if time or space are an issue to start looking for ways to improve.
In your code, you could also do something like this:
  itoa(first, sendBuffer[1], 10);

Which would save you a function call and perhaps some space.
Also keep in mind that the cost of sprintf() in terms of space may get amortized over many uses, so it might not be as bad as it initially seems.

The sprintf() may appear two times in sketch, In this case I'm focusing on memory and performance rather than amount of lines of code. Thanks for your answer.

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

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

I would however, encourage you to use snprintf().  This function differs from sprintf() by taking the maximum buffer size as an argument.  This will help prevent problems with buffer-overruns (i.e.: accidentally putting more data into a string than in can hold)
Sprintf on Arduino does not include support for floating point numbers though.  This is quite a drawback.  One needs to use additionally use dtostrf().
The real takeaway point is this:  Only optimise your program when you need to.  Donald Knuth said: "Premature Optimisation is the root of all evil".


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

The compiled code never cares how you upload it.

My thoughts were that there could be additional code intended for the Atmel16U2 and Programming Port flash method which would have to be removed in this situation.

Nope, just use avrdude to upload it and you are done ;)

But you can also upload it from the IDE with a serial interface of your own; you are not forced to use the 16u2

It depends
This may not have been the answer the question was originally asked, but now it appears to be: it depends on which revision of the Due you have.
The V03 schematics on the website show a 74LVC1G125DCK part designated IC10 that is being used to translate the 5V TXD signal from the ATMega16u2 (being used as a serial transceiver) to the 3.3V logic needed for the ATSAM3X8.  As drawn the TXD line is connected to the buffer/level converter input but it is also connected to its active-low output-enable line.  In effect, they're not just using it to convert logic levels, they are also converting the signal to a kind of open collector signal.  Looking at the ATSAM3X8 datasheet shows that, yes, there is an internal pullup in the pin receiving the signal.
If your Due is of this design, then yes, you can program the chip by attaching a USB->logic-level-serial adapter to D0 and D1 (USART) pins and program using the SAM-BA protocol. You need to make sure you are not sending over the on-board serial transceiver while this is happening so as to not have it wired-ORing its data with your adapter. The ATMega16U2 has code in it that controls the ATSAM3X8's erase pin, as well as reset pin, by request of the PC via serial-over-USB's DTR and RTS.  Since the erase signal is not routed to outside of the Due (on its headers), you would need to use the erase button, barring some modification to the board.
However, not all Due are of this design. Some DUE boards have the output-enable of 74LVC1G125DCK hard-wired active rather than connected to the transceiver TXD; so on these designs it does not behave as open-collector, and the ATMega16u2 serial transceiver is actively driving the line when idle.  This destroys the ability to program the board over UART via pins D0 and D1.  It does however make cleaner rising edges.  Without modifying the board, no, you can't do it with this design.
Identification
So far as I can tell, whether or not your ATMega16U2->ATSAM3X8 connection is open collector/UART-programming-friendly follows the location of the buffer part.  The chip is an SC70 package, a small 5-pin thing that looks a bit like SOT23-5.  If it is located off the ATMega16U2 itself it seems you have a open-collector configuration, again so far as I've been able to tell.  If it is located next to D0, between D0 and the "COMMUNICATION" header, then you have one that drives-high.
If you have a scope, you can put it on D0 and watch the edges generated when you send traffic from the PC over the ATMega16U2 at higher baud rates.  You will either see characteristic open-collector rising edges or you won't and that will answer the question.

source: Stack Exchange

license: 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/

sort: votes


text:
Arduino Uno data logger shield recording nonsense time
I'm using an Arduino Uno with the Adafruit Data Logger Shield powered by a Voltaic 5V 2A battery pack. When writing to an SD card, the time stamp never changes (always reports the same now.unixtime). However, when powered from a laptop, the time stamp is correct and everything seems to be working.
The input voltage from the battery is confirmed to be just over 5V and not substantially lower the the laptop usb port.
Has anyone seen this before? Any ideas?

Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.
You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.

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

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

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


text:
Accelerometer sensor gy-61 convert to m/s2
I have a problem calibrating my GY-61 accelerometer on an Arduino Uno to get values in m/s2.
Analog-reading code:
const int xPin = A5;
const int yPin = A4;
const int zPin = A3;
// ...
void loop() {
   int xRead = analogRead(xPin);
   int yRead = analogRead(yPin);
   int zRead = analogRead(zPin);

   float xData = (((float)xRead - 337.92) / 61.44 * 9.81);

   accData= sqrt((xData*xData)+(yData*yData)+(zData*zData));

xData should show values in m/s2.
What do those values  337.92  and  61.44 mean and how can I calibrate them to get right values?
Values I get (in one position without moving):
xData   yData   zData    accData
-11.16   1.61   -0.79    11.31
-0.79  -11.48    0.01    11.51
-0.47   -0.63  -10.68    10.71

accData should be near 9.81 m/s2, also x or y or z, depending on rotation.

Did you find the solution to this problem ?

I get some answers on other forums, this and this . Second solution is better, but i still get strange readings. So i ordered some new acc sensors for testing, one of them is ADXL 335, which have many libraries and instructions. But still want to figure it out about GY-61.


text:
Can I work with larger numbers than an unsigned long long in Arduino?
I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

You should look up the BigNumber library see if it is suitable for your needs.

But... why do you need them? Usually when someone needs larger numbers then he has probably chosen the wrong algorithm...

I'll check it out.

The entire point of my project is working with large numbers.

There are many ways to use numbers bigger than an unsigned long on Arduino. The right one depends on the application.
Floats and Doubles
floats and doubles types on Arduino can hold exact integers up  2^53. That is a very large number. They are built into the Arduino compiler.
uint64_t
The uint64_t type can hold exact integers up to 2^64. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.
BigNumber (or bc)
The BigNumber type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...
https://github.com/nickgammon/BigNumber
Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find BigNumber compatible functions for things like printing and serializing.


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

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

Can you explain why this would happen? println should already insert two newlines—why do you need two?


text:
How to make 2 LEDs flash in a 5/4 Polyrhythm?
Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.
//Making a 5/4 Polyrhythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

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

void loop() {

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

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

}

Where it is feasible to do so, a problem with a simple ratio like this may be most readily addressed by running something at the least common multiple and acting, or not, on each output as appropriate.  Likely this means you will need an event happening at 20 times the desired repeition rate, which (if you intend the flashes to be visible as such to a human), is not even remotely difficult for an Arduino to handle.  One LED would flash on events 0, 4, 8, 12, and 16, and the other one events 0, 5, 10, and 15...

It is up to you to decide if you want each LED to be one for one 1/20th or something else, for example you could double the rate to 40x and generate distinct events for on and off.

I generally calculate whether the led must be on or off, based on the current time.
//Making a 5/4 Polyrythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

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

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

Thank you very much. Could you explain what the (millis() / 600) %2 means? Is the millis just the millisecond time (from 0 to 600) is modded (%) with 2 and if it comes out odd or even determines if the LED is on?

@JonStapchuck millis() is the number of milliseconds since the board powered on.  This is then divided by 600, and if the result is odd, the LED turns on, otherwise it turns off.

See the comments inside the code.

See https://arduino.stackexchange.com/a/17929/6628 with code like:
const int onTime = 500;
const int measureTime = (int) (60*1000/10);  // 10 BPM, or 1500*4ms/measure
const int off4 = measureTime/4 - onTime;  // take care these don't go negative
const int off5 = measureTime/5 - onTime;  //
unsigned long next5;
unsigned long next4;

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

}


text:
Interleave Assembly and Source for avr-objdump
Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)
Original Makefile
Here's my current Makefile:
PREFIX=avr-
CC=${PREFIX}gcc
OBJCOPY=${PREFIX}objcopy

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

PROG?=atmelice_isp
PORT?=usb

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

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

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

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

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

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

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

First make sure you add -g to all your compilation commands.
Then you can run avr-objdump -S build/spi.elf (for instance).
Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.
Here is a makefile I use:
PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

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

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

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

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

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

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

That is some serious make-fu and I'm currently reading "GNU Make" before I come back to it.

Nothing that amazing really. It's mostly variable substitution and the use of the fact that Make already knows how to compile files as long as you set the right program and the flags to use with it. No need to specify each and every fole manually, just the list of objrct files and Make works the rest out for itself.

I'm back, it works great! Only problem is that it spits objects into the source folder; I want the objects to go into the build folder.

For that you're going to need to add a .c.o recipe possibly. Using separate folders like that gets a little tricky with make.

Nailed it with a few filename functions, thank you so much!


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

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

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

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

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

When I try to compile this I get:
error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

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

EDIT

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

#include <Arduino.h>

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

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

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

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

Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.
You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.
There is a Menu system in Cosa. Please see the example sketch. This implementation follows the MVC design pattern.
Cheers!

That was what I was missing, I forgot that in order to pass a reference like I wanted it needed to be static. I knew it was something simple. Thanks for getting me on the right track, unfortunately I can not figure out how to get the Cosa libraries compiling correctly in eclipse.

Your system works in pure C too:
typedef struct _MenuItem
{
    const char *label; // or String if you like
    void (*callback)();
} MenuItem;

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

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

    ... # more menu definitions with callbacks
}

void loop()
{
    unsigned int user_menu_selection;

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

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

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

In pure C I would use __flash const instead of PROGMEM: the compiler knows how to properly dereference a __flash pointer, whereas with PROGMEM you have to explicitly call one of the pgm_read_*() functions.

A pointer to a member instance function is possible:
void (Some_class::*Some_fnc_ptr)();

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

I know that you've resolved your dilemma, but I just wanted to show you a trick: personally, I hate the pointer-to-function mechanism that everyone uses, when there's a perfectly good alternative.
Here's a function that takes an int and returns a char:
char SomeFn(int i);

Here's a typedef describing that function as a type:
typedef char Fn(int i);

Looks pretty similar, huh? What's the point? Now that you've got a type, you can use that instead:
void SetCallback(Fn *fn);

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

What could be easier? If SomeFn was a static member of a class, you could just as easily use that:
SetCallback(&Class::SomeFn);


text:
Trinket: Battery + USB at the same time?
Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?
I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.
If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.

So that worked. Unfortunately I did not really achieve my goal entirely as the ATTiny on the trinket seems only to enter the bootloader when the controller is powerless and the USB-connection to it is made. Not after a Reset. So back to square 1 :-)


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

This sounds like an X-Y problem.  Can you give some background on why you want to turn off the 5V pin?  There may be a better way to accomplish your goal.

Can you provide a schematic which will illustrate your project better? Isn't the 5V pin hardwired to be "on" permanently.? You could add an external transistor to switch the circuit connected to the 5V pin, but I don't thin that you can switch the pin on the board itself. I might be wrong though.

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

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

There isn't programmatic control of the 5V pin, it is hard wired to the USB or the output of the Vin Voltage regulator.
You might try something from How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino? to control the low side of the external device.  If you need high-side control, maybe an opto-isolator would be a good solution.

If I'm understanding you correctly, you want a 5 V output that is under programatic control. Do you know how much power you want to pull from the pin?
If the demand is fairly low, you could use one of the digital pins directly – they will supply about 40 mA on an "official" Arduino.
If you need more power, then you could use the pin to switch an external device such as a transistor or a relay.

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


text:
max current while using a shift register
In arduino's official page about ShiftOut https://www.arduino.cc/en/Tutorial/ShiftOut, a drawing with two 74HC595 powered by the arduino board, is displayed.
Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.
So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?
Thank you

BTW, there is also a voltage drop across each LED, so the voltage across each 220R is not 5V, it is 5V-1.5V (or so).  Different LEDs have different "forward voltage" drops.  So the current is actually (5-1.5)/220 * 16 = 0.254A.

0.20A is not the maximum current for an Arduino device.  0.20A is the maximum current for the chip that is on the Arduino.  Thus it is only relevant to devices that are directly connected to the Arduino's IO pins (that connect direct to the chip).
The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board.  Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.

You are right, 0.2A is the maximum current of the ATMega328 chip. Nevertheless, if someone power let's say four shift registers which drive LEDs, not from an external power but directly from the arduino board, would that be OK?

@user3060854 As long as the total current consumption of the Arduino board and all the items powered from it is less than 500mA (USB) or 800mA (barrel jack) then yes that is perfectly fine.


text:
Trinket Pro 5V red light flashing when battery attached
I am using Trinket Pro 5V to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position.
It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.
Is the power source not sufficient - 9V?
Has anyone faced a similar problem?

Adafruit has a decent forum full of people that could probably be more helpful https://forums.adafruit.com/  All I can say is that the red LED flashes when in bootloader state. You also need to provide some more info such as: Is the green LED on? Can you switch back from battery to USB and it works fine?

@I. Wolfe The red light flashes and the green LED is permanently on when the battery is connected. As soon as I connect it back to a USB it goes back to green light, and red disappears. This does not reset the Trinket, the code is still remembered by the board. I hope this helps with the detailed description. Do you have any thoughts? Do you think  9V has enough juice for the piezo/motor circuit?

Please consider reading the "https://learn.adafruit.com/trinket-gemma-servo-control/wiring" tutorial.
It says

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

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.
Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.
Instead, use a better power source.
Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".
The "Adafruit 16-Channel Servo Driver with Arduino" tutorial says:

Good power choices are:

5v 2A switching power supply
5v 10A switching power supply
4xAA Battery Holder - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other Battery holders that hold lots of AA batteries in a convenient package.
Related:
"How to get high current from 9 volt batteries"
and
"What is the max current I could draw from a 9V battery?".

Thanks, @david-cary. As soon as I plugged the servo to be powered directly from the battery, it worked like magic! Appreciate your answer:)

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


text:
Weird stepper motor behaviour on RAMPS in arduino
Following this tutorial:
http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS
I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:
 //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

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

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

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

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

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

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

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

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

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

What did you expect/want to happen, and how is that different from what actually happened? Do know know how to detect which 4 wires from RAMPS go to which 4 wires on the stepper motor? What happens when you use a slower acceleration?

The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.
Recalculate your steps/mm values and slow down the feed rate to get something reliable.
For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.
Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:
#define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


text:
ESP8266 and Arduino bidirectional streaming from and to a website
I was looking for some easy tutorial on bidirectional communication via ESP8266 connected to Arduino UNO. I want to send and receive strings from and to JQuery based website.
However, I couldn't find any answers on this because most of them are about working directly with ESP. It's probably easy thing to setup but I'm totally new in working with network communication ;(
At this moment I know how to set AT for ESP as client and receive messages with pin number to toggle:
AT+RST
AT+CWMODE=1
AT+CIPMUX=1
AT+CWJAP="user","pswd"
AT+CIPSERVER=1,80
AT+CIPSTO=10

And JQuery for buttons (data is their ID) form one of tutorials:
$(".led").click(function(){
    var p = $(this).attr('id');
    $.get("http://192.168.1.14:80/", {pin:p});
});

Problem with this is whenever I send something the ESP gets the value and prints info but then it disconnects after 10 seconds (defined time) and when I hit the button again it reconnects and I can't do more (for example: send another value) during the time when it's connected.
Is it normal behavior? How to make it possible to send many messages when it's still connected to the port without waiting to reconnect? Can I make it in more "streaming" way? And how to make this bidirectional? Any advice on configuring the device will be helpful.


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

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

Low impedance circuits connected to the TX/RX pins would cause distortion in the serial signal and would interfere with communication.
A switch would help here. Alternately, you could use a Mega 2560 with more IOs, or if you are breadboarding it, use a 1284p chip.
You could also use SoftwareSerial to communicate with the other Arduino on another set of pins.


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

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

Mine were basic NEC protocol.


text:
Serial Communication, Arduino and Rpi , C library
I am currently working on a project on serial communication between RPi and Arduino. This is the code that I am using from RPi side, it's in C:
int main()
{
   //-------------------------
   //----- SETUP USART 0 -----
   //-------------------------
   //At bootup, pins 8 and 10 are already set to UART0_TXD, UART0_RXD (ie the alt0 function) respectively
   int Arduino= -1;

   //OPEN THE UART
   //The flags (defined in fcntl.h):
   //   Access modes (use 1 of these):
   //       O_RDONLY - Open for reading only.
   //       O_RDWR - Open for reading and writing.
   //       O_WRONLY - Open for writing only.
   //
   //   O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
   //                                           if there is no input immediately available (instead of blocking). Likewise, write requests can also return
   //                                           immediately with a failure status if the output can't be written immediately.
   //
   //   O_NOCTTY - When set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
   Arduino = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);           //Open in non blocking read/write mode
   if (Arduino == -1)
   {
       //ERROR - CAN'T OPEN SERIAL PORT
       printf("Error - Unable to open UART.  Ensure it is not in use by another application\n");
   }

   //CONFIGURE THE UART
   //The flags (defined in /usr/include/termios.h - see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
   //   Baud rate:- B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
   //   CSIZE:- CS5, CS6, CS7, CS8
   //   CLOCAL - Ignore modem status lines
   //   CREAD - Enable receiver
   //   IGNPAR = Ignore characters with parity errors
   //   ICRNL - Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters - don't use for bianry comms!)
   //   PARENB - Parity enable
   //   PARODD - Odd parity (else even)
   struct termios options;
   tcgetattr(Arduino, &options);
   options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;      //<Set baud rate
   options.c_iflag = IGNPAR;
   options.c_oflag = 0;
   options.c_lflag = 0;
   tcflush(Arduino, TCIFLUSH);
   tcsetattr(Arduino, TCSANOW, &options);

   //----- TX BYTES -----
   unsigned char tx_buffer[20];
   unsigned char *p_tx_buffer;
   int Angle=-20;
   int Speed=100;

   int Botschaft=Fusion(Crypt(Angle),Crypt(Speed));

   p_tx_buffer = &tx_buffer[0];
   *p_tx_buffer++ = Decompositer(Botschaft,1)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,2)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,3)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,4)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,5)+'0';
   *p_tx_buffer++ = Decompositer(Botschaft,6)+'0';

   if (Arduino != -1)
   {
      int count = write(Arduino, &tx_buffer[0], (p_tx_buffer - &tx_buffer[0]));     //Filestream, bytes to write, number of bytes to write
      if (count < 0)
      {
        printf("UART TX error\n");
      }
   }

//----- CHECK FOR ANY RX BYTES -----
   if (Arduino != -1)
   {
      // Read up to 255 characters from the port if they are there
      unsigned char rx_buffer[256];
      int rx_length = read(Arduino, (void*)rx_buffer, 255);     //Filestream, buffer to store in, number of bytes to read (max)
      if (rx_length < 0)
      {
        //An error occured (will occur if there are no bytes)
      }
      else if (rx_length == 0)
      {
        //No data waiting
      }
      else
      {
        //Bytes received
        rx_buffer[rx_length] = '\0';
        printf("%i bytes read : %s\n", rx_length, rx_buffer);
      }
   }

   //----- CLOSE THE UART -----
   close(Arduino);
}

int Fusion(int Angle, int Speed)
{
   int msg;
   msg=Angle*1000+Speed;
   return msg;
}

int Decompositer(int Num,int Place)
{
   int Result[5];

   Result[0]=Num/100000;
   Result[1]=(Num-Result[0]*100000)/10000;
   Result[2]=(Num-Result[0]*100000-Result[1]*10000)/1000;
   Result[3]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000)/100;
   Result[4]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100)/10;
   Result[5]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100-Result[4]*10);
   return Result[Place-1];
}

int Crypt(int Value)
{
   int result;
   result = Value + 100;
   return result;
}

And this is my code from the Arduino side:
void setup()
{
    Serial.begin(9600);
    Serial2.begin(9600);
}

void loop(){
    if (Serial2.available())
    {
        int inByte = Serial2.read();
        Serial.write(inByte);
    }
    if (Serial.available())
    {
        int inByte = Serial.read();
        Serial2.write(inByte);
    }
}

My purpose is to send a 6 digit number to my Arduino side, and be able to read them and then separate them into 2 different numbers...
The problem is I see only the first 2 digits and the rest are weird characters like 1‚þ.
I really appreciate your help.

Do you know just what it is your Pi program is actually sending out?

I guess, Characters ? by the way I tried to set a higher baude rate and for some reason it works , I dont know why :/

Was that 115200 baud perchance?

Yes exactly! Is there something wrong with it?

I have come across suituations where changing the baud rate fails miserably. Closing the port, re-opening it and setting the baud then works. It's like it only applies the baud change when the port closes. 115200 is the default baud rate the port is already on.

But do you think it might create a problem in the future?  Or should I change something in my code?

Later on I will post some other serial code that I use. I am not at my desk at the moment.

Here is how I use the serial port on Pi-like devices: https://github.com/majenkotech/SerialPort

Or you could just use one of the existing libraries on the Pi which work. Incidentally I don't know what the embedded code (with its own scroll bar) is supposed to show - it is unreadable.

This overriding problem here seems to be that you've mixed serial communication code with data coding code, without really verifying that either works by itself.  Split them apart and test your serial implementation with nice, human readable strings.  Separately test your encoding code to or from the terminal or a hex dump utility, depending on what it is you want it to be doing.


text:
Migrating from ATMega2560 to ARM based -- Teensy vs Due?
I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.
Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.
I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.
So my QUESTION is:
Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.
Any other considerations/suggestions/advice will be appreciated.
Thank you.

If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.
That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.
There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.

Thanks Majenko. I do care about compatibility but a better long term solution is a higher priority (also because it will be a learning vehicle for me working on arm uCs). So based on your answer I am leaning towards using the Teensy. Interested in seeing other replies as well (basically if someone has suggestions on boards at par with Teensy in terms of a good board but perhaps with better community support)

Personally i do all my work with pic32 or pic18 because i know those chips intimately, so i am somewhay biased towards those. Maybe you should have a dabble with the chipkit boards to see what you think. There are a number of inexpensive options, like the Fubarino Mini, that could let you experience them without breaking the bank...


text:
Using more than 8 digits using the sevseg library
I am using sevseg and i can't get more than 8 digits to work.  I really need 15.  Does somebody know what I can do to get this?
Shown is the original example
This is using Gabriel Staples example in the sevseg library:
#include <SevSeg.h>

SevSeg sevseg; //Instantiate a seven segment controller object

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

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

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

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

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

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

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

void setup()
{

  Serial.begin(9600);

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

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

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

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

}

void loop()
{

static byte decPlace = 2;

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

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

As per Dean Reading (programmer of sevseg.h) Using the example above, there will be a byte overflow and it is not possible for more than 8 digits.  So to further my question, is it possible (and if so how) do I break it down to say 3 segments of 5 digits each?  This would work for me as well, but it is over my head.  Thanks for any help I can get

Answer edited to show multiple instances, one to handle 8 digits, the other to handle 7 digits.

What Arduino are you using?  15 digits + 8 segments requires 23 IO pins, so I hope you are using a Mega2560.

You can change the pre-defined maximum number of digits at the top of the SevSeg.h header file to as many as 10, if you use long or unsigned long when you call setNumber.  It is defined here, on line 27:
#define MAXNUMDIGITS 8 //Increase this number to support larger displays

This the version referenced from the Arduino Playground SevSeg.  Be sure to use the same number in your modulo, too:
void loop()
{
  //local vars
  static byte decPlace = 0;

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

decPlaces is mostly useful for floating-point numbers: it specifies how many digits after the decimal point should be displayed.  For integer values, it specifies how many leading zeroes will be displayed.
However (as you discovered), you cannot call setNumber with anything larger than a long, so you are limited to 10 or fewer digits for MAXNUMDIGITS.  (There is no byte overflow -- it's just limited to the number of decimal digits in 232-1.)  This is a limit of one SevSeg instance.  You could have two instances of SevSeg like this:
#include <SevSeg.h>
SevSeg sevseg1;
SevSeg sevseg2;

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

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

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

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

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

The first instance handles 7 digits, and the second instances handles 8 digits.  Note the use of "UL" to force and unsigned long call.
Update 11-DEC-2015

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

First, the MAXNUMDIGITS is the maximum per instance, so you could set it to 5 to save some precious RAM.
Second, you have a copy and paste error:
sevseg1.refreshDisplay();
sevseg2.refreshDisplay();
sevseg2.refreshDisplay();   <--  Oopsies!  :)

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

Good catch on the modulo. I'd suggest using numDigits instead of a fixed value though.

Sorry, new to this forum.  See comment above.

using 3 instance of 5 digits each... The last 5 digits are blank.  Is it not possible to use 3 instances?  I am using a Mega 2560

Add new code to your question?

Added.  Thanks @slash-dev.   I am starting to get a feel for stackexchange.  Thanks for your patience

@klarson18, update added to my answer.

Looking at the sevseg README file on GitHub I find this:

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

Have you done that? Seems like that might be the problem.
As @slash-dev said, be sure to also modify the loop() code as well:
void loop()
{
  //local vars
  static byte decPlace = 0;

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

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

See the comment I made above also.  I am actually pulling numbers in from another program and can do that without an issue.  It is a set number of numbers.  The max I can get with the above code is 8 because of variables overflow.  Is there a way to do 3 segments of 5 digits each?  That will work as well.  Thanks in advance


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

If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.
It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.
To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.
Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.
To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.
A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.

Thank you for your answer, but the thing is the arduino itself is not resetting or switching off during the horn operation, it's perfectly driving the GUI display and other stuff it's used for. Only the values are changing. And yes, the voltage is dropping very much across the battery( low CCA, I suppose) but not directly affecting the arduino's operation.


text:
Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?
I am planning to buy a low cost and low weight laptop with an Atom Processor.
I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?

Are you wondering if you could install the Arduino IDE on the laptop?

Yes. Original FTDI chip will work but I am having cloned Arduino with CH340 and i am using Intel I3 which is working fine. Also planning to buy Atom processor based low cost laptop (Z3735F variant). Whether the driver will support the cloned one.

Install the needed drivers and you're done.

The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.
If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.
The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.

Thanks. I am planning to buy  http://www.snapdeal.com/product/micromax-canvas-l1161-lapbook-intel/661756382388 which is comes with windows 10


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

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

You can. But if it's a wall switch, it may be required to have an electrician do this, in your country. The 15Amps is the maximum current. Unless you are using a 2000 Watt light bulb, you won't reach the 10A limit of the relay. Remember to be careful, while working with mains voltage.

I have been working with mains lately, but I just don't know if the relay will blow out with the 15 amps.  But thank you!

It will only, if you have a device attached that uses more than 10 amps.

I'm voting to close this question as off-topic because it is about mains electrical wiring not Arduino.

All mains electrical work should be performed by a fully qualified electrician.
Yes, this relay board will easily switch a light bulb.
A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).
You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.
A similar question was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is Cybergibbons answer where he recommends using the PowerSwitch Tail as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.


text:
Issue with simple project
I'm new to Arduino and today I have a problem with this code:
int led_1 = 10;
int led_2 = 11;
int led_3 = 12;
int button = 3;
int time = 0;
byte val = 0;

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

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

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

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

Please explain what your code is supposed to do. You can't just dump the code on us, an expecting us to decipher what it does. Also, what is a casual?

edited the question with more informations

Thank you. Just use unsigned long time = 0; instead. What I also see, is that led 1 remains on, even if the button is pressed for more that one second. Idem for led 2 after two seconds.

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

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

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

To see the difference, just change the first line to
unsigned int time = 0;

Note how time rolls over to 0 after 65535 (well, only 65000 is printed).
I would recommend using unsigned constants by adding a "U" after the digits: 1000U.  In your if statements, you must cast the millis to the same (smaller) type: (unsigned int)millis().  Also, parentheses make the expression more clear:
      else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}

32768 will actually become -32768 not -1. I also think this will create a new problem after 65 seconds. Better to just use the same type that millis return. I.e. unsigned long.

Oopsies, edited -1 above.  However, he can use any size of unsigned int.  The key is to compare a difference with the desired interval: (unsigned int)millis()-start > interval, all unsigned numbers.  If he were watching for intervals < 256, he could have used unsigned char.

Thank you for the replies,I have solved the problem, but I have a question: I see that int time reaches 32768 and then becomes -32768, but after that it returns positive again. If I wait for 65 seconds (so time is positive) the LED still doesn't work. Why?
What does U mean?

Yes, I forgot that you need to cast the millis() to the smaller type.  My example does an implicit cast by assigning to the smaller unsigned int.  Edited answer and comment.

This is getting a bit silly. Casting the millis to an int?! Just use the proper type that is returned by millis, and use unsigned long time = 0;. This makes the code a lot more readable.

If millis is called just once and stored in a byte or word, like my example, there is no explicit cast (no impact on readability).  One would normally do this when grabbing a timestamp for comparison.  It does change the subtraction and comparison to a smaller type.  When the interval is small and the polling frequency is high, it can have significant run-time savings.  Another handy technique is to use the byte-sized TCNT0 directly and simply compare the elapsed ticks with interval/4.  This allows intervals up to ~1s and is efficient enough to use in an ISR or busy-wait loop.

Your code seems inefficient and there is a tempo variable that doesn't appear elsewhere.
  if (val == HIGH) {
    time = millis();
    while (digitalRead(button) == HIGH) {
      int time0=millis();
      if (time0 - time < 1000) {
        digitalWrite(led_1, HIGH);
      } else if (time0 - time < 2000) {
        digitalWrite(led_2, HIGH);
      } else if (time0 - time > 2000) {
        digitalWrite(led_3, HIGH);
      }
    }
  }

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


text:
Looking for help with WiFi modules
I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me.
Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.
I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.
Before anyone asks, yes, it is critical for it to work over wifi.
Has anyone done something like this? What gets the best results?

I think the uno will already be a bottleneck here.

The audio issue aside look at the Adafruit Huzzah ESP8266 breakout. It is a really great board, and you can run your Arduino code directly on it, removing the need to fight AT commands and all that.  It is also really cheep, compared to an Arduino and a WiFi shield.  For audio though, i would look at a microcomputer (Raspberry Pi maybe?) instead of a micro controller.

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


text:
Best way to implement score board logic using Arduino and Shift Registers?
I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.
Score - 888 (3 Digits) - I have implemented this logic using shift registers.  Three pin used from Arduino Uno and this is working fine.
Overs - 88 (2 Digits) - Need to find a best way to implement it
Wickets - 8 (1 Digit) - Need to find a best way to implement it
Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.
The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers.  There are only few pins.

Please Note: I need to print this design in PCB
This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

Are you saving pins on the Uno for something else?

I'd just daisy chain them all together. I code, you can have 3 variables (score,overs,wickets), and something like an update function that converts the values in the 3 variables, into bytes to send to the shift registers. I don't see any real advantage to using separate pins for the three different chains of shift registers. I'd suggest using the SPI pins to connect to the shift register, in case you ever need super fast update rates (e.g. for smoothly fading digits on/off).

@Gerben Thanks for your suggestion. It makes sense. I thought passing information via all serial registers may cause delay. Now i am clear with it.

There isn't really a best way (and such questions are usually discouraged as they can easily descend into argument).
Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.
From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.

Thanks for your suggestion and your answer. It helps me to decide which way to go.

You could use a 16x2 LCD to display the information; then you wouldn't need so many separate lines from the Arduino, the PCB would be simple and compact, etc.
However, if you need a big high-power display that is not multiplexed, you could use one 74HC595 per digit, assigning one bit per segment with 7-segment LED displays, with a driver transistor on each output.
The six '595s would be in series, which would use only two output lines from the Arduino: clock and data.
Another approach is to build your display from 84 or 126 WS2811 or WS2812B LEDs (2 or 3 per segment, and 7 segments times 6 digits).  About $10 to $15 on Ebay.  This would use one data pin from the Arduino to drive the whole display and would supply bright RGB light.

Thanks for your suggestion. Actually i am doing the same.Using 74HC595 per digit which works fine. But my question is there are three different logics for leds. I asked what is the best way to implement it. Did you get my question?


text:
Connecting and Programming LinkSprite Camera to Arduino
I recently bought the LinkSprite color jpeg camera:
https://www.sparkfun.com/products/12804
And the Arduino Wireless SD Shield:
https://www.arduino.cc/en/Main/ArduinoWirelessShield
I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.

What type of Arduino? The camera requires serial communication. HardwareSerial would be a good idea but that would require a Mega or Leonardo etc (board with extra serial ports). SoftwareSerial is possible but difficult to get to work at higher speed.

its an Arduino Uno r3

i have a mega also if i need that

What have you done so far to try this yourself?

Nothing really, i have been looking around to figure out how to connect it

Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on wiki.
Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc.


text:
arduino SD card saving to file
Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield
I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me
My code is;
#define redled 10
#define greenled 11
#define echoPin 12
#define trigPin 13

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

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

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

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

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


text:
glediator + PL9823 (WS2812B) + teensy = fail?
here is what I got:

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

I first off have to set the code to 160 on the teensy just to get it to                     at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.
Code
#include "FastLED.h"
#define NUM_LEDS 160
const int dataline = PIN_B4;
CRGB leds[NUM_LEDS];

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

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

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

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

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

Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.
I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

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

The teensy++2.0 uses a hardware USB built into its AT90USB1286 chip and  completely ignores any baud rate set in the Serial.begin(10000000) line, using instead a 12Mbit/sec rate i. See https://www.pjrc.com/teensy/td_serial.html

Cool, I didn't know that, thanks. I don't yet have any Teensy stuff. It is something I've wanted to play with :)


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

Run on batteries for at least 1 month
Detect motion
Logging the detection motion onto a text file in a SD card

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

It is possible to modify an Arduino Pro Mini (clone or original) to less than 1 mA and give at least a month on standard batteries (1000 mAh). Basically you need to remove the Power indicator LED and use low power mode in the sketch.
You could start simple by just lighting a LED when motion is detected and add the SD log later.
There are several techniques to detect motion. Advanced accelerometers such as ADXL345 but also simple wire sensing. The standby power requirements for these have a large variation.

Hmmms thanks for the prompt suggestion. WIll have to read up more on what a clone Aaarduino is.
Preferably i would like my device to function somewhat like a motion sensor that is installed in a lot of toilets and offices where lights turn on upon detecting motion. in that sense, a simple PIR sensor would do well. I will look into wire sensing though but an accelerometer seems overkill =)

PIR will work great. Advantage is that you can connect it to an interrupt pin on the arduino, to make it wake from sleep, when motion is detected. But since the arduino is sleeping, it will have no sense of how much time has passes. So you probably would want to add a RTC module, so you can log the exact time and date of the motion event to the SD card. Another option for motion sensor, is a vibration sensor

yup im looking around for a reliable PIR sensor but it doesn't seem there are much choices on Sparkfun...
i don't need exact time though. just the mere fact that someone opened my cupboard during the time that i am away is sufficieint. so a RTC might not be necessary =)

For low-power, just some tips (link references)
https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption
claim the below results,
LED off, without the JeeLib library: 6.7 mA
LED on, without the JeeLib library: 8.8 mA
LED off, with the JeeLib library: 43 uA (!)
LED on, with the JeeLib library: 2.2mA

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption
Detailed step by step tutorial.
For sensing PIR will depend on exact components; using SMD low-leakage components will do the trick but cost would increase. There are very-low-power RTC on the market and maybe SD logging will be more difficult as can consume up to 200 mA per reading/writing operations.

Hmm...I see...thanks for the reference and the info on SD logging. didn't know it was so power hungry. do you have other suggestions for logging? the data only needs to be present for 1 day as i will do daily checks.

well, if you encode your time-stamp in two bytes you can store 128 events on 256 bytes.

You have 32,256 of total program space in Arduino UNO and supposing using a 95% of that space for your program it will leave approx. 1,612 bytes, but who will open the door more than 806 times per day???

hahahahaha good point! i just need the occurrence of the event being logged. time is not important so i guess i can probably do with the existing program space then.

You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state.  Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.
An SDcard is neither necessary, nor a good idea.  If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card.  They will also be simpler to support in software.  Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.
Your main power consumption win however will be sensors.  If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption.  Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened.  Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.

ok so i could do without a SD card but how do i go about retrieving the data if i store it on the on-chip EEPROM or static RAM? RAM is fine actually since i don't need persistent data, just the mere fact that someone opened the door i.e. i want to track the number of times the door is opened in the period that i am gone so that i can go hammering around to find out who actually opened my door.
a contact sensor....i might consider that...just need to factor debouncing as my door isn't exactly tight so a kick or a nudge may set off the program to count as an event occurrence.

Probably have it upload the data over the serial port.  That does mean that for ram you would need to either disable auto reset or stop the utilized part of ram from being intitialized on reset.

hmmms...it is going to be a standalone though so having a serial port doesn't sound feasible. trying to find a way to stop ram from being initialized on reset..is that even doable?

RAM is cleared by software.  Removing the module for serial download should be possible if removing an sdcard is.  Having a button and LED to flash the open count might be easiest, and can mean no issues with trying to stop a USB serial from consuming power...

hmmms so a button and LED huhs. that sounds like a good idea...if i go for purely the chip alone, the USB serial is only needed when i flash in the program right? after that I can take it out which should hopefully help with reducing power consumption

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

thanks ^^ still thinking of what sensors to use since power is a major concern. i didn't think about light based sensors being power hungry but after Chris Stratton mentioned it, i might drop the idea of using PIR even though it is freaking convenient!


text:
Script stops functioning after calling irsend() function in irlibrary!
I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.
/*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

IRsend irsend;

decode_results results;

int intValue;
String strValue;
String str3;

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

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

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

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

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

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

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

  else{}
  //powerOff();
}

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

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


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

Roll

Yaw

Have you estimated the offset values vector and updated it in code?

yes i did. You can see values coming towards from 0

I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.
What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.
Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.
Below the L3GD20's mechanical characteristics

the sensor has internal temperature sensor so the gyro compansates temperature changes automaticaly.

even internal compensation is not perfect that's why datasheet has SoDr, OffDr and so on parameters.


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

Have you tried sending the baud rate command yet?

Try sending a command that sets the GPS baud rate to something a little lower:
altss.write( F("$PMTK251,38400*27\r\n") );
altss.end();
altss.begin( 38400 ); // change to match above command

Are you sure you're having trouble reading, because there are many other things you may be doing in your sketch that cause input buffer overflow.  Please post your code and some sample output for us to examine.  It may be failing for a different reason.
For example, you may just be losing data because you're trying to do too many things in loop().  Please take a look here.
To solve this kind of problem, I have posted a modified version of AltSoftSerial on github, here, that let you process GPS data in the background (i.e., during interrupts).  When coupled with NeoGPS, it can save you quite a bit of program space, RAM and execution time.  There is an interrupt-driven example here.  Just change which include is uncommented on lines 30-31:
#else
  // Only one serial port is available, uncomment one of the following:
  #include <NeoICSerial.h>
  //#include <NeoSWSerial.h>
#endif
#include "GPSport.h"

...and the baud rate below, on line 140:
  // Start the UART for the GPS device
  gps_port.attachInterrupt( GPSisr );
  gps_port.begin( 115200 );
}


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

This has already been asked on EE.SE. You will end up being asked the same questions here; if you don't help us then we cannot help you.

The answers over at EE also suggest that this is not the most appropriate sensor for this purpose.  Given you are detecting AC, note that the ACS712 returns values representing the sine-wave, crossing over at "0", which is 2.5v output from the sensor.  So you could take samples via the Arduino over a short period and detect the peaks in software to determine the total current, but from the answers below and at EE it seems an alternative sensor component, or additional circuit between the ACS and the Arduino would make the most sense if you need to use this particular sensor.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?

I'm voting to close this question as off-topic because posting a question to multiple sites is explicitly prohibited.

Considering an ATMEGA with a 5V VCC we have:
LOW  = < 0.3*VCC = 0,3*5V = 1.5 V
HIGH = > 0.5*VCC = 0,5*5V = 2.5 V

You can connect directly to the Arduino if the output of your sensor is higher than 2.5 volts whether current is present or below 1.5 volts if not. This would translate to HIGH or LOW output from digitalRead() function respectively.
You need to recalculate this values for the 3 volt version of Arduino, probably in this case is better the comparator solution to ensure up to 3 volts max logic level.
Example circuit as follow, just need to set voltage divider to desired threshold (note this is for 5v case),

You should instead use the Peak Detector example from the datasheet; it's designed for AC use and is much more appropriate for a current/no-current output.

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

Can you please expand your answer to include how to do this? What components would the OP need? Thanks!

Your answer would be even more useful if you could include more detail. For example, can you suggest a comparator that would be suitable, or a link to a tutorial that does something similar.

Depending on which Arduino, it already has an analog comparator.

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

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


text:
Where can I get a high-quality ADC (audio digitizer) for Arduino?
Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?
Does anybody know where I can find the best options for this?

32 bit ADCs are unlikely to exist.  Even at 24 bits on a multilayer PCB designed by an experienced professional the lower bits will only have meaning in a statistical sense as an input to certain types of filtering.  You are unlikely to be able to use even 16 bits to full advantage in an arduino project, so there's no point in looking beyond that.

You are going to need a bigger board.
(96000000 samples/second) * (32 bits / sample) ~= 3 Gigabits/second
A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.
While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.
The highest quality audio recording shield for Arduino I've seen is a modified Wav Shield that can record 8-bit mono files at 44,100 samples per second using the waverp library.

think 96000kps was most likely a typo. 96ksps or 96000sps is more likely since the title specifies audio. Still a little too much for an Arduino though. You need a chip with I2S and a CODEC chip.
I am working on a project at the moment interfacing a PIC32 to a CODEC for CD quality audio reproduction. The codec I am using (PCM1774) is DAC only, but you can get CODECs in many combinations of ADC and DAC with different numbers of channels in each.
I2S is very similar to SPI but needs some extra facilities that not all chips can provide. Things like:

High speed flexible base clock at (for example) 256x the sample frequency
Left/Right framing clock derived from base clock
DMA for smooth transfer of data

I don't know what offerings Atmel have, but for PIC32 you need one of the more modern chips, such as the PIC32MX1xx/2xx family, PIC32MX470, or for high end work the 200MHz PIC32MZ chips.
The MX1xx/2xx and MZ chips are available in a Arduino-like system called chipKIT which might suit your needs better than small Atmel chips.
The Arduino Due might also be able to do I2C but I won't be able to help you with that since I have relegated my Due to the bittom of my junk pile.