text:
What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?
I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller.
The setup is as follows:
Arduino|---UART--------------------------|MCU2
Arduino|---FLOW_CONTROL_PIN---|MCU2
I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).
At this point I log the amount of bytes sent and compare that to the buffer threshold level.  If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay.  I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).
A problem can arise if the Arduino api is providing more latency than the path under test.  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api.  I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.
I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.
I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.
This is probably what you are experiencing. See HardwareSerial.cpp:
// Define constants and variables for buffering incoming serial data.  We're
// using a ring buffer (I think), in which head is the index of the location
// to which to write the next incoming character and tail is the index of the
// location from which to read.
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

For this test you might want to edit that file and reduce that number, substantially.
Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?
However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.
To keep things simple though, what you really need to do here is not buffer because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:
Serial.write ('a');  // or whatever
Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).

what I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation.  I have noticed substantial speedup when I go from the Arduino API to coding it all up myself at a register level (i.e. digitalWrite() vs setting up PORTnx/DDnx/PINnx, etc.) and want to make sure that any overhead involved with using the API is not significantly going to effect my results.

@ryeager: Buffering and overhead are two different things. digitalWrite() has a big overhead and no buffering, while your issue with HardwareSerial seems to be about buffering.

See additional couple of paragraphs in reply.


text:
How to turn LEDs based on voltage readings?
I am trying to turn LEDs in an LED bridge based on the voltage reading from a power source. when the Voltage is zero nothing is ON and then the LEDs gradually turn ON as increase the voltage connected to the Ao pin. ( I am using a pro trinket 3V 120 MHZ)
This is my code:
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 7; // the number of LEDs in the bar graph

int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached

void setup() {
    // loop over the pin array and set them all to output:
    for (int thisLed = 0; thisLed < ledCount; thisLed++) {
        pinMode(ledPins[thisLed], OUTPUT);
    }
}

void loop() {
    // read the potentiometer:
    int sensorReading = analogRead(analogPin);
    // map the result to a range from 0 to the number of LEDs:
    int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

    // loop over the LED array:
    for (int thisLed = 0; thisLed < ledCount; thisLed++) {
        // if the array element's index is less than ledLevel,
        // turn the pin for this element on:
        if (thisLed < ledLevel) {
            digitalWrite(ledPins[thisLed], HIGH);
        }
        // turn off all pins higher than the ledLevel:
        else {
            digitalWrite(ledPins[thisLed], LOW);
        }
    }
}

However, I am not getting the outcome I want. when there is 0 voltage one LED turns ON instead of nothing. when there is a voltage all connected LEDs turn ON regardless of what the voltage is
when there is no voltage connected (floating wires), I get this:

when I put any amount of Voltage as long as the power supply is ON the results is the same:

Note: What am I doing wrong?
edit: connections are something like that but with fewer digital pins.

Note: What am I doing wrong!EDIT:
I was able to get around and print the serial monitor result:

when the power source is OFF, the reading at A0 (sensorreading) is:

Note: What am I doing wrong!- when the power source is ON at any value, the reading at A0 (sensorreading) is:

(Note: What am I doing wrong!)

Try printing sensorReading and ledLevel in your program and see if they are the values  you expect.

Could you please add a schematic showing how you connected the power source? Voltage divider, protection resistor, ground connection...

@Delta_G I can not communicate with trinket pro as it does show as a port, but a USBISP

is the Trinket your only Arduino?

Currently, yeah.

Is the Arduino GND connected to the negative lead of the power supply?

yes @EdgarBonet

I can't see the connection from the negative terminal of the power supply.  Can you show that as well.  Where is it connected?

I don't see any resistors in series with the LEDs. Where are they?

You are using a Full-size breadboard, for the full-size breadboards, the power rails are divided into two half sections as shown in this picture, and you need to have jumpers to bridge the two half-sections if you want to use them as a single power trail full-size section.

So on your photo, you thought that your blue wire (for GND) is connected to the rest of GND pins, but it is actually not connected.

It makes sense. I will try it tomorrow or so. YOU ARE A GENIUS. #Observation

I can say your code is working but you need to check the wirering of your circuit .
Note that the voltage on the analogread pin should not be an oscillating voltage at low frequency like AC voltage. It should be  a direct stable voltage to get the correct output.
Here is my diagram below for you to make changes with yours .
Ive testedit on my simulation app and its working perfectly.
The code

const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 7; // the number of LEDs in the bar graph
int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached

void setup() {
Serial.begin(9600);
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT); }
}

void loop() { // read the potentiometer:
int sensorReading = analogRead(analogPin);
Serial.print("sensor read : ");
Serial.println(sensorReading);

// map the result to a range from 0 to the number of LEDs:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
Serial.print("led Level : ");
Serial.println(ledLevel);

// loop over the LED array:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// if the array element's index is less than ledLevel, // turn the pin for this element on:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}

// turn off all pins higher than the ledLevel:
else {
digitalWrite(ledPins[thisLed], LOW);
} }

//delay(500); //for debugging
 }

The diagram

Note that if you're tryingto measure a voltage higher than 5 volts, make sure to build the voltage divider circuit with the appropriate resistor values for you to get 5v output as that is the highest volt the arduino can carry.
measure
Example below shows a 12 volts dc battery voltage measure(note that 5 volts is the highest voltage supplied to the arduino, not the full 12 volts):

source: Stack Exchange

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

sort: votes


text:
Checking a thing about interrupts
If I disable interrupts (for example noInterrupts or cli) and enable them (interrupts or sei for example) later, would interrupts which would have executed in the window in between fire by the execution of the latter? I guess not, and haven't confirmed or denied it. If not it is always an option to manually disable timers or components with similar concerns with respect to the interrupt status? It makes sense that AVR-based Arduino boards would behave similarly. It seems plausible that the bits for the force interrupt execution will turn on and turned off when the jump occurs. Thanks for reaching out.

your question is not about Arduino ... it is a general question about the AVR microcontroller ...  better fit at https://electronics.stackexchange.com/questions

Thanks, it seems that I made the same mistake as before, I thought that noInterrupts and interrupts would justify it.

@jsotola this is a reasonable question - otherwise you could hive off almost all questions about Arduino saying they are about AVR microcontrollers.

See How do interrupts work on the Arduino Uno and similar boards?
Yes, most interrupts will be remembered and the ISR will be executed when interrupts are enabled again, plus one more instruction has been executed. If that didn't happen it would be very bad, as you may turn off interrupts briefly and you wouldn't want to miss the thing that the interrupt was for (eg. incoming serial data).
To stop that happening you need to clear the "interrupt has happened" bit for the individual interrupts. This is documented in the datasheet for each interrupt.
The order in which outstanding interrupts will be serviced is the interrupt priority, that is lower-numbered interrupts will be serviced first. The call to the ISR causes the processor to clear the "interrupt has happened" bit for that interrupt.

Note that each interrupt has a single 'interrupt occurred' bit, so that if a particular interrupt fires multiple times during the CLI-SEI window, it will only be serviced once outside the window.  So the handler has to check all possible triggers...

@user10489 Can you elaborate on what you mean by "all possible triggers?". The interrupt bit will be set only once in that window. Once it is set it can't be "double set". It is important for ISRs to handle their respective interrupts quickly, so as not to unnecessarily delay the processing of other interrupts.

Right.  If an interrupt is multiple triggered but only fires once, your handler will only be called once, but might have to handle all the things that would have caused it to fire.  For example, if you have an interrupt for characters received by the uart, you might end up reading multiple characters.

Yes, in that case, the UART has a (small) buffer so reading until it is empty would be advisable.

As a note to somebody who might find this useful, it seems that the interrupts flags are those force bits, like the force compare A and B in the timer registers.

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


text:
Does the bootloader use some SRAM?
I want to use all SRAM of an Arduino by writing the code in assembly. But does the bootloader use some SRAM while the program is running, and if the answer is yes would changing that data lead to failure or does the data stored there get corrupted? Thanks for reaching out.

You did not specify what type of Arduino you are using. My answer is for
the AVR-based ones.
The bootloader does use RAM while it is running. However, once it
handles control to your program, the microcontroller is all yours: you
are free to use all the RAM.
Id did not check with optiboot but, it is possible that the bootloader
leaves some stuff in the stack. The C runtime of the avr-libc takes care
of this: one of the first things it does is to reset the stack pointer.
If you link with the avr-libc, you will find the stack empty. If you
don't, I suggest you set the stack pointer to RAMEND at the beginning of
your program, just in case.

I expecting that it didn't, but apparently optiboot as it was compiled for UNO leaves 2 bytes on the stack, entering application code with SP = 0x8FD. It doesn't matter for the reason you pointed out, but it's fun useless trivia I guess. =)

Whether you need those two bytes depends on an architecture detail: is the stack pointer written, then decremented or the other way round on the avr cpu?

@PMF: On AVR, the stack pointer is post-decremented when writing to the stack.


text:
Multiple I2C devices on Arduino
I'm design a custom PCB based around the Arduino Zero/Adafruit Feather M0. The plan is to use a few I2C devices. I just had a few questions about whether I've designed the board correctly.
You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...
Also, are the devices just connected in parallel? Are there any considerations I need to make when using 3 I2C devices like this?

You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...

You should have just two 3.3K resistors - one on the SDA and one on the SCL lines.  However all your 10K resistors in parallel will equate to about the same thing - just taking up 3x the space.

Also, are the devices just connected in parallel?

Yes, it's a simple multi-drop bus.

Are there any considerations I need to make when using 3 I2C devices like this?

Not really, no.  The frequencies in use are generally too low to require any specific layout considerations. Just try to keep vias to a minimum and don't snake the traces around the board too far.

Where does the value of 3.3K come from? I've seen 10k total suggested and also 4.7k. Will the bus capacitance make a difference?

2.2-4.7k is the recommended range for I2C. It is above the minimum for the voltage the Arduino works at, and low enough as to keep the rise times well below the thresholds for "normal" (<200pF) bus capacitances.  Chapter 7 of this document by NXP gives you all the technical blurb and formulae. There's even some nice graphs. You can see from those that 10k is kind of on the knee of the graph - too high really to be properly in spec - and the 30k+ of the internal pullups on the Arduino that everyone seems to use are way way out.

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


text:
Switch to drive Arduino and optocoupler
At the moment I have a switch that connects to a digital pin on an Arduino as per the schematic below.  (Obviously there is an pull-up resistor on the pin).

simulate this circuit – Schematic created using CircuitLab
I now want this switch to also connect to another Arduino via an optocoupler. Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues.  First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage.  For example, with Vcc=5V, table 30.2 DC Characteristics in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V.  If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.
Second, if the pullup is large, not enough current will flow to trigger the optocoupler.  For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler.  (See figure  35-17, ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V) in datasheet.)
What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos.  The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs;  optocoupler outputs go to  Arduino inputs.
Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input.  Connect the first Arduino's input pin to the low side of the switch.  I think that input will register low when the switch is open.  It will register high when the switch is closed.

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


text:
Daisy Chaining USB Communication over Arduino Due
I have two Arduino Due boards. I would like to connect one to my computer through the programming port as USB Serial so that I can send it commands, but I would like it to also be able to communicate to a second Arduino Due as the host on the native USB port.
I see in the manual that it has drivers for acting as a host to USB Mice and Keyboards, but is having it load appropriate drivers for communicating with another Due doable? I've done plenty with the USB ports, but never as a host so I'm not really sure how to start.
The goal is to have one "master" Due connected to the computer that controls a complicated piece of equipment with a lot of supporting electronics, and a second "peripheral" Due that acts as an interface for the user. The master would accept commands either from the computer, or from the peripheral. Reason is that the peripheral has to have fast interrupts to handle rotary encoders and the like (the "master" Due is quite busy so those interrupts can be troublesome) and be physically located in a different place.

Have you considered exposing one of the USARTs over USB, and connecting it to the other Due?

Using Serial (UART) or SPI would be a lot easier, and less burdensome on both the Arduinos


text:
Controlling multiple LED strips with arduino
I want to control several (undecided) cut strips of these led lights:here.
I want to be able to turn the LEDs on and off from the arduino, but I know that the voltage is too high to work with with the arduino and I don't want to fry my arduino. I've looked into relay modules, but I'm a software guy and I don't understand even the difference between voltage and amperage (I think I have the idea down, but I get the two mixed up sometimes). I also don't know how much voltage or amperage I should be giving each strip or how to control that. I have all my code set up to control my arduino with my simple C# form I've made, but I'm dumbfounded when it comes to hardware, can anyone help?
Also, I'm not well into money so I'd like to avoid spending money on some relays if possible.

http://arduino.stackexchange.com/questions/3535/rgb-led-strips-with-arduino or
https://learn.adafruit.com/rgb-led-strips?view=all . I short; use a 12v power supply and switch the strips on/off using a MOSFET.

The bottom line here is you aren't quite ready to do this project. You need about a couple weeks of education and experimenting - not a big deal, get on that right away. I would suggest doing the example programs, learn to blink an LED, then learn to blink multiple LEDs. The ones that are important to you are "Blink" and "BlinkWithoutDelay" to learn programming standards (those are the Hello World of microcontrollers). Then, this example from AdaFruit where you learn to control a high-voltage device with a transistor - https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors

And, the reason I say that is: money is important to you and you're going to fry parts if you don't address the issue of "don't know how much voltage or amperage I should be giving each strip or how to control that" - because that's basic to everything you will ever do, and without a clear understanding of it, you will end up spending extra money on this project. With some simple knowledge you'll be able to design and program this correctly. Personally, I think relays is the simplest way to do it - but there's at least three other methods I can think of.


text:
WiFi UDP.endPacket() continuously fails
I am attempting to send data from my Arduino to my computer using the WiFi shield.  However, my code is erroring out on UDP.endPacket(), and I do not understand why.  Here is my code:
#include <WiFi.h>
#include <WiFiUDP.h>

int status = WL_IDLE_STATUS;
char ssid[] = "NETGEAR31"; //  your network SSID (name)
char pass[] = "oddearth926";    // your network password (use for WPA, or use as key for WEP)

char  ReplyBuffer[] = "acknowledged";       // a string to send back

WiFiUDP Udp;

void setup()
{
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD)
  {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  Serial.println("\nStarting connection to server...");
  if(!Udp.begin(8765))
  {
    Serial.println(F("failed"));
  }

  // if you get a connection, report back via serial:
}

void loop()
{
  IPAddress ip(10,0,0,5);
  int port = 8766;
    // send a reply, to the IP address and port that sent us the packet we received
    if(!Udp.beginPacket(ip, port))
    {
      Serial.println(F("Failed beginning packet"));
    }
    Udp.print(ReplyBuffer);

    if(!Udp.endPacket())
    {
      Serial.println(F("Failed ending packet"));
    }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

And here is the log:
Attempting to connect to SSID: NETGEAR31
Connected to wifi
SSID: NETGEAR31
IP Address: 10.0.0.34
signal strength (RSSI):-63 dBm

Starting connection to server...
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet

It will continue to spit out "Failed ending packet" until I stop it.  Any ideas?

Fixed by updating firmware on Wifi Shield.


text:
How to retrieve the data type of a variable?
I am using Arduino and I would like to know if there is a function that returns the data type of a variable. That is, I would like to run something as like the following:
// Note: 'typeof' is a sample function that should return the data type.
Serial.println(typeof(myVar));

Why do you need to do this? the type of the variable should be known since you declared it

@sachleen Not true. Arduino Reference info is infamous for not telling you what function return types are. I have to define as auto, then use a bunch of function overloads to find out. RTTI would be simpler to find out.

In a typical C++ program, you would use the typeid operator, like this:
std::cout << typeid(myVar).name();

However, that requires a compiler feature called Runtime Type Information (RTTI). It's disabled in the Arduino IDE, presumably because it tends to increase the runtime memory requirements of the program.
You can get more information about the resource cost here: https://stackoverflow.com/questions/579887/how-expensive-is-rtti
Any fully-featured C++ compiler will definitely support RTTI though. If you want to try using a 3rd party IDE (such as Eclipse with the Arduino plugin) then you could easily enable it. It's probably not worth the hassle just for that though.

Alternative
A higher-performing (but less flexible) solution would be to use a traits class approach. This involves some funky template meta-programming:
// Generic catch-all implementation.
template <typename T_ty> struct TypeInfo { static const char * name; };
template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";

// Handy macro to make querying stuff easier.
#define TYPE_NAME(var) TypeInfo< typeof(var) >::name

// Handy macro to make defining stuff easier.
#define MAKE_TYPE_INFO(type)  template <> const char * TypeInfo<type>::name = #type;

// Type-specific implementations.
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( short )

You can add MAKE_TYPE_INFO(..) lines for any type you want, including the names of custom classes. You could then use it like this:
int myVar = 17;
Serial.println( TYPE_NAME(myVar) );

Anything you don't define using MAKE_TYPE_INFO(..) will show up as "unknown".
That's some fairly advanced stuff in there, so I won't try to explain how it all works here. There are various tutorials on the web though about C++ template programming if you're interested.
EDIT: It's worth noting that the typeof operator isn't standard C++, but is supported by a few compilers, such as GCC. It's basically an older equivalent of decltype, which appears in the C++11 standard.

very informative and thorough answer! would appreciate more of this kind

I use a simple stupid approach...
// serial print variable type
void types(String a) { Serial.println("it's a String"); }
void types(int a) { Serial.println("it's an int"); }
void types(char *a) { Serial.println("it's a char*"); }
void types(float a) { Serial.println("it's a float"); }
void types(bool a) { Serial.println("it's a bool"); }

This is the concept of function overloading where multiple functions with different parameter types are created but with the same function name. During run time, the function matching the right number of arguments and argument type(s) will get called. Hope this explanation helps.

Could you expand your answer a little, briefly explaining how it works?

i had to rewrite it by hand because copy paste led to issues i didn't understand. After retyping it by hand just as it is to the sketch it worked like a charm. Quite usefull...

Simple, easier to understand without knowledge of templates. Could be expanded to return enum of type.

Building on @snakeNET's answer (which I regard as function overload rather than polymorphism)...
A more generic way would be to pass in a pointer to Print, allowing any Print related class to be used (not just Serial); also pass objects by reference e.g.
void types(Print* p, const String&) { p->print("it's a String"); } // for each type
...
Serial.print("Type is "); types(&Serial, myStr); Serial.println();

Note that I has changed 'println' to 'print'; again, making it more generic.

I think the meaning of the term polymorphism has morphed somewhat over the decades to now include function overloading outside of OOP classes as well as overloading of member functions within classes. When I started learning programming, it only referred to overriding of virtual class methods in descendant classes.

There also a trick using compiler predefined macro. The advantage is it can print any type.
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;

    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');

    return s.substring(start, stop);
}

Use it like this
double pi = 3.14;
const char* str = "test";

Serial.println(type_name(pi));
Serial.println(type_name(str));

EDIT:
Some improvements based on tim's analyze.
First I have a comment on variation that has lower memory requirements. __PRETTY_FUNCTION__ is a literal string (a constant) that should not be changed. So my const version that do not use heap is following.
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature;
    while (*beg++ != '=');
    ++beg;

    const char* end = signature + N;
    for (; *end != ']'; --end);

    static char buf[N];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

A less safe but more efficient version using the fact that offset to type we want extract is a constant (always the same). If function signature changes (like put it in a namespace) the offset will change too. But come on, set it once, write a comment and it will work forever :).
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature + 42;
    const char* end = signature + N - 2;

    static char buf[N - 43];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

While above is ok ofcourse it can be improved further. Here is a my version of constexpr function mentioned by @tim. It uses constant offset as above to keep it short. This code generates only extracted string of type, the proof is here.
#include <utility>

template <class T, std::size_t... I>
const char* type_name(std::index_sequence<I...>)
{
    static constexpr char name[] = { __PRETTY_FUNCTION__[I + 60]..., 0 };
    return name;
}

template <class T>
const char* type_name(const T&)
{
    return type_name<T>(
        std::make_index_sequence<sizeof(__PRETTY_FUNCTION__) - 44>());
}

The minimum requirement for this is C++14 because of sequence traits. These can be re-implemented (see definition here) to adapt it to C++11.

That's great, but int stop = s.lastIndexOf(']'); is better because some types have [] in them.

@tim True, thank you! Will change it.

I tested the template form, the long-hand form, and the __PRETTY_FUNCTION__ macro and got different results. See the last two rows of the table for the differences.
Template Form 1
Attribution: Peter Bloomfield
MAKE_TYPE_INFO( bool )
MAKE_TYPE_INFO( bool* )
MAKE_TYPE_INFO( char )
MAKE_TYPE_INFO( char* )
MAKE_TYPE_INFO( double )
MAKE_TYPE_INFO( double* )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( float* )
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( int* )
MAKE_TYPE_INFO( short )
MAKE_TYPE_INFO( short* )
MAKE_TYPE_INFO( String )
MAKE_TYPE_INFO( String* )
MAKE_TYPE_INFO( char[5] )
MAKE_TYPE_INFO( char(*)[5] )

Long-Hand Form
Attribution:

SnakeNET
brewmanz
Tweaked by me to be more generic.

const char* TypeOf(const bool&)   { static const char type[] = "bool";    return type; }
const char* TypeOf(const bool*)   { static const char type[] = "bool*";   return type; }
const char* TypeOf(const char&)   { static const char type[] = "char";    return type; }
const char* TypeOf(const char*)   { static const char type[] = "char*";   return type; }
const char* TypeOf(const double&) { static const char type[] = "double";  return type; }
const char* TypeOf(const double*) { static const char type[] = "double*"; return type; }
const char* TypeOf(const float&)  { static const char type[] = "float";   return type; }
const char* TypeOf(const float*)  { static const char type[] = "float*";  return type; }
const char* TypeOf(const int&)    { static const char type[] = "int";     return type; }
const char* TypeOf(const int*)    { static const char type[] = "int*";    return type; }
const char* TypeOf(const String&) { static const char type[] = "String";  return type; }
const char* TypeOf(const String*) { static const char type[] = "String*"; return type; }
//const char* const TypeOf(const char[5])    { static const char* type = "char[5]";    return type; }  // Decays to char* so generates compiler redefinition warning.
const char* const TypeOf(const char(*)[5]) { static const char* type = "char(*)[5]"; return type; }

Template Form 2: __PRETTY_FUNCTION__ Macro
Attribution:

Original String version by Vladimir Talybin
Tweaked char array version by me.

Using String
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;
    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');
    return s.substring(start, stop);
}

Using char array
This variation has lower memory requirements.
template <typename T>
char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin = strstr(pf, "[with T = ") + 10;
    char* end = strrchr(pf, ']');
    *end = 0;
    return begin;
}

Test Code
bool b = false;
char c = 'a';
double d = 1.2;
float f = 3.4;
int i = 5;
String s = "6789";
char chars[] = "1234";

Serial.println(F("TypeOf() Test"));
Serial.println(TypeOf(b));
Serial.println(TypeOf(&b));
Serial.println(TypeOf(c));
Serial.println(TypeOf(&c));
Serial.println(TypeOf(d));
Serial.println(TypeOf(&d));
Serial.println(TypeOf(f));
Serial.println(TypeOf(&f));
Serial.println(TypeOf(i));
Serial.println(TypeOf(&i));
Serial.println(TypeOf(s));
Serial.println(TypeOf(&s));
Serial.println(TypeOf(chars));
Serial.println(TypeOf(&chars));

Serial.println(F("TYPE_NAME() Test"));
Serial.println(TYPE_NAME(b));
Serial.println(TYPE_NAME(&b));
Serial.println(TYPE_NAME(c));
Serial.println(TYPE_NAME(&c));
Serial.println(TYPE_NAME(d));
Serial.println(TYPE_NAME(&d));
Serial.println(TYPE_NAME(f));
Serial.println(TYPE_NAME(&f));
Serial.println(TYPE_NAME(i));
Serial.println(TYPE_NAME(&i));
Serial.println(TYPE_NAME(s));
Serial.println(TYPE_NAME(&s));
Serial.println(TYPE_NAME(chars));
Serial.println(TYPE_NAME(&chars));

Serial.println(F("type_name() Test"));
Serial.println(type_name(b));
Serial.println(type_name(&b));
Serial.println(type_name(c));
Serial.println(type_name(&c));
Serial.println(type_name(d));
Serial.println(type_name(&d));
Serial.println(type_name(f));
Serial.println(type_name(&f));
Serial.println(type_name(i));
Serial.println(type_name(&i));
Serial.println(type_name(s));
Serial.println(type_name(&s));
Serial.println(type_name(chars));
Serial.println(type_name(&chars));

Results

TypeOf()
TYPE_NAME()
type_name()

bool
bool
bool

bool*
bool*
bool*

char
char
char

char*
char*
char*

double
double
double

double*
double*
double*

float
float
float

float*
float*
float*

int
int
int

int*
int*
int*

String
String
String

String*
String*
String*

char*
char[5]
char [5]

char(*)[5]
char(*)[5]
char (*)[5]

Some Conclusions

TypeOf() has an issue with a decaying pointer.
TypeOf() and TYPE_NAME() have to have individual definitions with long-hand form or MAKE_TYPE_INFO.
type_name() uses the __PRETTY_FUNCTION__ macro to automatically get the type name within the template function, therefore there is no need to individually define the different types.
Template Form 1 has the lowest memory requirements.

Questions

Since Template Form 2 has higher memory requirements than Template Form 1, how could it be converted from Form 2 to Form 1?
How would a static const char * be initialised from a substring of a char array obtained from the __PRETTY_FUNCTION__ macro and passed as a template argument at compile-time?

Something like this pseudo code?
static const char * name = substr(__PRETTY_FUNCTION__, begin, end);

Perhaps this constant expression which can be assigned to a template struct member at compile-time? (I used a for loop because strstr and strrchr are not constexpr.)
template <typename T>
constexpr char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin;
    char* end;
    begin = end = pf;
    bool found_open_square_bracket = false;
    for (; *pf != 0; pf++)
    {
      if (!found_open_square_bracket && *pf == '[')
      {
        begin = pf + 10;
        found_open_square_bracket = true;
      }
      if (*pf == ']')
      {
        end = pf;
      }
    }
    *end = 0;
    return begin;
}

Note that: 1. When you pass an array as a function argument, it decays to a pointer to its first element. 2. char*[5] is an array of pointers, whereas &chars is a pointer to an array.

@Juraj, Sorry. I thought the first paragraph covered it in the context of this thread. I'll make it clearer.

It is more a limitation of  C÷+ version in Arduino. On PC I would return std::string_view in this case. On Arduino you may return a struct of const char* and size_t. This will solve you mem issue.

I would also split the template part and parsing part in 2 functions to make compiler generate less code for each requested type.


text:
Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board?
I need to do a Servo controller using Arduino and I have a spare MKS GEN V1.2 board right now, looking at the documentation from here http://reprap.org/wiki/MKS_GEN it seems this board is actually an Arduino board which can be programmed with the Arduino IDE.
Is this a correct observation that the MKS GEN V1.2 board is, in fact, a Arduino MEGA board internally?

It features an onboard ATmega2560.

This means that it is internally compatible with the Arduino Mega 2560. This does not mean that it is completely compatible with such since of course there is no way to use Mega shields with the board. This also means that there may be a core that provides better facility with the board, supporting its connections (LCD, positioning, heater/fan, etc.) better than the generic Mega core would.

This is good news for me, we can reprogram it to use our own Arduino codes to control the servo motors based on our code, the problem now is there seems no Schematic for the board so we start using it as our Arduino board

Did you see the third image in the Summary section?

Ah yes I can see it now, so for example the D30 there in the diagram corresponds to Arduino D30 pin?


text:
Running Stepper motors (at least 2) at the same time
Is there a way to run a Stepper motor with Arduino MEGA 2560 with A4988 driver component.
I am using this https://github.com/laurb9/StepperDriver library and with this code,
Serial.println("Starting motor ALL");
int steps = atoi(third.c_str());
int duration = atoi(fourth.c_str());

BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
stepper1.enable();
stepper1.setMicrostep(MICROSTEPS);
stepper1.setRPM(MAX_RPM);

BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
stepper2.enable();
stepper2.setMicrostep(MICROSTEPS);
stepper2.setRPM(MAX_RPM);

int starttime = millis();
int endtime = starttime;
while ((endtime - starttime) <= duration) // mS
{
     stepper1.rotate(90);
     stepper2.rotate(90);
     endtime = millis();
}
stepper1.disable();
stepper2.disable();
Serial.println("DONE");

The problem with this is that each stepper motor in this code waits for each other and not simultaneously like a DC motor. What could be done to make it work simultaneously?

Use a different library. This one is blocking code-execution while rotating.

Try the AccelStepper library. It can control both steppers at the same time. Also provides some useful examples
AccelStepper with more than one stepper also requires the Adafruit Motor library to be installed.


text:
Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port
Hello is there an Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port?
I've seen simulator online but I can't seem to find a simulator that can be programmed using the Arduino IDE through a Virtual COM port.

Possible duplicate of Can I program for Arduino without having a real board?

One of the option is using Proteus simulator with Arduino library. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).


text:
Trouble reading V_BG
I would like to read MUX 14 with the ADC.  On page 263 of the Atmega328 data  sheet it shows 1110b on the MUX corresponding with reading V_BG.
I need to read this so I can calibrate my sensor readings taken with the 5v reference to those taken with the 1.1v reference.  Because the 5v power supply may vary and the 1.1 is more stable, I need to be able to translate the readings taken with a 5v reference based on how the internal 1.1v is read.
Based on the code for analogRead, I wrote this:
int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

_analogReference is either 1 or 3 depending on the reference voltage desired.
I expect to read 1023 when _analogReference is 3 and about 225 when _analogReference is 1.  Instead I get smaller values which I'm guessing are from a floating (unconnected) analog pin.

How are you initializing ADCSRA?

As I understand it, these are registers on the atmega328.  If they were just variables, then the loop would never exit.

Ignacio, are you suggesting that I need to do more than twiddle a single bit in ADCSRA?

You might find this of interest: http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino

The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion.  Thank you Majenko for the link.
int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  delay(2); // Wait for voltage to settle
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

The above code is specifically for the Arduino UNO.  Majenko's link above has #ifdef statements which support other devices.

Can you accept this answer please so that StackExchange doesn't keep "bumping" it in the hope someone will give an accepted answer. :)


text:
Is it possible to use the DASH7 protocol in an arduino?
I've been reading about the protocol DASH7 but can't find much documentation about it. There seems to be a protocol stack called OpenTag writen in C and I want to know if there is something familiar written in arduino code and why can't I find a lot about this tecnology.

I hadn't heard of DASH7 before, but I checked the website and I'm not enthusiastic. To get the free(!) spec the site plays games with you, demanding to add it to a shopping cart, asking for a lot of personal information, etc. They're a nuisance. If that's the level of service for people whom you have to win over for your product, what level of service can you expect later on, after you've been won over already?


text:
Arduino car on bluetooth remote appears to crash when motors started
I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.
When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.
I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.
What is going wrong here? What issue am I encountering?
The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.
Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?

What sort of 9 V battery? One of the ones you put in a smoke detector? Almost certainly it is underpowered. I would also be interested to see the wiring.

It probably is the kind that goes into a smoke detector. It is a Varta Longlife.

Please sketch or photograph the wiring setup.

The wiring is very minimal. The sonic sensors and the bluetooth module are attached to pins on the motor shield. The motors are in the screw in terminals, as is the 9V battery. Here's a photo:https://drive.google.com/file/d/1Ev7B0DkuhxZA6TcpqyLhaMbF5M7nmoaPmQ/view?usp=sharing

Did you cut the "Vin Connect" jumper on the back of the board? I suspect you need to.

In any case you won't drive those motors for long with that 9 V battery.

Cutting that jumper has done the job. Now I'm on to the battery issue. Thanks.

You seem to be using your heavy-duty batteries for the Arduino and the light-duty 9 V battery for the motor. To me this seems backwards. Also the Vin pin to which you have the 9 V battery connected is by default connected to the Arduino as well. This means that if the motors draw a lot of current it will drag the Arduino's voltage down and it will probably reset (thus cutting power to the motors, and then it reboots).
From the Arduino Motor Shield page:

Vin on the screw terminal block, is the input voltage to the motor connected to the shield. An external power supply connected to this pin also provide power to the Arduino board on which is mounted. By cutting the "Vin Connect" jumper you make this a dedicated power line for the motor.

You should cut that jumper so that the Arduino and the motor have dedicated supplies.
Also, arrange better batteries for the motor. You may find you can run the Arduino from the 9 V battery, and then make sure you have enough AA batteries to drive the motors.

it sounds like the motors are pulling down the battery voltage enough to reboot the Arduino; and the USB-port is able to supply enough current without as much voltage drop.
We'd need to see a schematic, but check that the power supplied to your Arduino and power supplied to the motors are completely independent; that the Arduino only supplies current to a switch or a relay in the motors' power circuit but not to the motors themselves.


text:
FTDI Adjustable 3v3/5v only outputs 5v
I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.
http://www.ebay.co.uk/itm/301597777458?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
Now on the eBay description it says:

This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.
You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.


text:
Need help with uploading to arduino ng or older with atmega8
I am a newbie in arduino. I successfully installed driver for arduino atmega 8l, which were provided by the company i bought arduino from. The driver is PL2303 by prolific. The reason i m mentioning this is because at first i had some problems in installing them.
Now after i have made a blink program. I thought of uploading it. Whenever I try to upload i get this error:
avrdude: arduino_read_sig_bytes(): (a) protocol error, expect=0x14, resp=0x75
avrdude: error reading signature data for part "ATMEGA8", rc=-2
avrdude: error reading signature data, rc=-1
My computer: Windows 7 32-bit
I tried pressing the reset button before uploading, i get the same message.
I tried it in another computer of mine. There the driver is showing a code 37 error so basically my other computer is not reading the arduino.(also my board comes with bootloader already innstalled). Thank You

You have to select the correct board from the Tools->Boards menu.

@Gerben i have selected the correct board as well as the serial port. I have select arduino ng or older with atmega 8 and serial port com25 in my case, the board info was given by the manufacturer of arduino

I thing 0x75 is for a ATMega16, not an 8. Please look at the main chip on your board. The type should be written on it.

@Gerben I already have checked the chip. Its is an atmega 8, I know how to program in 8 languages but electronics was new and i do want to try it, so i just ordered a new board, but would like to see this running too though and thanks for helping me out


text:
Unable to add multiple potentiometer in Midi controller
I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..
    #include <MIDI.h>
int pot[] = {A0,A1,A2};
int AnaPinsNum = 3;
int potIn[] = {0,0,0};
int analogValue = 0;

int lastAnalogValue[] = {0,0,0};

 void setup()
 {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(115200);
  int i;
  for (i = 0; i < 3; i++);
 }
 void loop() {

  int i;
  for (i = 0; i < AnaPinsNum; i++)

  potIn[i] = analogRead(pot[i])/8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
    }
  }

}

Perhaps you want to send your values on different channels, or different controllers, instead of all on the same channel/controller combination...?

for (i = 0; i < 3; i++); - what is that line intended to do?

Yes I want to send different CC messages with different channel/value etc. in different inputs

Your logic is flawed here:
  int i;
  for (i = 0; i < AnaPinsNum; i++)
    potIn[i] = analogRead(pot[i]) / 8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
      }
    }

The first three lines read all three analog pins:
  int i;
  for (i = 0; i < AnaPinsNum; i++)

    potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of i which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.
  int i;
  for (i = 0; i < AnaPinsNum; i++)
    {   // <------------------------------- add this
    potIn[i] = analogRead(pot[i]) / 8;

    // potentiometer could be too sensitive and
    // give different (+-1) values.
    // send CC only when the difference between last value
    // is more than 1
    if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
      {
      // value changed?
      if (potIn[i] != lastAnalogValue[i])
        {
        // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
        // more info: http://arduinomidilib.sourceforge.net/a00001.html
        MIDI.sendControlChange(1, potIn[i], 1);
        lastAnalogValue[i] = potIn[i];
        }  // end of not same as before
      }   // end of value changed
    }   // <----------------- add this

If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:
Change:
MIDI.sendControlChange(1, potIn[i], 1);

to:
MIDI.sendControlChange(i, potIn[i], i);

Thanks Nick Gammon for the help..I am able to solve the input issue but I am still unable to send different MIDI messages through different input.. For ex if 1st pot is sending value 49 as expression value the next pot should send 50...like different expression value/channel message etc...in the increment of 1

if 1st pot is sending value 49 as expression value - I'm sorry, I don't understand that.

I want to send  values on different channels, or different controllers, instead of all on the same channel/controller.. Right now all the pots are sending out same Messages. I want different pots different messages..

If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2..

See amended answer.

OK got it. I have made the changes and it works

Sorry Sir.. I have accepted!!


text:
Arduino can't find my custom library: fatal error, Motor.h not found etc
I have been working on a project building a robot and using my own custom-built libraries to control it. However after converting all my old code into libraries Arduino can't find them.
Everything thing I have seen says to save them in the 'libraries' folder in with the sketches in MyDocuments and to reboot the Arduino Environment so it will recognize them.
Did that.
It even recognizes them in the sketch menu as libraries that can be imported. However, when I click on them to be included, a new blank line is entered into the sketch instead of an include statement. Perhaps this is some clue? I am really out of ideas at this point as to what I have done wrong.

Which version of the IDE? What is the library name? What are the file names in this library? Personally I never use the "import library" menu item, I simply type the include in myself.

its 1.6.3, its a library I made myself called Motor.h and I actually did write the include statement in myself too. I thought maybe I was doing it wrong somehow. The files are just Motor.h and Motor.cpp but it doesn't find them even though they are in the libraries folder

Are they in a folder, called Motor which is itself inside the libraries folder?

yes it is. the libraries folder in with all my saved sketches not the one in the C drive (though I tried adding it to that one too).

It should not be in the Arduino distribution folder (the one with the Arduino program in it). It should be in libraries in the sketchbook folder.

It is in the correct libraries folder. However the program still insists the file Motor.h doesn't exist

I wanted to vote for the answer from trpropst, but I don't seem to be authorised to do so.
I had the same problem as Caleb. It turned out that the problem was that the user library directory /Arduino/libraries/ contained a library with a missing ".h" file. The Arduino IDE stopped loading the user libraries when it reached the library with the missing ".h" file.
i.e.
the folder "/Arduino/libraries/libraryA" existed
the file "/Arduino/libraries/libraryA/libraryA.h" existed
but the file "/Arduino/libraries/libraryA/libraryA.h" had an include
"#include <libraryB>" for which the folder "/Arduino/libraries/libraryB" existed but it did not contain a file "/Arduino/libraries/libraryB/libraryB.h"
I was trying to compile a program using libraryC, but not using libraryA or libraryB. I guess the lesson is do not develop libraries using the production tool chain.
edited to print < and > correctly

I had the same symptom described here. In my case, there was a broken link in my libraries directory. Removing that link made the problem go away. It seems that you need to be careful that there is nothing in that directory that could cause the IDE to have difficulty parsing it.
I saw this on a Linux environment (the original poster didn't specify the OS but the reference to "MyDocuments" sounds like Windows). The link I referenced was a symbolic link I had created to a custom library that I subsequently moved, breaking the link.


text:
Running multiple tasks at once
For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.
The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.
void loop() {
// Heartbeat sensor loop
  while (array is not full) {
    delay(30 minutes);
    heartbeatArray[index++] = readHeartbeat();
  }
  sendData_Bluetooth(heartbeatArray);
  emptyArray();
// End of heartbeat sensor loop

// Accelerometer loop
  while (true)
    if (readAccelerometerData > limit)
      sendAlert();
// End of accelerometer loop
}

How long does readHeartbeat() take to execute? What is the accelerometer sampling rate and must it stay consistent?

Reading the heartbeat takes about 10 seconds but may take longer as we plan to read multiple samples to check for inconsistent data (the sensor sometimes doesn't work or gives odd data). The accelerometer samples every 100 ms and should continue like that, preferably also while reading the heartbeat.

What you want to do is rather easy task, you just need to forget about delay() function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:
unsigned long delay1 = 100;
unsigned long delay2 = 1800000; //30 minutes in miliseconds
unsigned long t1, t2;

void setup() {
  t1 = t2 = millis();
}

void loop() {
  if(millis() - t1 > delay1) { //this will be executed every delay1 ms
    // do one part of code
    t1 = millis();
  }

  if(millis() - t2 > delay2) { //this will be executed every delay2 ms
    // do another part of code
    t2 = millis();
  }

  // here insert the code that should be executed as frequently as possible
  // (every loop passage)
}

There is also a nice Arduino library called TaskScheduler, that basically does the same thing: periodically executes different functions with different time intervals.

I figured delay() wouldn't be a good idea as I was aware of it blocking execution; I just put it in to indicate the wait before the next reading. Thanks for the millis() suggestion though, think I'll give that a try. Will it however block the accelerometer reading if the heartbeat sensor reading takes a few seconds?

@OlivierV accelerometer can be read every time main loop executes. So if you are stuck at some inner loop of reading heartbeat, other sensors won't be checked. Try to divide this long process to smaller pieces. Perform the first piece, read accelerometers, perform the second etc. State machines concept can come useful here.

millis() is your great friend here.
millis() is function that returns the value of a 32 bit counter that is incremented once per millisecond. By adding the current value returned by millis() to a value representing the number of milliseconds that you want to 'delay' for you get a value that can be compared with the ongoing value returned by millis() to see if the time period has elapsed.
You can have as many variables as you wish which hold future timeout values for millis(0 - you perform the related action when millis() returns >= the saved value and reinitialise the value to some new future time.
Variables used to hold values from millis() MUST be type unsigned long.
The millis() timer rolls over every 49.7 days.
( = 2^32/1000 ms/s / 3600 s/hr / 24 h/day)

If your system may run for longer than that without being reset or powered down then handling millis()'s timer rollover must be known about.
It's MUCH easier than many people realise but best not dealt with here EXCEPT to know that if you add a constant to millis() and the value exceeds 2^32 and is truncated the comparisons with and subtractions wrt millis() still work correctly if the variable is type unsigned long. ("Why" is for elsewhere)

micros() is like unto millis() but returns the time since reset in microseconds. Depending on the processor used micros() may have a granularity of 4 uS rather than one uS. ie it steps by 4 counts every 4 uS rather than 1 count per uS.
micros() rolls over every 1.19 hours
( = 2^32 / 10^6/3600s/h)

// Example - not tested:
unsigned long DoitNow;

void setup(){
  DoitNow = millis() + 1800000; // Add half an hour of milliseconds
 }
void loop(){
   if(millis() > DoitNow)
   { Do heartbeat stuff;
      DoitNow = millis() + 1800000; // Add another half hour of ms
   }
 Do accelerometer stuff;
}

Your test millis() > DoitNow does not work if the computation of DoitNow = millis() + 1800000 has rolled over. You should never compare timestamps like you have done here, it does not make sense. Comparing delays (as in mactro's answer), on the other hand, is rollover-safe.

I just finished a tutorial on the millis() rollover covering precisely this issue. You may want to take a look.

See https://electronics.stackexchange.com/a/67091/10371 (Since this is another stack exchange site, I won't copy the info)
The short answer is to use timers that trigger interrupts.  Examples are shown in the link.

To keep the 10Hz accelerometer sample rate consistent, you'll need an 10Hz interrupt routine to do the sampling, and probably queue them somewhere, as they will accumulate while you're off measuring the heart rate.
Your main loop can collect any accelerometer samples out of the queue periodically, and at appropriate intervals, read the heart beat. This organization will keep the accelerometer sample rate stead whether your main loop has anything else to do or not.
Make the queue more than long enough to hold all the samples that could collect during a heartbeat measurement, which you should probably make one at a time, even though you might do it in rapid succession, so the main loop gets to drain the accelerometer queue as often as possible.
Otherwise you'll need a queue as large as (10 Hz * 10 sec * maxPossibleConsecutiveHeartBeatMeasurements * factorOfSafety * sizeof(oneSample) bytes; and you don't have a whole lot of memory to play with in an Atmega 328.
Where will you be storing the measurements between Bluetooth connects? If it's an SD card, you'll need some space for its write-buffer, and the main loop will have to manage the card writing.


text:
Arduino Ethernet shield frequently drops its IP address
Im working on a sketch that needs to display some internal variable values and analogue reads in a simple webpage. The only catch is that it needs to be as reliable as possible.
Im getting some odd behaviour across multiple shields where the sketch will work briefly (sometimes as long as 5-6 minutes) before cutting out and setting the IP to something weird (commonly 0.0.0.0 or something similar)
My main loop has some other code in it for reading buttons, values, sensors, etc, but the bulk of it is basically
void loop()
{
  ... do some stuff ...
  // listen for incoming clients
    EthernetClient client = server.available();
    if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                Serial.write(c);
                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connnection: close");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("");
                    // add a meta refresh tag, so the browser pulls again every 5 seconds:
                    client.println("<meta http-equiv=\"refresh\" content=\"5\">");
                    // output the value of each analog input pin
                    client.println(getStrDivByTag("MyWebPage", "h3"));
                    client.println("
");

                    client.println("");
                    break;
                }
                if (c == '\n') {
                    // you're starting a new line
                    currentLineIsBlank = true;
                } else if (c != '\r') {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
    }

  ... do some more stuff ...

}

When the server is working as expected, my serial output gives me something like:

new client
GET / HTTP/1.1
Host: 192.168.1.17
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0)
  Gecko/20100101 Firefox/73.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8

But just before it stops working, I get two back to back requests:

GET / HTTP/1.1 Host: 192.168.1.17 User-Agent: Mozilla/5.0 (X11;
Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0 Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Accept-Language: en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip,
deflate Connection: keep-alive Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
client disconnected Current Draw: -0.341
192.168.1.17 new client GET /favicon.ico HTTP/1.1 Host:
  192.168.1.17 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux
  x86_64; rv:73.0)
Gecko/20100101 Firefox/73.0 Accept: image/webp,/ Accept-Language:
en-CA,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Connection:
  keep-alive Cache-Control: max-age=0
client disconnected Current Draw: -0.048
0.0.0.0
Accept-Language: en-CA,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
client disconnected

What is that request, something about favicon.ico? After these back to back requests, the IP resets to 0.0.0.0, sometimes jumping to something odd like 0.64.1.0, 0.1.0.64, etc.
Is there an issue with my network configuration, the ethernet2 library Im using?

use the Ethernet library

Make sure you explicitly disable the SD Card slot if you don't use it, by setting pin 4 to high in your setup (at least that's the pin my Ethernet2 shield uses). I almost tore out my hair finding the reason why my (autonomous) sketch would sometimes run for 10 minutes, sometimes an hour, but always stopped responding after some time. It seems the SD Card SPI interface sometimes interferes with Ethernet SPI traffic unless you explicitly disable it.

There are many Ethernet sketch examples that are not reliable at all. They basically handle the network setup in setup(), and the TCP connections in loop(). This is wrong. It just means that if there is anything wrong in your network connection, it won't restart correctly. You should check Ethernet.localIP(); and restart your sketch if it doesn't fit.
This routine should do the trick : void reset() { asm volatile ("jmp 0"); }
Also, you should be ready for requests for a favicon.ico from usual browsers (that's the small icon that comes in your tabs and favorites) and reply to it (you can use a 404 reply if you don't want to send a file). Providing a robots.txt is also good practice.

I dont want to reset the entire sketch as it will bring down some relays transmitting power that the sketch is meant to keep open, but Id imagine it should be possible to just redo the network setup process every time the IP changes, right?

Is there any way of smoothly restarting the Ethernet instance without hard resetting the sketch?

Yes, you have to move the Ethernet start routine from setup, into loop, but in a 'if' statement that checks whether the Ethernet is active or not. I remember having seen a few sketches that did exactly that on github, but I couldn't find them back for referencing them in the answer (maybe they used the old Ethernet ENC28J60 chip). Sorry about that.


text:
Write with SD card; flush versus close?
I've got an application that requires moving to specific points on a file on an SD card, reading, modifying and then writing an update.  The file is fixed size.  The code has no problems moving to the specific offsets required and then reading in blocks of data.
However, when the code does a seek() to the next desired location, then a write() and a flush(), the data is not written.  If my code seeks back to the start of the block just written and reads it back, it does not contain the new data.
The file is definitely open for writing, and the write operation indicates it wrote all the bytes.  No calls are indicating any error.
Since reads and seeks are working I'm assuming this is not a problem with wiring of the device to the Arduino Mega.  The files range from around 100K to almost 2M each, and the code needs to access the entire content of the file, but almost never sequentially.  Writes are almost always non-sequential as well.
Is it necessary to do a close after each write instead of the flush?
Does anyone have any suggestions of things I should be investigating?
Bob

What filesystem layer are you using?

I'm using the File layer.  Ie, File myfile;  myfile.open(), myfile.seek(), myfile.write(), etc.

I just ran an experiment where the code seeks to a record in the middle of the file, writes a new record and then closes the file.  Next, it re-opens the file, seeks to the record and reads in back... the changes are not there.

Can u post example of your code?

This may sound trivial, but did you check if write protect is enabled? I'm not familiar with the library your using, but from the information I gleaned from a  quick google search, it seems like it simply returns the number of bytes written. In some file systems, the number of bytes written doesn't always mean that it was a successful write. It could just mean that x number of bytes were written to a buffer, pipe, or whatever.


text:
Arduino ADK, other board, shield or what?
Sorry for bothering.
I have a problem with my project and I can't fine someone who can help me yet.
I need the next configuration:
PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB
I need serial communication with USB cable in both boards.
I have now solved the ( PC --------USB cable------MegaA) part.
And the other part, I have done PC------------------USB cable------------------MegaB
But I need do that like the first schematic.
I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable.
Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)?
I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB.
Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port.
I need help, is very important.
Excuse my english
Thanks

Does MegaA have to relay your thing to MegaB? Couldn't you just use a USB hub to plug both of them into the PC?

You would need a USB host shield to achieve what you want.
The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:
http://www.arduino.cc/en/Main/ArduinoUSBHostShield
In the list of supported devices is:

USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.

I think that Hot shield is the answer, but I don't know If I can use both ports at the same time ( if one of them not cancel the other one) and how i can indicate the port to receive and the port to send, all the programs that I have found using the serial pins, and when it define the serial communication using the pins number to differentiate the receive part of the send part.

You seem to be a bit confused about what a host shield does and how it connects to the Arduino it is stacked on.  There won't be any confusion in your program as the Host operations will be quite distinct.  It is possible you will eventually end up with a "HostSerial" or something class you can use to talk to the slave Arduino, but it will be up to you to proxy messages arriving on "Serial" through to that when appropriate.  To be honest, what you want to do seems beyond the realm where Arduino is a sensible choice.

A USB host is far beyond what an AVR Mega handle. You could add a 'daugther' board of some kind, but that would be a computer far more powerfull than the Mega itself (think of a RaPi, or a fat 32-bit micro-controller), so it would be a bit weird.
You might physically patch the first USB through to the second one, using for instance a relay. That would allow the PC (but not the first Mega) to talk to the second Mega.

The USB Host Shield, which will do the job fine, is not "a computer far more powerful than the Mega itself".  The Arduino is perfectly capable of performing the task with that small addition of a single SPI interfaced USB host chip.

@Majenko - on the contrary, most hosts are in fact computers more powerful than the mega.  But the real solution is to replace the hosting mega itself - for example with a $3.30 KL25Z

You don't actually need to use serial-over-usb, the two devices can communicate more simply. The simplest way would be to Serial1, which uses pins D18 and D19; connect Serial1 on MegaA to either the serial or serial1 on MegaB. Since MegaA's transmit is MegaB's receive, you need to cross-over the wires (i.e. connect MegaA's TX to MegaB RX and vice versa).
Complete details can be found at: http://www.arduino.cc/en/Tutorial/MultiSerialMega
Make sure the two Megas have a common ground - the easiest way is to use one power supply (in your case, the USB) - you should just be able to wire GND and +5V from one board to the same pins on the other. If you use two different power supplies (e.g. two USB ports, even on the same PC), they may have different ground levels, and you can get a current flow directly out of one ground, and in to the other, damaging your PC.

"I don't have access to the MegaB because this is inside a machine, I can't access to its pins" - so how does he go about that then?


text:
Second SD not writing
simple problem I can't see the reason behind, the sd card writes the first file fine, but the second doesn't write at all. Can any one see why?
    #include <SPI.h>
    #include <SD.h>
    const int chipSelect = BUILTIN_SDCARD;
    File datafile;
    void setup()
    {
      Serial.begin(38400);
      analogReadResolution(13);
      //Initialize SPI pins to avoid errors
      //USB host SS pin
      pinMode(9, OUTPUT);
      delay(200);
      digitalWrite(9, HIGH);
      delay(200);
      pinMode(chipSelect, OUTPUT);
      delay(200);
      digitalWrite(chipSelect, HIGH);
      delay(200);

      Serial.print("Initializing SD card...");

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
       Serial.println("Card failed, or not present");
  }
  Serial.println("card initialized.");
  File dFile = SD.open("datalog.txt", FILE_WRITE);
  dFile.println("BORK");
  dFile.close();
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i / 10 + '0';
    filename[7] = i % 10 + '0';
    if (! SD.exists(filename)) {
      datafile = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }
  }
  Serial.println(filename);
  datafile.print("A0,");
  datafile.println("A1");
  if (!datafile){
    Serial.println("oopsydaisy");
  }
}

void loop()
{
  Serial.print("analog 0 is: ");
  Serial.println(analogRead(0));
  Serial.print("analog 1 is: ");
  Serial.println(analogRead(1));

  datafile.print(String(analogRead(0)));
  datafile.print(",");
  datafile.print(String(analogRead(1)));
  datafile.println();
  delay(1000);
}

please correct the title of your post .... right now it says that the second SD card does not work .... anyone searching for solution to issues with writing  multiple files will miss your post

You should cut your code down to the bare minimum.  You need to work out if:

It's the fact that it's the second file you're opening that causes it to fail, or
It's the way you're building up the filename in your loop, or
It's the way you're handling the file once it's been opened.

You should add extra debugging to your program so you know how your loop is operating. Is it checking for the existence of the files correctly? Is it looping too far? Not at all? Is the filename being created properly?
You haven't properly described your symptoms. Does the file actually get created? If so, is it just that it is empty? (I suspect so).
Why do I suspect that?  Simple:
The SD library uses a certain amount of crude caching. Nothing gets written to the SD card itself until either a whole block of data (512 bytes) has been written, or you close the file. Or manually flush the data to the card.
When doing periodic writing to a file like that it is better to open the file as (O_READ | O_WRITE | O_APPEND) before each block of writes, then close it afterwards. This ensures that the file is in a good state between each sampling period and all the data is written and the FAT updated properly.
So your method should be:

Find your unused filename.
Open the file FILE_WRITE (or (O_READ | O_WRITE | O_CREAT) - different versions of the library define it slightly differently) to make the file.
Close the file.

Then on each loop iteration where you want to write:

Open the file again as (O_READ | O_WRITE | O_APPEND)
Write your data.
Close the file.

@Juraj Regardless of whether it has append or not, it has O_CREAT, so it will make the file if it's not there - so it will always succeed on the first file whether it exists or not.

but I see no such operation in his code. and it was not edited

@Juraj Oh, hang on... All that extra irrelevant code was blinding me with extraneous file opens. Buried deep in there is actually an "exists" that I didn't see before... woods... trees... just goes to show the importance of the SSCCE concept instead of just dumping reams of irrelevant code on us.

@trinityalps, what was the problem? What from Majenko's answer helped?

You do not close the second file.
The examples show that you should close the file after every write and open it again before next write. Opening the file with SD library using FILE_WRITE flags, opens it for append if the file exists.
In my project I have a MCU with enough RAM (Mega, esp8266 or M0) so I cache the rows into 2000 bytes buffer and write them to file if the memory cache is full.


text:
SeeedDuino/Grove and the story of not being able to upload programs
I am new to the arduino world and wanted to start playing with the micro controllers, I am a .NET developer by trade so not completely new to this kind of world.
I purchased a seeedduino v3 and a Grove started kit (No soldering skills here) and can't even get the basics to work.
I am setting up a simple button to light up the LED program. I have had it run once or twice but it seems really hit or miss on whether or not the Arduino IDE actually gets the program onto the seeedduino.
Arduino IDE (1.5.6-r2) set-up:
Followed setup instructions found here: SeeedDuino v3

Board: Arduino Duemilanove or Diecimila
Processor: ATmega328
Port: COM4 [this is what popped up once device was plugged in]
Button is installed on D3
LED is installed on D7

Program:
int button = 3;
int LED = 7;

void setup()
{
  pinMode(button, INPUT); //define button on INPUT devices
  pinMode(LED, OUTPUT);   //define LED on OUTPUT device
}

void loop()
{
  int buttonState = digitalRead(button); //read the status of hte button

  if(buttonState == HIGH) //also used (buttonState == 1)
  {
    digitalWrite(LED, HIGH); //also used digitalWrite(LED, 1)
  }
  else
  {
    digitalWrite(LED, LOW); //also used digitalWrite(LED, 0)
  }
}

Upload Verbose Message:
avrdude: verifying ...
avrdude: 1070 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

I have only had the LED from this program turn on twice, then reloading it ruins it.
SIDE NOTE
If I try and run Burn BootLoader I get this message-
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb"

You had a USB-problem too: 'avrdude: usbdev_open(): did not find any USB device "usb"'. Always verify if your device actually got the port assigned you expect it to have assigned. Not sure if you can assign a device a static COM-port on Windows, I know it is possible on Linux.

Yeah I had ended up forcing it to be COM251 to be consistent. Thanks.

OK mystery solved!
I ended up getting Visual Micro Debugger plug-in for my Visual Studio 2013 since I am native .NET programmer. I could see that the code was indeed loaded onto the board and when I pressed the button it was indeed getting to the line of code for setting the digital LED to HIGH.
It was a very unfortunate case of trying different components and learning I actually had 3 dead LEDs and one bad cable. After getting functioning ones it's all good. :) unlucky me just had 4 bad parts in my kit.
Output from Visual Studio Debugging:
Legend:
line 12 = button state check
line 16 = button pressed turn on LED
line 20 = button not pressed turn off LED

=================OUTPUT====================
14:01:04.372 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.372 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.481 SeeedDuinoPlayground.ino, line 10
14:01:04.481 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 10
14:01:04.696 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.697 SeeedDuinoPlayground.ino, line 20  loop()
14:01:04.804 SeeedDuinoPlayground.ino, line 10
14:01:04.804 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.912 SeeedDuinoPlayground.ino, line 20  loop()


text:
Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino
Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?
I have a system with an ethernet port to connect to the internet. It works fine if I plug it into my switch at home. However, I would like this system to have its own cellular internet connection.
This is what I have found so far:

I'm basically trying to replicate the following:
https://nimbelink.com/e2clink-ethernet2cellular/#parts
If the following reddit post:
https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/
is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.

I'd suggest using a TP-Link Portable 3G/3.75G Wireless N Router (TL-MR3020), together with a USB 3G dongle. Probably cheaper also.

You're right! This seems to be even a cheaper option than using a Raspberry Pi 2 + USB 3G dongle. Thanks.

No, it's not possible.
Chiefly because the normal Ethernet shield is not capable of routing.  The Arduino never talks to the ethernet - it talks to the chip on the shield and tells it how to handle the ethernet connection - everything else is then done by the ethernet chip and the results passed back to the Arduino.
Similarly with GSM - you make requests to it and it goes off and does the work.
To link the two together you would need raw access to the incoming ethernet packets, and you would then have to perform NAT (Network Address Translation) and maintain internal state tables for current streams and such, and pass reformatted packets on to a GSM modem that could accept raw data like that.
Way outside the scope of a lowly Arduino.
Maybe possible with one of the higher end Arduino-ish systems like the Edison, Galileo or Yun (just) since they run Linux and have a real Ethernet port and a proper USB port to communicate with a proper celular modem.

Thanks Majenko, that makes sense and explains it nicely. I will check out the systems you've mentioned.
Also, do you think a Raspberry Pi 2 would be able to do this instead, given it includes an on-board Ethernet & USB port(s)?

Yes, a Pi would do the job admirably - just plug in a typical USB data modem for HSDPA / 3G and configure it as the internet connection - then configure packet forwarding and NAT and all the other proper routing you'd need and you're good to go - just like doing it on any Linux computer. You can even do most of it graphically through the GUI. Just follow the myriad of tutorials out there for a generic Linux PC (Debian) - it's exactly the same.


text:
Programming bluetooth module JY-MCU v1.06
I have a popular bluetooth module JY-MCU version 1.06 (picture below). Before i insert it to my arduino project I want to configure the name, bound speed and the pass code using usb-to-serial link. But I am facing a problem where the device does not respond to commands. Please let me explain.
I send the module to programming mode by applying +5V on 'key'
Then I send commands using CoolTerm program:
AT+NAMEmyArduinoProject
> OKyour set name

Ok. setting the name works as expected. But that is the only thing that worked for me. Other commands give no response:
AT

AT+BAUD2

AT+VERSION

AT+VERSION?

Maybe you had this happen to you? I am I sending wrong commands or doing something wrong? Please help me to figure out how to control this module.

I've heard how sometimes you have to put it into "AT mode" by pulling up a pin to HIGH. It might be like the "KEY" pin (not entirely sure).

Just a comment on configuring these boards: there is no provision for resetting them to default- or factory-settings. They remember only their most recent settings. Either write down how you last left it or always use it the same way - the serial settings especially! The only alternative, if you've forgotten the last settings, is to run a program that tests combinations of baud and serial-framing until it can establish communication with the device and set it to your new preferences. Glad you got yours sorted out!

I believe that the active IV on this is also known as the HC-06.  You may also want to study relevant data sheet information on that device.

The board is actually called a Bluecore CSR Ext 4. Collioquially its known as an hc-05 bluetooth module. The jy name is tge breakout board it sits on

OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!

The protocol is peculiar.
You are to send the command unterminated within one second.
For example the AT command comprises the two characters AT and nothing more, no line ending at all. And the command must be completed within one second.
So,
AT[cr][lf] will just be ignored.


text:
Several SIM with Arduino GSM/GPRS shield
For some purpose we need to communicate with Arduino using more that one SIM card, but still like to use an only GSM shield.
So, the idea is to use several SIM holders, to commutate each of six SIM wires to the sim we currently use. But it is still the question
1) How we should handle the gsm module itself? Is it okay for it if the SIM wire will be commutated to another SIM when it is in the middle of something? May be we should power off the module before, but it unclear how to do it programmatically when it is installed on the top of Arduina Mega 2560
2) should we commutate all six wires, or may be there are few signal ones and another shouldn't be never commutated?
3) what is the best way to do this commutation? Relays/transistor switches and so on?

Hi Ilya, have you finally implemented it? Could you please share the solution? Thanks

Hi, unfortunately no> I haven't implemented it :(

You should reset the shield, and keep reset, while switch sims. The reset is on pin 7.
If you look at the schematic, you can see there are only 3 lines, plus a GND and VDD. The GND and VDD you can probably share between the different sims. The SIM_RST, SIM_SCK and SIM_DATA need to be switched.
I think you should use a MUX for that, but that is not my area of expertise. Note that at least the DATA line is bi-directional.


text:
Figuring out some numbers for a mini pump
I'm just now getting into electronics (I don't know why I waited so long) and I'm just figuring out some stuff.  I picked up an Arduino kit from Vilros.com and a few other parts for my project.
I'm currently trying to work on a project that is basically a humidor keeper.  Living in So.California, it's extremely dry here and I would like a perfectly controlled environment for my humidor.  I purchased a few things like some humidity sensors (as an input obviously), a humidifier (basically a water canister with a sponge and tubes) some tube splitters and twist valves and most importantly, a small air pump.
The small air pump is what I'm having problems with at the moment.  This is the pump. Obviously it's a 3v pump.  I will be using the supplied 9v battery cable when the project is ready, so I understand I'll have to use resistors to bring the voltage down so I don't burn out the pump.  As I said, I'm new to this, so I'm trying to figure out ohms law to find out what kind of resistor(s) I will need.  The problem is, I don't know the amperage.  Where would I find this?
I looked at the details for the pump and what looks like amps (or milliamps) is really just the product number.  Can anyone help me out?
Right now, I have my equation as r=6v / ?i  But where do I find the current?

The current used by a motor can vary. Normally the motor's datasheet would give you typical values. But in any case you don't want to use a voltage divider for this.

There are two serious problems with your approach, which you will need to change in order to end up with a sound solution.

If by "9v battery cable" you mean that you intend to use a 9v battery, this is highly unsuitable for motor applications given its low power storage capacity and high internal impedance - without extreme care to use sleep modes, it probably can't even run the Arduino alone for a week.  It would be much more appropriate to use a larger capacity lower voltage source - 4 or 5 C or D cells for example.  A power supply could be another option, though given the water involved, be very careful to pick an isolated one and use a ground fault protected outlet.
Resistors are a poor way of reducing the supply voltage to a motor, as they are not only wasteful, but the applied power will depend too much on the load.  A professional solution would use pulse with modulation to apply the supply voltage at a reduced duty cycle - something you can try with one the various motor shield, but you will need to be careful not to overheat the motor by using too high a duty cycle.

Probably your best bet would be to buy a pump with a 6 or 7v motor (as is showing up in the associated products at the bottom of that page), or even replace the standard-form-factor motor in that pump with a higher voltage one.  A 7v or so supply voltage can then be a compromise solution for running both the motor and the arduino.

Great post! So much to say, but so few characters! Luckily, I purchased a 6v air pump before I purchased the 3 (the 6v shipping was going to take forever) so I will use the 6v instead.  I didn't even connect the dots on the PWM spots, I will look into that instead.  I'm not sure of the amperage, so I'm not sure how long this system would last even with larger mAh batteries.  I see someone said the Arduino draws about 25mA while running code.

You can reduce the current consumption of the processor by using sleep mode and only occasionally waking up to monitor, using the internal RC oscillator or at least a clock divisor, etc, however this may be tricky to do when using the arduino libraries.  Additionally, other components on the board including the regulator may waste power.  Make sure you never leave a signal driven against a pulling resistor.  If you ultimately go with batteries you may want a custom board with a low frequency clock, low quiescent current regulator, and no onboard communication interface.

all great points.  I guess I just want to do this as a prototype (as the Arduino is supposed to be used) and then find someone to flash a chip/board for me for this purpose alone.  Is that reasonable as well?

Doing a simple proof of concept before chasing battery life can be worthwhile, yes.  There is some risk of boxing yourself into a corner it will take work to exit if you ultimately want to run on batteries, but re-implementing things a second time based on lessons learned will obviously take less time than the first attempt.

Unlike voltage, which depends on the source, the current depends on the motor itself. To find the current, you need to run the motor and measure it with a multimeter:
              +------------+
    +---------+ Multimeter |
    |         +--------+---+
+---+---+              |
| Motor |              |
+---+---+  +--------+  |
    |      | Power  +--+
    +------+ source |
           +--------+

Note that when the motor is actually pumping, it will draw more current.

It also depends on how the motor is running. The more torque the motor is exerting, the more current it needs.

Aah I see. Luckily it's just an air pump so when the motor is pumping, it should be at its highest needs.  A friend told me about a DC power supply that is variable, so I could run it at 3v and measure the current from there without risk. Would this be the same thing?

@ntgCleaner I think that would work.

It will be at its highest needs when blocked. Put a circuit breaker between the full speed and blocked currents so that you don't burn out the motor.

good call! I purchased a DC variable power supply (1.5-15v) from Tekpower.  Whether I need it or not for this project, I'm sure I'll be able to use it sometime!