text:
Serving binary file with ESP8266WebServer
I am currently using a Nodemcu ESP8266-12E with the Arduino IDE in order to control my boiler. Everything is working fine, however I haven't figured out yet how to serve binary files, eg. images. (I am hosting them on a server at the moment).
ESP8266WebServer server(80);

void setup()
{
  [...]
  server.on("/", handleResponse);
  server.onNotFound(handleResponse);
  server.begin();
}

void handleResponse() {
  if (server.uri() == "/style.css") {
    server.send(200, "text/css", "[css]");
    return;
  }
  if (server.uri() == "/favicon.ico") {
    server.send(404, "text/html", "Not set");
    return;
  }
  [...]
}

unsigned char favicon_ico[] = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};
unsigned int favicon_ico_len = 894;

Converting the arary to a string and serving it with server.send does not work and  server.stream expects a file.

It looks like you can use the send_P function to send raw PROGMEM data:
void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength);
I.e., (from what I can gather):
PGM_P favicon = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};

server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

Incidentally, PGM_P is just a typedef for const char *.

Thank you very much, after changing unsigned char favicon_ico to const char favicon_ico it worked with server.send_P()! Setting it to PGM_P somehow threw an error.


text:
Arduino as analog to digital converter for temperature sensor
I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.
So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.
I think this is possible but I can't figure out how to do it because I can only set pins to high or low.
Can somebody help me? Thanks a lot
P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone

Serial connection (RX/TX) seems like the way to go. If it didn't work it only means you had a bug to fix.

Both the ESP8266 and the Arduino have UART serial interfaces. This is by far the simplest method of communicating between two boards.
Connect the TX of the Arduino, through a voltage divider to drop it to 3.3V, to the RX of the ESP8266. Connect the grounds together. That's all you need. Yes, you can connect the TX of the ESP8266 to the RX of the Arduino but if you are never going to send anything from the ESP8266 to the Arduino then there is little point.
Then, with both devices set to the same baud rate, you can Serial.print on the Arduino, and Serial.read on the ESP8266. Just follow one of the many many tutorials about communicating between Arduinos using UART.

source: Stack Exchange

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

sort: votes


text:
Size of String array
I am trying to find out the size of an array like this:
    String days[3] = { "Mon", "Tue", "Wed" };
Serial.printf("Size of array: %2d\n", sizeof(days));
for (int i = 0; i < sizeof(days); i++) {
    Serial.print(days[i]);
}

The result of the code above is 36 which is incorrect.
Do I have any other options considering that I don't know the size of the array to begin with?

sizeof() is the number of bytes and not the number of elements. sizeof(array) / sizeof(element) gives the number of elements.

No, the result is correct, you're just interpreting it incorrectly. If you want the number of elements in a statically-allocated array use:
sizeof(somearray) / sizeof(somearray[0])

Sorry if I post in wrong topic
follow answer of Ignacio Vazquez-Abrams, in case of size of each String in array is different? like String days[] = { "Monday", "Tuesday", "Wednesday" }; Thanks

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


text:
Server checkbox not working properly
I am trying to make an arduino alarm clock to which you can send alarm clock times over the web.
This is the HTML code
 <input type="checkbox" name="alarm1" id="alarm1">1</button>

It's sending the HTTP correctly but the rest of the code insists that the alarms are always on.
      if (_server.arg("alarm1") = "on") {
      alarm1 = true;
      Serial.println("Alarm 1 is set");
  }
  else {
      alarm1 = false;
      Serial.println("Alarm 1 is inactive");
  }

The alarm is always on because you are setting it to be always on.  You code should say:
 if (_server.arg("alarm1") == "on") {

To clarify, one equal sign is used to assign a value to a variable, two equal signs is used to determine if one value equals another.


text:
Feasability question
I have some experience with Arduino, but not (yet) with other AVRs or Raspberry/Orange.
I want to make a project with some slave devices (mostly Arduino Unos, one Arduino Mega). These all need to communicate with a controller.
This controller has about the following requirements: - It need to respond every 5 ms to some messages from the devices, within the next 5 ms. - It needs about 128 KB RAM space, but more would be more comfortable (although 1 GB is enough). - I need quite some 'programming' space (like FLASH) - The program that needs to run on it will be reasonable complex, so using a nice programming language would be convenient (Python/Java/C++) - SD or other nonvolatile storage is mandatory - nRF24LR01+ 2.4 GHz RF Transceiver - Like upto 8 LEDs for status showing - WIFI would be nice - Using an adapter (12V/2A?) would be good, no intention to run it on batteries
I think I can do it with a Teensy or Due, but those are reasonable expensive. Another option is an STM32 kind of AVR.
However, I an noticed Orange Pi Zero, which are very cheap. But I wonder if I get myself in trouble? I know Linux commands, never installed it on a computer though. Someone made a remark in another related question to go for a stronger AVR, but afaik an Orange should be suited very well for this (seeing the limited electronics involved).
Or would it be better to go for a Teensy or STM32?

first off, the due only has 96k RAM, you're not going to get much further on integrated chips.

Initially my plan was to add a 128KB 23LC1024 SRAM IC, but it makes programming much less convenient (since I cannot store directly/use variables/lists/arrays).

A Pi gives you lots of CPU power but I'm not sure how good it would to on the tight timing requirements.
It doesn't have everything you ask for but something like the NUCLEO-F746ZG may be an option. That gives you a 200+ MHz Arm M7 with floating point, 2 MB of flash and 512 kB of RAM. It has USB and Ethernet built in and has arduino compatible headers for connecting shields to give you things like an SD socket or a radio link.Plus you get 8 UARTs, (no more software serial :-)) and 6 SPI busses (obviously not all on the arduino headers)
You can program it either natively or in c++ using the mBed framework & online compiler.
It is around $20. There are cheaper variants with less processing power / memory available for a little less.

A RPi will be fine if you work on the bare metal. Note that you won't get any help with any peripherals so don't walk in expecting to whip something up on a e.g. RPi Zero W in a few hours.

@IgnacioVazquez-Abrams True, I was assuming the Pi would be running linux and possibly programmed in python. The CPU is more than capable enough, it's accessing that power without adding latency that gets tricky.

Can you give me a link where you can get it for $20 ... I mostly get my items from Aliexpress and there is is about $35-$40 ... in the Netherlands it's not for sale, only the discovery box for 50 euro (excl. shipping).

I checked for a NUCLEO-F446RE or NUCLEO-F411RE ... these are also quite acceptable for my needs.

http://nl.farnell.com have it for 22.5 euro.

@Andrew: Thank you very much ... strange I didn't found it before. I first buy the cheapest one from China go get a feel for Nucleo's (never tried one nor an STM32), and than the one you proposed sounds like the way to go!

Personally I use the mbed library and build system rather than the STM32 one. Mainly because it makes it easy to switch between lots of different Arm based systems depending on what I need at the time. Unfortunately it's not the best documented thing out there and while there is a support community it's no where near as active as the arduino one.

@Andrew: I now realize that the F746ZG is indeed one of the best options ... 128 KB is too small (since I also need space for the program stack/heap), and have 512 KB is than more than enough for future updates. ... I would have to check mbed library ... I heard of it but that's it. I will check into it, thanks (and hopefully I don't run into too many problems, being still an Arduino starter).


text:
Powering from 3V coin cell to VCC, using I/O pin as supply GND
I'm thinking of creating a "small" electronic dice.
(I will solder the button a little different though xD)

But there are some concerns on my design:
Powering from a coin-cell
It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?
Can I use a I/O as (input/supply) GND?
You can actually use outputs as positive voltage, and you can sink currents.
But does that mean I can connect the negative side of the coin-cell to an output, and sink it?
This way it should power my arduino's VCC pin through the "digital GND"
Using the reset button
I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?
(I probably won't use it though, it's placed inconveniently for this project, but I am wondering.)
A crude drawing below:
The fun thing is, polarity of the LED's/segments doesn't matter, since I can change which side is high or low? :)
Also, I've only drawn half the LED's/segments. And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.
(btw, battery GND pin should be pin 4, not pin 2)

Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for another (low power) device, but
you should power the Arduino itself from its Vcc and GND pins.

I could use the reset button, but would it still give me "random
  enough" numbers?

You will likely see the very same sequence every time you reset it.
There are ways around this:

You can seed the random number generator (RNG) at startup with an
analogRead() from an unconnected pin, but it's not clear how much
entropy you can expect from this.
You can save the RNG's entropy into the .noinit memory section, this
way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the
dice, if only for one reason: the time when the user presses the button
(that you read with micros()) is a very good entropy source for
seeding the RNG.
For example, whenever the user presses the button you could:
srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

This way you combine the entropy from the button press with the entropy
from the analog pin (if any), with whatever entropy may already by in
the RNG.
Edit: More on entropy gathering.
As you seemingly already know, random() is a pseudo-random number
generator intended to produce a sequence of numbers that look random.
Unless you have some other source of randomness in your program, every
time you restart the Arduino you will get the very same sequence of
numbers. Getting true randomness (also called “entropy”) on an Arduino
is not so easy. Here are some ideas you may want to explore.
Read from an unconnected analog input
This trick seems to be pretty popular. It can even be found in the
Arduino documentation on
randomSeed():

use randomSeed() to initialize the random number generator with a
  fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a
test program that prints out the output of analogRead(0) and it seems
to cycle through the same few values in an almost predictable way.
I estimate this gives around one or two bits of entropy per call. On the
plus side, each call takes just over 100 µs.
Read from an analog noise source
There is a lot of literature on building analog noise sources. Such
sources are used inside crypto-grade random number generators, but the
circuits are likely to be more complex than you would like. There seems,
however, to be a very simple alternative. In a comment to this
post, CharlieHanson wrote:

Connecting the analogue input to the collector of a run-of-the-mill
  transistor, with the emitter grounded and base open helps to make a
  noisy input.

I have not tested this idea, but it is certainly worth exploring.
Time user input
If the user is required to press a button to throw the dice, the timing
of the button press is probably the best entropy source you can have.
With a 8 MHz clock, the micros() function has a resolution of
8 µs (64 clock cycles). Assuming the user is unable to control his
timing better than 0.1 seconds, then you have more than
13 bits of entropy per button press.
If, instead of micros(), you use timer 1 running at the full CPU
speed, then you would have 16 bits of entropy per button press. And
you would not need random() at all, as you could just output
1+TCNT1%6. That would be like throwing a dart at a carnival wheel
spinning at 80 million RPM (8 MHz / 6)!
Measure clock drift
The drift of a clock relative to another clock can be used as an
entropy
source.
The ATmega chip in your Arduino has two independent clocks: the internal
“calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator
used by the watchdog timer. Both are low-accuracy clocks subject to
somewhat unpredictable drift, which is a good thing for this
application. You can gather entropy from this by configuring the
watchdog timer as a periodic interrupt source, and using timer 1 at full
speed to time the interrupt arrival times:
#include <avr/wdt.h>
#include <util/atomic.h>

// Configure Timer 1 for counting CPU cycles and the watchdog as an
// interrupt source firing (roughly) once a second. Call once in
// setup().
void configure_timers()
{
    // Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS10);  // prescaler = 1

    // Watchdog. This is a timed sequence.
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        WDTCSR = _BV(WDCE)  // enable changing the prescaler
               | _BV(WDE);  // ditto
        WDTCSR = _BV(WDIF)  // clear interrupt flag
               | _BV(WDIE)  // enable interrupts
               | WDTO_1S;   // timeout ~ 1 second
    }
}

volatile uint16_t wdt_time;
volatile bool wdt_fired;

// Watchdog interrupt service routine.
ISR(WDT_vect)
{
    wdt_time = TCNT1;
    wdt_fired = true;
}

// Add entropy to the RNG from the timing of the last WDT interrupt.
// Call periodically in loop().
void get_wdt_entropy()
{
    if (!wdt_fired) return;  // No WDT event since last time.
    uint16_t wdt_time_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        wdt_time_copy = wdt_time;
        wdt_fired = false;
    }
    srandom(random() ^ wdt_time_copy);
}

I have tested this idea by plotting the time differences between
successive interrupts. On an Arduino Uno clocked at 16 MHz, I see
short-time fluctuations with an amplitude of about 300. That should
provide around 8 bits of entropy per second.
Save the entropy pool across reboots
Once you have spent some effort to gather entropy from the environment,
it would be a pity to lose it all at power down. It is common practice
to save the entropy pool to disk when a computer shuts down, and restore
it at boot time. This avoids the problem of the RNG always starting in
the same predictable state. On the Arduino, you have no disk, but you
can use the EEPROM instead. The problem is you cannot know in advance
when the user is going to switch the device off. Then, ideally, you
would save the entropy every time the user requests a new dice value.
The new problem is that the EEPROM is only guaranteed to work reliably
for 100,000 write/erase cycles. This may not be a serious problem
(100,000 is plenty of throws), but it can nonetheless be mitigated by
using a wear-leveling scheme, where you distribute the writes across the
whole EEPROM instead of always overwriting the same bytes.
Wear-leveling can add significant complexity to your program, but it
turns out there is, in this particular case, a wear-leveling scheme that
is trivial to implement: just write at a random location! At startup,
you do not know what was the last location written to, but you do not
need to: you read and mix the whole contents of the EEPROM:
#include <avr/eeprom.h>

// Save the entropy to EEPROM. Call this every time the user requests a
// new value.
void save_entropy()
{
    uint32_t *address = (uint32_t *)(random() & E2END & ~3);
    eeprom_write_dword(address, random());
}

// Restore the entropy from the EEPROM. Call once in setup().
void restore_entropy()
{
    uint32_t seed = 0;
    for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
        seed ^= eeprom_read_dword(address);
    srandom(seed);
}

Combine the entropy sources with the XOR operator
As you probably already noticed, the bitwise xor operator (^) is used
every time one wants to combine entropy sources. The main reason is
that, if a and b are independent random variables, then a^b is at
least as random as the most random of a and b. Which means that
XORing a “good” random variable with a “bad” one is harmless. This is
somewhat formalized as the piling-up
lemma.
As an example, doing randomSeed(analogRead(0)) at program startup is
fine, but doing it repeatedly during program execution is a terrible
idea: most of the time this will put the RNG in one of a very few
states. If instead you
srandom(random() ^ analogRead(0));

then you are combining the current randomness of the RNG with the output
of analogRead(), and putting this back into the RNG. And this is
harmless even if analogRead() is quite predictable.
A side note on randomSeed(): Arduino releases prior to 1.6.5 had a
bug that would truncate to 16 bits the entropy provided with
randomSeed(). On those releases it is better to use the avr-libc
srandom()
function.
The bug has since been
fixed.

It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

That is correct.

You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

Definitely not. That is a sure-fire way to kill the Arduino.
Also you have a Catch-22 situation. To make the pin conduct to ground you have to set it to output and switch it LOW. How can you do that if the chip is powered off? You need to power the chip on in order to power the chip on. It just can't work.

I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

You will only get random numbers if you seed the PRNG with a random number. If you can get a source of entropy (noise on an analog pin for instance) then yes, that could work.

And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

It's not "better" - it's REQUIRED.  With just one resistor and one segment on that segment will get 8x the current compared to having all 8 segments on. You then either get very dim segments with lots on, or smoke from segments when not many are on.

Hmm, and what if I loop through all segments rapidly, having only one on at the time? Then one resistor should do? Since it makes it much easier to wire. Or I should indeed accept the difference and very dim with all on?

If you only have one segment on at a time then yes you can get away with one resistor.

Yup, that's a nice "hack". Equal brightness, efficient power usage. The trick for randomness is also a good one. If using milis and resetting device, it wouldn't be smart, since milis will the almost always be the same? Is it good to reseed once in a while?

It can increase your randomness, yes. Especially if you reseed at random times ;)

Hmm, yeah when using time as a "random variable" you should avoid seeding at specific times :) I could also try running it and collecting the data, test different methods, should be interesting.

Yes you should be fine with the voltage from a coin cell - though don't expect it to last long!
No you can't use an I/O as ground - they are set to input by default, and even if they weren't, if wouldn't be guaranteed to work, and even if it did happen to work*, it would be horrible.  I don't quite understand why you want to do it this way - why not just connect the cell's -ve to the GND pin, right next to the VCC?
If you seed your random number generator suitably (e.g. from an unconnected analogue input) you ought to be OK since that will suitably random - you'll be reseeding it each time with a different seed.
*Stranger things have happend! The very fist ARM chip worked without power, running from parasitic currents from the inputs, as they discovered by mistake when they tested it with the power supply disconnected.

The reason was that when just inserting the coincell holder, the other pin could only land on an IO pin. Or I would need some wiring. It should only show the digit for a short time when pressed on the button. But what battery is most energy per size?

I should look up the battery voltages by myself, sorry. Might even use USB power bank, but doesn't really look small. And might put it in proper board indeed.

Ah, that's a coin cell holder in the photo! I thought it was something you'd rested it on to take the picture! :-)  Bear in mind that you're probably going to want an off switch, unless you want to take the battery out, so maybe you can wire that in neatly somehow.

Yeah, when I look at the picture again, it actually looks awfull. I'm ging to use a protoboard as backplate and probably 2 digits (for other games). An on/off switch is indeed better. And maybe even 2xAA

You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

It would not be a good idea to use a input pin as they can only sink a maximum of 40mA per pin.
Also, incase any power surges are experienced and it is connected to Vcc if that 5v is exceeded then it could damage your board. It might be a better solution to use the RAW pin even if it does ultimately use more power.

I agree on not using a digital pin as GND. But, the RAW pin needs a higher voltage? And a power surge from a battery is some what unlikely?

Not from a battery as such however since the design is exposed and open to surrounding sources of static charge it could affect the boards operation

Good point, though any static charge on the 5V/GND pins may cause failure? But it indeed is more likely to happen (like when touching the battery if it's connected). But the RAW pin has ESD protection?

I think a simple (and aesthetically pleasing) solution would be a case for the whole design. This would mean it could use the 3.3v VCC pin which would use less power compared to the RAW pin.

True, but I don't have a laser-cutter or 3D printer ;) I might design a case and let it print by one of those online 3D print services.


text:
Powering multiple (separately enclosed) Arduinos by one adapter
I currently use one Arduino, but my plan is to use multiple Arduinos.
These Arduinos will be relatively close together (within one meter or less), and depending on the configuration I want 2 to 5 Arduinos, all in separate enclosures.
I don't expect a high power consumption from all of them, but I don't want to use batteries. So I would like to use a 9V or 12V adapter with 2A (cannot find higher amperage).
My questions:

Can I just split the cable, and add extra plugs for the other Arduinos? (so like a parallel circuit of Arduinos)?
Is it a problem if I only would connect 1 Arduino? (I don't think so)
Is there a maximum Amperage I can divide this way? (I mean what if I would find a 5A adapter?)
I see 9V or 12V adapters ... why would this matter, since the Arduino works on 5V anyway. I don't need to drive external motors, just like 5 small LEDs, some ICs (optocouplers, SRAM) and some basic connectors (like MIDI, later DMX, Audio etc), an RF or ESP01 module.

The difference between Vin and 5V is all dissipated in the linear regulators of the Arduinos. Thus a 9V adapter would be more energy-efficient and generate less heat on the regulators.

@EdgarBonet Thanks ... that means a 9V should be enough, and probably with 2A I can support (hopefully) 5 Arduinos ... I guess I can measure the amps usage currently if I probe at the right positions (have to find out where)

using just 5v would be even better; cooler, cheaper, more efficient, allows more sensor capacity, etc. basically, removing any extra source of heat from the MCU itself.

For the annoying personal downvoter: please mention why you voted my question down.

more than 2500 views and -1 score... interesting.

Can I just split the cable, and add extra plugs for the other Arduinos? (so like a parallel circuit of Arduinos)?

Yes.

Is it a problem if I only would connect 1 Arduino? (I don't think so)

No.

Is there a maximum Amperage I can divide this way? (I mean what if I would find a 5A adapter?)

You can draw, in total, whatever the power supply can provide. If 10 Arduinos need 500mA and you have a 5A power supply you can power 10 Arduinos from it.
If they draw just 50mA you could power 100 Arduinos from it. It's all just a matter of managing the wiring in a suitable manner (connecting hundreds of wires together gets tiresome).

I see 9V or 12V adapters ... why would this matter, since the Arduino works on 5V anyway. I don't need to drive external motors, just like 5 small LEDs, some ICs (optocouplers, SRAM) and some basic connectors (like MIDI, later DMX, Audio etc), an RF or ESP01 module.

12V will cause more heat dissipation from the linear regulator in the Arduino than 9V will, since the 12V has to lose more of the voltage as heat.

Thanks for the answer ... seems that 9V is enough (actually even less, but less than 9V is not possible).
I did a small calculation and I think I can be under 2A (which some adapters provide).

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


text:
Industrializing Arduino - 24V io? (Electronics)
I would like to make an arduino board that is capable of handling 24V i/o.
Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.
For input:
24v to 5v input scaling could be created with a voltage divider.
As far as I know, there will never run a high current into the arduino? So the power loss is minimal?
For output:
5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.
So I could choose to make half the I/O only input and half only output.

Could I combine the MOSFET and voltage divider, and in what way?
Are my "assumptions" about the I/O correct, or are there beter ways of handling it?
What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?

Sounds like you want isolated level switching, not just voltage dividers and MOSFETs. At least, that's what I hear when someone says "industrialize"...

Like this.

Sound more like a job for opto-isolators.

Or this: http://www.rugged-circuits.com/ruggeduino/

Very good points, indeed, putting opto-isolators in might be a better move. I kinda want to abstain from using a relais as I heard they can burn so that they won't stop outputting signal.
So my best shot would be 2-way opto-isolators that can work with 5V at one side and 20V (larger amperes) at the other side?
This would make it unable to use analog inputs for other than 0-5V though, but I'm not sure if it's neccesary to have those. The voltage dividor with an overvoltage protector might do for analog inputs?
I guess I'm going to check more of those other designs, before I try to make my own

You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.
If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.
To scale up the outputs to 24V I would suggest one of the following options:
a) Relay board /
These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC.
Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.
If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!
Many of these boards are available on the web, so it's a quick solution.
b) Optocouplers /
Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely.
They are silent and fast acting. Available for AC or DC and up to 600V.
Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)
c) MOSFETS or Bipolar transistors /
If you are designing your PCB then this could be an option.
Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end.
I this case you get complete control of PCB layout which might be a consideration.
If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).
A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.
If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.

I was indeed looking for a "broad" solution, as in using the arduino like a PLC. So at this point I don't have any more details on the environment. Also, I posted this to check if my ideas were right. I found that opto-couplers might fit best, or even in a combination with some relaises. I was unaware of the existence of optocouplers, so this really helped.

24 VDC industrial circuits are typically based around 4-20mA measurement (AI) transmitters and outputs (AO) to valves and other actuators. There are also 24 VDC DI & DO's. I believe that you should investigate Analog Devices and Texas Instruments chips for 4-20 mA interfacing.  They have a number of chips for reading in and outputting 4-20 mA.  You can get started if you Google "analog devices 4-20ma application note" or "texas instruments 4-20ma application note." If you Google "4-20mA application note," you will find that there are any number of people that make these chips and lots of people that provide application notes for 4-20mA loops.
Any information provided here is on a Caveat Emptor basis.

It just came to my mind that an PLC wouldn't directly power something. I always had that thought because it was 24V (but amperes would be critical, and nobody is going to run 2A through a PLC?)
So I could get some 2way opto-isolators and just hook them, like a regular PLC, as they aren't made for powering directly either.

This is a pretty old post but I'm sure people still search this topic from time to time. If what you are after is making an arduino into the plc replacement of sorts, look at these links. I've done these tasks and they worked pretty easyily for me. When you compare the cost of a plc to these alternatives, you won't find a new plc for the same price:
https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/
and
https://www.visuino.com/ - A visual ide


text:
Help understanding circuit for button example
I´m working on the button example
.Basically, i don't quite get the use of this connection.

Also, the breadboard i'm using is not quite the ones i see on most tutorials.

is there any 'mapping' i could make between them?
I really appreciate any help you can provide.

The connection in that picture is pointless.  They are just putting power and ground on the top set of rails, but they aren't using it.
Your breadboard has only one rail on either side.  So you'll have to designate one for power and one for ground and you'll need some slightly longer wires for some of the connections.

Thank you! i get it now, i'll see if i can make it work.


text:
Arduino Nano off 9V : is there any change to output?
I'm building a test circuit on an Arduino Nano that consists of a simple 220 Ohm resistor and an LED on pin D2 which is routed back to GND (ground).
It's as simple as this:

It's running a very simple program to blink the LED on and off.  It all works while connected to the USB port.  I know the USB port provides 5V.
Now I want to run it my Nano and circuit from a 9V battery.  The datasheet says that you can run the Nano on 6V -12V by connecting it to pin 30 (VIN).  Of course, I know I'll have to add a line from GND back to the (common) battery ground also.
When I do that, the voltage on the OUTPUT pin (D2) will never be higher than 5V though, right?
I should not expect any change in output voltage even though I'm changing voltage that is powering the Nano, correct?

It looks like VIN connects to a LM2940, 5 volt regulator, so the voltage on the OUTPUT pin (D2) will never be higher than 5V.

Side note: The actually used voltage regulator differs from board to board (with chinese clones etc) so you always need to look at the datasheet. For the LM2940x in the 5V version, the output is between 4.85 to 5.15V (given about 10V input voltage at 25°C). Other regulators (AMS1117,..) might differ. [http://www.ti.com/lit/ds/symlink/lm2940c.pdf]

That's a great, definitive explanation because you've also shown me how to discover this information on my own. Thanks very much and for the note about the clones.

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


text:
How can I identify the abilities of my ESP32 module?
I was attempting to discover how to identify my ESP32 development board.
I was wondering how to discover the abilities it supports.
Here's a snapshot of my board:

This was related to a question I asked about which Arduino board to use.

I discovered the ESP Product Selector (official website) to answer this question.
Here's the board specs, dataheets and all the rest for my board.
Now you can

go to the main page
find your product in the list (bottom portion of page) and select it
Get all information

Make sure you match :

What is printed on your ESP32 on that main chip area
To the exact text in the list (on the web site).

You can see a graphic on the web site for the individual item so you can try to match the two.  Here's what mine looks like:

This will help you know you've got that exact one and then you can view the abilities listed for it.
In my case I was wondering about BLE and I discovered that these support BLE 4.2 (not 5.0) like newer ones.
What Site Looks Like: How To Use

You can click that to see the image to see if it matches what is on your chip

You can float over this area to see the details of specs - see the BLE is 4.2 example

This area can be scrolled and has all the details of your specific ESP32

You got an ESP32-WROOM-32. Here is the datasheet.
https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32_datasheet_en.pdf
ESP32-WROOM-32 is a powerful, generic Wi-Fi + Bluetooth® + Bluetooth LE MCU module that targets a wide
variety of applications, ranging from low-power sensor networks to the most demanding tasks, such as voice
encoding, music streaming and MP3 decoding.
At the core of this module is the ESP32-D0WDQ6 chip*. The chip embedded is designed to be scalable and
adaptive. There are two CPU cores that can be individually controlled, and the CPU clock frequency is adjustable
from 80 MHz to 240 MHz. The chip also has a low-power coprocessor that can be used instead of the CPU to
save power while performing tasks that do not require much computing power, such as monitoring of
peripherals. ESP32 integrates a rich set of peripherals, ranging from capacitive touch sensors, SD card interface,
Ethernet, high-speed SPI, UART, I2S, and I2C.
You can make an advanced ESP32-WROOM-32E IoT Dev Board. This board will integrate temperature and humidity sensor, gas sensor etc. :
https://www.pcbway.com/project/shareproject/Advanced_ESP32_WROOM_32E_IoT_Dev_Board_90812ac7.html


text:
Programming ATMega4809 via Atmel-ICE with Hex File from Arduino IDE - why doesn't the code loop / work?
Background
I am programming a 40-pin ATMega4809 (datasheet)  using ATMEL-ICE programmer.
I'm simply using the Atmel Studio to upload a HEX file to the chip.
I generate the HEX file using the Arduino IDE.
I'm using the very simple blink sample sketch with a slight modification which uses a different output pin for the LED.
const byte LED = 6;

void setup() {
  // initialize digital pin LED as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I have a LED (with resistor) connected to PA6 on the ATMega4809.
Code Result
I use the Export compiled binary choice in the Arduino IDE to generate the HEX file.

I then use Atmel Studio to upload the HEX file to the ATMega4809.
When I do, the program runs and the LED turns on.
However, I never see the LED turn off (blink).
Do you know why this might be true?
Things I've Tried

I've tried increasing the delay value to see if internal crystal is
set different and the timing is different or something.
I've set the internal crystal to different values (ranging from 1Mhz
to 20Mhz) and haven't seen any difference.
I've considered that it could just be not looping, so I've tried
various things to see if that were true or not.
I've placed all of the code in the setup() function to see if it
would working differently -- it didn't, it still just turned the LED
on but never off.
I've tried turning LED on in setup() & off in loop() to
insure both are at least running once and they are.

NOTE: I know the HEX file is being properly uploaded because when I alter the program and upload different ones (turn on/turn off led) then the code does seem to either turn the LED on or off.
I've also verified the code using Atmel Studio -- reading the chip's memory out to a file and doing diff.

for what board do you compile in Arduino IDE? why do you think pin 6 is PA6?

I was trying not to get to deep into the weeds, but I downloaded special boards from https://github.com/MCUdude/MegaCoreX These support the 4809.  Also, that's a good question about PA6.  I just noticed that when I used pin 7 (in IDE) I could turn on PA7 and when I used pin 6 I could turn on PA7.  But, you're right, I need to look closer at that.  Do you see something different somewhere?  If so let me know. thanks. Also, if I build the HEX for the Nano Every (which uses the 4809) it does not turn on PA6 / PA7 using 6, 7.

Because of the great question asked by @Juraj I thought about how pins are mapped (and that I was probably thinking wrong about that mapping).
I searched for and found the following diagram:

Notice that D7 is mapped to PA1
I switched the code to use Digital Pin 7 (const byte LED = 7;)
I then switched the LED in the circuit to be connected (with appropriate resistor) to PA1 which is actually PIN 34 (on my ATMega4809 40 pin).
Back in the Arduino IDE I switched the board to Nano Every (which also uses the ATMega4809).

I compiled the code.
Then I exported the HEX file and uploaded it to the 40 pin ATMega4809 using Atmel Studio.
With Bootloader Or Without
Didn't Work: With Bootloader
The first time I tried it i selected the HEX file which contains the bootloader and it didn't work.  The LED didn't flash.
Did Work: Without Bootloader
I then tried uploading the HEX file which does not contain the bootloader and the LED began flashing as expected.
Solved!  All because of the great question which got me thinking better.
Thanks,
Here's a very fast video of it in action (youtube).


text:
ATMega4809 via Nano Every marked as 20Mhz, but does this confirm it is actually at 16Mhz?
If you go to the official Arduino Nano Every page and click the Tech Specs tab, you'll see that it lists it as running at 20Mhz.

Turn On Verbose Compile
However, if you go into the Arduino IDE and go to File...Preferences... and turn on the Show Verbose Output during: compilation then you can examine how the board is actually set when a program is uploaded.

Examining the Output
When you look at that output you will see that it seems to be setting the board to run at 16Mhz.

Am I Looking At This Properly?
It looks to me as if the board is actually set to run at 16Mhz, right?
Am I looking at that properly?
Extra Question
I'm attempting to confirm this because I am :

writing code in Arduino IDE
Compiling in Arduino IDE (to generate HEX file).
Uploading to a stand-alone 40-pin ATMega4809

The ATMega4809 datasheet states the following:

If I upload that sketch to the ATMega4809 40-pin chip, that means it will expect to run at 16Mhz, right?
Set Fuses?
Will the 40-pin chip be set to 16Mhz by the HEX file or will I need to set fuses on the chip to insure the chip is running at 16Mhz?
FYI - Compiled For Correct Board
Also you may wonder if I had the wrong board selected when I compiled, but here you can see I chose the Nano Every.

With the Nano Every they went out of their way to make it look like as much like original Nano, to the point of providing that "register emulation" feature to make it appear that it has the 328P's older style of GPIO registers.  Running at 16MHz just make sense if you want to behave like the common Nano as much as possible.
If you want to convince yourself that it's running at 16 MHz, you can blink an LED with causes of __builtin_avr_delay_cycles(16000000); in between.  This busy-waits for the requested number of cycles.  If it's running at 20 MHz instead of 16, you would see something faster than a 1 second delay.
They keep the configuration fuse values in a file fuses_4809.bin.  On further investigation, it's not entirely clear what that file is for, despite containing the correct values.  The actual OSCCFG value being used (which is the same in the file) is defined there directly in the boards.txt:
nona4809.bootloader.OSCCFG=0x01

So you can see it's set for 16 MHz on the Nano Every.  The -DF_CPU in the command line originates from a line in boards.txt for the Nano Every:
nona4809.build.f_cpu=16000000L

and works its way into the compile command-lines via a line in platfrom.txt:
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} "-I{build.core.path}/api/deprecated" {includes} "{source_file}" -o "{object_file}"

The D_CPU macro exists to inform the compiled code what frequency it will be running at.  The OSCCFG is controlling the actual frequency, it's important that they agree for any timing related code.
When you upload it's the "-Ufuse2:w:{bootloader.OSCCFG}:m" that becomes "-Ufuse2:w:0x01:m" in the avrdude command line generated from the upload recipe in platform.txt that has the actual effect of configuring the chip for 16 MHz.
If you really wanted to run at 20 MHz, you could try tweak the definitions of these, but it probably makes more sense to look at something like MCUdude MegaCoreX which appears to have a board definition for the ATMega4809 at 20 MHz.

Thanks for the info and idea. I will try that and see what I get.

Thanks a ton for that additional info on FREQSEL.  I was reading datasheet and attempting to figure out how all that is set.  Really helps.

I just updated because I noticed the bin file isn't actually used in avrdude.  They're taking values directly from boards.txt properties, which has the same OSCCFG anyway.  But I changed it for accuracy.

The second to to last paragraph is more explicit on how the chip becomes programmed to 16 MHz, that is programmed with the 16 MHz oscal value.  Something I should have mentioned earlier, more clearly.  This is the same command-line, same instance of running avrdude that issues the -U:flash:file.hex:i that gets your compiled sketch code into the chip.  I'll integrate that later if I have cause to edit again.

So much helpful information.  Thanks again for adding so much.  It's helping me get my code flashed to the chip so I can test.  Really great.

It runs at 16Mhz because all of the timing code in the Arduino library assumes 16Mhz - running at 20Mhz would make all the timing code (sleep(), etc) not work like you might want. Since Arduino is targeted at everyone from beginners to advanced users, and strives to have "plug-n-play" compatibility with nearly all ATmega Arduino compatible chips... keeping things consistent is the way to go. Advanced users can override stuff with fuses and their own timing logic, and beginners can have things that "just work" out of the box.


text:
Will analog servo work with Arduino servo library?
I ordered some cheap servos from Amazon before I noticed that there seemed to be two different kinds (digital & analog).
Mine are Tower Pro SG90 Analog (http://www.towerpro.com.tw/product/sg90-analog/)
I was trying to get mine to work with an extremely simple sample code (below) using the Arduino Servo library (using digital pin 3) and I was experiencing the jitters.
I read over the solutions at : https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking
While reading that I learned that there is also a digital flavor of the servo:
http://www.towerpro.com.tw/product/sg90-7/
I'm wondering if that is part of the problem I'm seeing with the servo jittering.  I haven't seen this addressed elsewhere.
My questions are:

Are those servos even different? Maybe that is just a marketing
thing??
Do I need to switch to using an analog pin for the servo data
    connection?
Is it even possible to use the Arduino Servo library for this
purpose or do I need to use some manual code (like analogWrite()) and move the servo to an analog pin?
Or, should it work completely fine and the jittering is just some
unrelated problem?

Here's the simple code I'm using:
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

"Analog" servos are the traditional PWM form which example servo code assumes - in fact the term "analog servo" is rarely used in the hobby context as those are the normal type, while "digital" would designate something supposedly premium, either incorporating a microcontroller inside and/or communicating by some more complex scheme.  If you're having a problem, it is something other than the use of a traditional style servo.

If you want to put that as an answer I will set as answer.  The distinction of analog v digital on that tower pro site confused me.  Thanks.

Seems like it would be more useful if you edited this to be about your actual problem.

That's a good point.  I was just thinking of people who have the jitter problem and notice the analog v digital servo and then find this and have an specific answer that it is not the problem.  There's a lot of discussion about the servo jitters out there.  :)

In general, embedded processor like an Arduino have less jitter problems than processors running an entire OS like a Raspberry Pi.  This is because the embedded processor is likely only controlling the servo while the processor running an OS is busy sharing its resources with all the other normally running processes in an OS.

There's a discussion here about the difference. The short answer is they both are commanded by a PWM signal but differ in the internal control circuitry that responds to it.

Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.
Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?
This analog servo requires PWM, so is pin 3 of you board PWM capable?
How fast does you servo rotate?  At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.


text:
How to merge 2 batteries socketof 6v each
i want to merge 2 batteries socket of 4 AA 1.5v batteries , how can combine them to have 12v ?

Connect the + of A to the - of B. The + of B and - of A are 12V.


text:
How to turn servo to a specific location and then turn over
I work on my first arduino car project and i want to turn my servo to a position with a letter input
This is my code so far
 #include <Servo.h>
Servo servo;

 void setup() {
 Serial.begin(9600);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
 }

 void loop() {

 if(Serial.available()>0){
 int  caz=Serial.read();
 switch(caz)
{
  case 'w':
      digitalWrite(8,LOW);
      digitalWrite(7,HIGH);
      break;
  case 's':
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      break;
  case'd':
       servo.attach(12);
       servo.write(0);
       break;
  case'a':
       servo.attach(11);
       servo.write(180);
       break;
   default:
       digitalWrite(7,LOW);
       digitalWrite(8,LOW);
       servo.attach(0);
  }
}

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .
And also i would like to do that to my motor , moving a bit when i input the key.

Nice use of a switch statement :D

I found out that my servo 360 Parallax has continuous rotation

You should get a 180 degree servo. You code looks fine and it should work with a 180 degree servo. Read my comment under the answer by Matt. Using .write command on continuous servos tells them the speed and direction in which to rotate, not the angle.

@user6317433 are you still in need of an answer?

Rather than writing to 180 and 0 write to a variable.
static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;

Doesn't the servo.write need to be outside of the if statement?

'MovementAmount' it should be the position ,number?

@Matt does it matter what kind of servo i have ?

@Gerben - Doh :)  That would help wouldn't it, I'll edit it.

@user6317433 - The movement amount is the amount you want it to move by every time you press the relative key.  You will need a block of code like this for case 'a'.
I don't think a continuous servo will affect the code, but you will have to remember to use -MovementAmount and +MovementAmount. otherwise it will turn around where you don't want it to go.

@Matt I actually believe that it won't work with continuous servos. When saying servo.write(180), that means rotate full speed one way. write(0) is full speed the opposite way. 90 is stop. I do not think that there is a way to get precise angles with continuous servos.


text:
Communication between python script and Arduino sketch
I'm trying to transfer data beetween the two scripts. I'm already using the YunMesseger library (https://github.com/plotly/YunMessenger). But it only make the
Arduino -> Python
communication.
I would like to know how to make the reverse way.
I would like to point that I'm search for a solution that doesn't involve the use of the Bridge, because I don't want to have concurrency problems.

What do you mean by concurrency problems? For example, if you use bridge's mailbox, I'm pretty sure that messages from multiple sources just go into a queue on the Linux side, and the 32u4 can check this queue at it's leisure.

One option is to use spacebrew. This is a cloud-based service, however you can run your own server which is based on node.js, so it should work on the Yun.
Your Arduino can then send or receive data using yunSpacebrew, and you can connect it to python using pySpacebrew. This is a pure python library, so it ought to run fine on the Yun.

Thanks for the comment. I'm aware of spacebrew, however I'm trying to build a service similar to theirs but integrated with other solutions I'm developing. That's why I need to know how to make this communication. Looking at their source files I saw that they use Console.read() in the arduino part, but I couldn't find how they do the python part.


text:
Use an ethernet shield and RFID rc522 together on a mega?
I am using an Arduino Mega and I would like to connect a rc52 RFID reader and a network shield.  My problem is that both are set to use the same set of pins: 50 - 53.  Can I redefine the pins used so that I can use both at the same time?

Yes, I do think so. according to my Question with RFID and display it turned out that those pins are for serial communiacation. So I think it should work.
I can verify
 that it will work if you do use the ICSP headers MOSI/MISO/SCLK pins. Connecting those three with the RC552 as well as GND and 3V3. Also connect two other pins to SS and RST. This pins can be adjusted in the sketch on the Arduino.


text:
Is it problematic to 'check an input pin' or 'set an output pin' each step?
I am using an Arduino in an automation project which will be using a state machine to conduct a one-hour scenario.  Currently, the Arduino reads each input pin, runs its state update script, then sets each update pin.  99.99% of the time, each output pin will be set to the same state that it had in the last step.  Although it is better (in my opinion) to only set the pin when a setting changes, I was wondering if constantly checking and setting pins would have a big negative impact on the hardware?
Would checking a pin's current state (digitalRead or other method) before setting the pin improve anything?

what do you mean by "negative impact"? Are you talking about the speed the application runs? physical wearing of the hardware?

It does not hurt the Arduino to set an output pin to high if it was already set to high.  If you are concerned about performance, it is more efficient to just set the output pin compared to reading the pin and then setting it only if it's different

Would checking a pin's current state (digitalRead or other method)
  before setting the pin improve anything?

So instead of:
SetPin(OUTPUTPIN,true);

You want to do:
if(!PinIsSet(OUTPUTPIN)){
 SetPin(OUTPUTPIN,true):
}

To avoid writing to a pin (making it high) when it's already high/enabled?
Well doing so will waste a little amount of your programs' speed (it'll need to check each pin before setting it). But when you set a pin, when it's already high, it simply doesn't even change. And even then it's not required to check it first, Microcontrollers are basically made for this.


text:
Why does Arduino Tone example with 8 ohm speaker make USB port fail?
I'm using an Arduino Nano and attempting to run the basic sample program at:
https://www.arduino.cc/en/Tutorial/toneMelody
When I build the circuit they way they show (extremely simple) using an 8 Ohm speaker and connect the power to USB the Nano begins to power (never fully powers up) and then the USB port fails (I believe as a protection mechanism).

Is the schematic provided with that sample incorrect?
They say it can be used with an 8 Ohm speaker but they show it hooked up with e piezo.
Here are the comments from the Sketch:

Is it possibly overdrawing current with the 8 Ohm speaker?
Is the circuit incorrect in some way?
NOTE: Without the speaker connected the Nano powers up with no problem. I am also building other circuits with the Nano and they work fine.

If you have a pure resistive load of an 8 ohm resistor across a 5V voltage source a current of 625 millamps would flow -- USB by standard provides 500mA (https://superuser.com/a/690077/546860), but since the current is coming out of the digital pin in this case, you will overload your pin which has a max of 40mA (https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations). I'm also interested in how this is supposed to work (inductive load?).

Thanks for you input.  Because I was searching around and reading before I tried the simple circuit, I thought maybe it was wrong too.

Try putting a capacitor (maybe 470uOhm) in series with the speaker. This prevents DC voltage to pass through. But also keep in mind, that the pins are not designed to drive a speaker directly. It can work (tried it myself one time), but it is risky. The piezo doesn't let any DC current pass (since it is basically a capacitor with a special dielectric material in it), so it isn't critical.

@chrisl Thanks for hints. I think I'll be safe and use a piezo.

The circuit depicted is for a piezo and is reasonable for that use.  Using it with a low impedance magnetic speaker is incorrect (you'll find this is not the only glaring omissions in Arduino materials).  However, that does not explain the USB failure, since the current drawn by shorting an I/O pin does not exceed that limit.  Perhaps the speaker was accidentally connected between supply pins, rather than as shown.

someone should write an answer :-)

@Juraj - no factual, credible cause of the observed behavior has been identified.  Comments have made it clear what would be better, but there is no explanation of the failure that headlines the question.

@ChrisStratton If you write up your answer I will set it as answer since it was actually correct (see comment on other answer).  Also, I am still curious though (and afraid to try) about what would happen now that the circuit is fixed, if I re-connect the 8 Ohm speaker which some say will draw far too much current.  Is that true?  Will it draw to much current on the Arduino pin?  Is it unsafe to actually use an 8 Ohm speaker as shown?  Or can you do it?

As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.
In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.
There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.
One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).
The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.
When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.
Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.
So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.
A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.

This was an older question and I obviously figured out the issue to resolve the problem, however, you explained the difference between the piezo and the speaker and that was something I thought was incorrectly explained in the original Arduino.cc post so I marked this as answer.  Thanks.

Thanks for marking my answer. But I am still curious: did pin 8 survive and did you find the reason for the USB-port failure?

Pin 8 did survive. I found an old piezo buzzer on an old motherboard and desoldered it and used it for my tests.  I never did try the 8 Ohm speaker.  The real problem (as I mentioned) was that I had wired one of my pushbuttons back to 5V instead of GND.  However, everything worked (including that mis-connected pushbutton) until I added the piezo buzzer.  When I did that I was seeing the Nano get kicked off the USB port (thankfully) so it didn't burn out the Nano or the USB port of my computer.

The USB +5v opens to protect your computers from the connected device trying to draw too much current. The pin driver may have burned out, or it may, in fact, have delivered an excessive current (even if not the full 625 mA) but have been saved from failure by the USB supply having opened soon enough.

No.  The stated circumstances of this question would not draw more current than a USB protection device permits, because I/O pin output drivers are practically rather weak.   That would only happen if something about the actual situation were not as stated.

@ChrisStratton To close the loop on this-when I went to add the piezo I noticed that one of my input buttons was wired improperly.  The input button had 5v incoming and then a line to 100K resistor and out to ground. As I looked closely, I saw that the line from the resistor to ground was actually back to 5v (missed ground hole on bboard, hit 5v). There are 3 input buttons & other 2 were correct.  Also this input button still worked though wired improperly.  However, when the 8Ohm speaker was added (between pin 8 and ground) only then did I see this odd behavior of USB port fail (protection).


text:
Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560?
I'd like to offer some context about what I'd like to do because I might have misundertood something.
I'm trying to reduce power consumption on my device, an Arduino Mega 2560, and I've found this library
https://github.com/rocketscream/Low-Power
which uses the Watchdog to put Arduino on power saving for a predetermined interval of time; after that it reactivates what has been disabled and let the program continue its flow.
I searched for more information about the Watchdog and I found out several warnings about dealing with Watchdog on an Arduino Mega 2560, stating that it would only work with a modified bootloader:
This scared me a bit because I'm not very keen on risking to brick my Arduino (I absolutely need it to work on the next few days).
Now, I only have two Arduino Mega 2560 at my disposal and if I'm not mistaken, flashing the bootloader on an Arduino Mega 2560 using another Arduino Mega 2560 as a programmer can't be done because the procedure ends with errors:
( see http://forum.arduino.cc/index.php?topic=126160.0 )
Hence my most important question: if I test the watchdog functionality on my code (the sketch) and the Arduino happens to continually reset, can I fix the situation by powering off the Arduino?
(if you can help with my other issues as well, I'd be very grateful, I'm not sure I completely understood how these things work)

The problem you have is that once the watchdog is turned on it is very hard to turn it off again. There are certain procedures you have to go through to ensure it's turned off.
The default bootloader doesn't turn the bootloader off, and a reset doesn't turn it off either. The watchdog then fires whilst the bootloader is still waiting for communication from the PC thus making it reboot before your sketch has had a chance to run. Hence the change needed in the bootooader.
The only way to clear the watchdog is to remove the power. However as soon as your sketch runs and turns the watchdog back on you are then back at square one.
So you need to upload a new sketch to stop that happening, but that is tricky, since the watchdog keeps resetting and interrupting the bootloader. So what do you do? Well, there's a specific sequence you need to do.

Unplug the mega
Compile the new sketch
Hold the reset button on the mega
Plug in the mega
Press upload
As soon as avrdude starts release the reset button.

That way you have a chance of the bootloader running without your sketch having run first and enabled the watchdog. The bootloader runs just the once when the computer is tryung to upload the sketch, and with luck that will happen instead of your sketch running.

wow, that's a real gamble!
I'm not keen on taking such a risk for the moment, but I greatly appreciate your explanation, thanks!

It's not that much of a gamble - it's all a question of timing, and that just takes practice. Once you have the knack of releasing the reset button at the right time it's easy enough to replace the sketch with something that doesn't enable the watchdog. Until then, though, it may take you a few attempts to get the timing right.


text:
Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch?
I was reading in the OpenWRT wiki that you can indeed connect to the serial TTY console of an Open WRT roouter using the serial console if you're careful aabout the voltages.  https://wiki.openwrt.org/doc/hardware/port.serial.cables#method_b_no_physical_changes_to_arduino_board
However, I don't know anything about the voltages of my particular model of OpenWRT router a Netgear WNR2000v4.  I know that it is accessible via 3 holes on the board but I know nothing of the voltages.  Does anyone know or have experince with this about what voltages / wires to use to access it via the serial console?

3.3V. It's always 3.3V.

You can also find this information about the voltage of 3.3V on the site you linked

Why do you want to attach an Arduino to the UART port in the first place? If you can flash LEDE / OpenWRT on it or just activate the Telnet port, you can also remote-control the router, without having to have a Arduino logging into it over serial.

@MaximilianGerhardt Because the flashing didn't go so well...

@MaximilianGerhardt Will this do it? https://www.hotmcu.com/cp2102-module-usb-to-33v-ttl-p-35.html

@leeand00 I'm not sure if the CP2102 in this design outputs 5V or 3.3V on the TX pin. I'd buy a FT232RL module (https://www.amazon.com/dp/B014Y1IMNM) because there is a jumper to select either 5V or 3.3V output.

The WNR2000v4 serial port is at JP1: 115200 8N1 at 3.3V. Pads are, from left to right with the ethernet ports on right: [GND] [Rx] [Tx] [Vcc]

Source: https://wiki.openwrt.org/toh/netgear/wnr2000, PCB picture: https://wiki.openwrt.org/_detail/media/netgear/wnr2000/wnr2000v1_pcb_detail_small.jpg?id=toh%3Anetgear%3Awnr2000

So it has a mofset in it?

I have some wires that seem like they would work...they have little female ends on them; how am I going to know if the wires are okay for 3.3v?

If you are not connecting to a PC serial port, you do not need the mosfet. You linked Method B in your question, so I was operating under the assumption that was the path you chose forward.
It's not the wires you have to worry about at such low voltages, it's the device on the other end. If your Arduino is one with a atmega16u2, then it will work fine to hook up per your link.

@leeand00 For communication you only need to connect (from Arduino to Router) GND -> GND, RX -> TX, TX -> RX over a voltage divider. 3.3V is high enough to register as a '1' with the Arduino's 5V logic. Don't put your Arduino's 5V TX signal into the router though, use a simple voltage divider (example https://randomnerdtutorials.com/how-to-level-shift-5v-to-3-3v/)


text:
SIM800 or SIM900 library for Arduino
I have a SIM 800L module which I am using to send /receive SMS calls.
I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.
Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.
Actual Issue :
I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal.
If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.

Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for HardwareSerial.h in your Arduino installation and look for the #defined variable SERIAL_RX_BUFFER_SIZE in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it.
Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a while loop to do this efficiently, with timeouts and all).

Thanks a lot @brianrho . I have tried increasing the serial buffer as you mentioned. It works. But it has an impact on the dynamic memory for the program. Previously  in MEGA it was using only 25% for my entire program but now it has risen to 39% if i change both Rx/Tx buffers to 256. I don't think i need the Tx buffer to be increased. Even if I increase the Rx to 128 it works. Can this be further reduced to 96 ?? and keep the Tx as 64 . will that cause any other issues .. I have tried setting the CNMI to sim memory and used index to read that but facing the same issue.

I once again tried with the CNMI index logic and it works fine with the default buffer setting !!!:)

@user3689864 Great...but you'll have to use trial and error to know what RX buffer size is good enough for you. Keep in mind that the maximum length of an sms is 140 and the SIM can only store a max of 15 sms (in my experience) before it stops saving them. Receiving only notifications is a good way to handle a lot of SMS traffic since it would take about 25 notifications for a 256-byte Serial buffer to get full, and it also allows you to use the default buffer size, like you've discovered. There's no need to change the TX buffer size from its default value.


text:
How do I send an IR signal from an Arduino
I want to send a generic (not Sony, etc.) remote's signal from my Arduino.  I have already used a IR decoder program to capture the timing of the signal:
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    88, 88,
    174, 88,
    86, 86,
    88, 86,
    88, 88,
    86, 86,
    88, 174,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 2252,
    88, 88,
    174, 88,
    86, 86,
    88, 88,
    86, 88,
    86, 86,
    86, 176,
    86, 88,
    86, 88,
    174, 174,
    86, 88,
    86, 0};

Now I need to send this through the IR LED.  I have never written a program that can modulate a signal at this microsecond level.  How would I do this?

Use a library, like IRremote. Otherwise, you have to setup one of the pwm-timers to generate a 38kHz frequency, and then turn on and off this pwm based on the values you have captured above.

Use the IRRemote library as mentioned and use the IRecord example.  This will allow you to input a signal and then push a button which will send that signal from the infra-red LED on the arduino.

Please, take a look at Ken Shirrif's  IRRemote library, as it is what you need. I used it in some project and worked better than other solutions that I coded.

I think that this is the one I am using, I am having a hard time finding good documentation for 'generic' IR signals (or RAW signals)


text:
How can I add some additional 5 volt power
I have an Arduino which is being powered by a 9v, 2 amp power supply.  I have about 20 relays which are powered by 5 volts each.  I do not want to over work the voltage regulator on the board, so I would like to add another (possible 2) 5 volt regulator that I bought on amazon.  I am planning to:

Connect the regulators VIN to the Arduino's vcc (9 volt)
Connect the regulator's GND to the Arduino's GND.
Connect the regulator's VOUT to the Relay's VCC

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?
Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.


text:
What are some fun things you can do using the ICSP header?
I bought 10 Arduino Nanos for a project, each with all of their headers soldered in place.  Each was going to go into a tiny space, so I found myself needing do desolder the ICSP headers.
This led to a bit of a moral conundrum.  What would I lose by removing these useful looking headers.  They cover quite a lot of space on the nano, so they must be important right?  Am I going to regret removing these things when I finally realize how useful they are (I thought to myself.)
In the end, I did remove the ICSP headers, but the event got my thoughts going.  What is this header all about?  Why is it there?  What can I do with it?  I began to search for things that I could do with the ICSP header, but engaging results were not forthcoming ( except for this project:  https://www.arduino.cc/en/Hacking/ParallelProgrammer )
Anyway, I was more interesting in things that flash, move, jump, sing, and such, so are there any interesting things that can be done with the ICSP header?

Mostly useless. You can always add them back if you need to, or use the other pins (as the ISP header pins are the same as pins 11,12,13,RESET,GND,VCC)

Are they the same pins for all Arduinos (mega, nano, etc.)?

Not necessarily. Pins 11, 12, 13 are MOSI, MISO, SCK on the ATMega328 based boards (like Uno and Nano).

You can use every single last byte of flash on the device.
Since you're performing low-level programming of the device you get the entire chip to play on, without having to worry about bootloaders and such.

You can debug (breakpoint, single-step, watch, disassemble, etc.) the code on the chip using software on your computer.
Admittedly the devices you'd need in order to do so are more expensive than a simple ISP programmer and it only works with specific pieces of software, but it can be done.

One interesting thing I just came up with: you could use this header to attach a simple control panel for your Arduino.
Imbed the Arduino in any place/box/machine you like. Then use a cable with a 6 pin connector to connect the header to a small control panel.  The panel could have 3 buttons or LEDs, a reset button and a power plug.


text:
Can I access individual pixels on my 16x2 LCD display
I have a generic 16x2 LCD display connected to my Arduino.  I can use the standard LCD library to display characters, but are there way to turn on and of individual pixels?

It's possible to define custom characters for “generic 16x2 LCD displays” [ie, displays based on HD44780 or equivalent controllers], but only up to eight such characters at the same time.  See LiquidCrystal.CreateChar for details.  See page 2 and part of page 1 of the Print degree symbol ° on LCD arduino.cc thread for create-character examples that don't use the library.  Page 1 of that thread also shows a table of all the characters built into typical HD44780 controllers, some of which may perhaps meet your needs.
For pixel-by-pixel LCD control, look at graphics LCDs, eg the KS0108 or LCD12864 and similar.

I am attempting to make a bar graph, so the 'CreateChar' function is great, but I wish I had more than 8 characters (20 would be ideal.)  Still, this might be the way to go.  \Unfortunately, none of the predefined characters works well for bar graphs.

I don't see why you'd need 20 different symbols for a simple bar graph. You can only have 5 different widths (horizontal bar), or 8 different height (vertical bar). Just do a google image search to see some examples.


text:
What is the quickest and simplest way for two Arduinos, with network shields, to communicate?
I have two Arduinos, each with a network shield.  What is the quickest and simplest way to connect a cat5 cable between these two Arduinos and have them exchange strings?

Connect them with a cross-over ethernet cable. Run a client on one and a server on the other. The Ethernet library comes with example clients and servers.

For clarification: a crossover cable has the green and green/white wires swapped with the orange and orange/white wires at one end. This connects the TX of one end to the RX of the other end and vice versa - just like when you're working with serial.

Is there a library that can simply send strings back and froth without a client/server?


text:
can I create an on/off switch for my Arduino using the reset pin?
If i connect a switch to the reset pin, can I create an effective way of turning off the Arduino (overnight) without removing its power supply?

It wouldn't really be off, but the I/O pins would be high impedance, and the sketch would not be running. If you just want to stop it doing something (like feeding fish or something) you could just have the code test a pin, and if that pin was in a particular state, stop doing whatever it  usually does.

If your concern is power consumption, you'd have to see how much of the chip the reset shuts down (and what is consumed by the built-in pullup resistor on the reset itself).  There are also ways to shut down nearly everything, until it is woken up again by a pin interrupt.  Note that neither will shut down the USB-serial chip and its consumption.

The question is, why do you want to do this? If it is to save power, my experiments show that holding the chip in reset is not the most effective way.

Wouldn't connecting the switch to the power supply be just as  easy? Holding reset will not power down the AVR, nor will it shut down the other parts that are on the Arduino board (voltage regulator, led, usb-to-serial etc.)

Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".
All that would do is stop the currently-loaded sketch running, and save a few milliamps.


text:
3.95 TFT LCD SPI or parallel interface
I would like to get one information about this TFT LCD module . This particular module works with parallel interface with arduino mega and uno.
I am trying to get rid of arduino in my project and use esp8266 itself. I have this module http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html
This has only the parallel interface pins mentioned which requires around more than 10 pins to make it work. Is there any possibility that there is an SPI interface supported for this one by  making use of any of the existing pins for the parallel interface.
I don't think so but still can someone confirm that. If so I need to get SPI interface ready TFT LCDs.
Thanks,

In general, no. The interface used by the chip is normally hard wired either in the connections to the Chip On Glass or in the connections of the shield (most commonly the former) and as such cannot really be changed.
You will need to either use a TFT screen that has the interface already set to SPI (and there are many) or use some form of SPI I/O expander to provide enough I/O pins to drive a parallel display.
Note that using SPI to communicate with a screen makes the screen updates considerably slower than using a parallel interface. The bigger the screen the slower it gets.


text:
HardwareSerial - check for overflow
The SoftwareSerial library has a built-in Overflow function, but the Serial library does not.  Is there a simple way to check for a data buffer overflow on a hardware serial port?

The current code just ignores incoming data, if the buffer is full. So there is no way to see if the buffer has been "overflown". Though it wouldn't be hard to add this yourself.

@Gerben - yes I'm aware.  That is the question I'm asking: how would you add something to check?

Just add a single boolean variable to the class  (e.g. _rx_overflow). After the lines in the link, add else _rx_overflow=true;. Add the function overflow which returns the value of _rx_overflow and sets it back to false. Pretty much the same way the softwareserial library did it.

The HardwareSerial has actually two levels of RX data overflow. The first may occur if the ISR is locked out a longer period and the UART RX registers are not emptied in time. There is a special status flag for this (UCSR0A USART Control and Status Register A, Bit: DOR0 Data Overrun). The second level is the RX ring-buffer as described above.

A look at HardwareSerial_private.h shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll Serial.available() in loop() to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:
    void loop(){
        //your code
        if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases
            //buffer is overrun, do what u will
        }
    }

You could make some changes to HardwareSerial_private.h to get something like the overflow() method of SoftwareSerial. The relevant lines are:
    if (i != _rx_buffer_tail) {
        _rx_buffer[_rx_buffer_head] = c;
        _rx_buffer_head = i;
    }

The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An else block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when Serial.read() is called.


text:
avrdude: stk500_recv(): programmer is not responding after all tries
After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

Facts :

v1.6.20 of the boards
v1.8.5 of the IDE
Windows 8.1 64bits
Programmer: "AVR ISP"
Drivers are fine (the boards are well recognized)
Serial monitor works
I'm trying to upload the "Bare minimum" exemple sketch
Nothing in pin 0 and 1, nothing at all is plugged actually
Get Board info:
Uno : VID 2A03
Mega2560 : VID 2A03
From instructions here, every instruction is "echoed back"

What i tried :

https://forum.arduino.cc/index.php?topic=385160.0
avrdude: stk500_recv(): programmer is not responding
https://zestedesavoir.com/forums/sujet/5676/probleme-televersement-arduino
All other programmers
A few old versions of boards
Resetting the boards a few times, during upload, before, after...

Nothing works. If you have any idea.....
Thank you all !

What i tried : ... i do not see rebooted computer on the list

haha @jsotola but I did :)

It eventually worked by using upload / ctrl+U (what I didn't try... smh) instead of  upload using programmer / ctrl+shift+U.
So i know now where it comes from, though I don't know what's wrong with AVR ISP.

"upload using programmer" requires one more step to work. You need to change one of your Arduinos into an ISP (there is a sketch for that) then you put some wires between the ArduinoISP and clean (no bootloader) ATmega/ATtiny, and you can write program (or bootloader) directly to the chip. Your ArduinoIDE was trying to find the ArduinoISP, but it couldn't because there wasn't any. and told you "programmer is not responding" Read more here: https://www.arduino.cc/en/Tutorial/ArduinoISP

Thank you, this resolved the issue for me as well.


text:
Tv remote connection to an Arduino
I have a tv remote that I want to connect to an Arduino so that I can send a series of commands to the TV using the remote.  I would like to open the remote and solder transistors or a Transistor Array in place of the buttons.  I have never done this before, so what do I need to be aware of?  I think that I will need to power the remote using the Arduino's power supply, but I am a bit foggy on the details.

If you're just running lines to the buttons, you won't need to power the remote from the arduino.  You could just let it keep the internal batteries.  But it would be possible to wire it up for power as well.
As a learning project, you could just take it apart and see if you can access the button contacts.  See if the contacts are split.  If so, shorting one side to the other should count as a button press.  But the details have nothing to do with an arduino.  They would depend on your specific remote and how it's constructed.
If your purpose is really to control the TV (rather than learning about the remote and fiddling with it), it will be much easier (and probably cheaper) to blast the IR without involving the remote at all.  A single IR transmitter and a library would work in most cases.  As an example: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
P.S.  By coincidence, Adafruit just posted an updated guide to IR library use on Arduino.  https://learn.adafruit.com/using-an-infrared-library/overview

That library is probably the best option.  Still, if I were to use the 'short' rout, I still need to automate the pressing of buttons in a specific order / timing.  I opened the remote and it does use two sided contacts.  How can I short them in a controlled, automatic way using an Arduino?

If you get an IR photodiode, you can read the output from the remote, store it either as flash or in program data. I've seen it done, Practical Electronics years ago on a PIC, so I know it works. You could add a 'learn' mode to your program.. you know, 'Press "1" now' sort of thing.

@Hoytman, An electrically easy way is to use a solid-state relay.  Treat it like an LED from the arduino and when it's on it completes the circut.  Use it to bridge the button.  More complex would be to tie the two devices together to ground and feed power to the correct side of the button.  That's more difficult in terms of investigation (which side is low and which is high) and making sure the voltage is good.  But it would probably be cheaper (no SSRs to deal with).

+1 for IR blasting. There's no need to complicate it by involving the remote except to program the Arduino with the command sequences.

Using an IR library as mentioned in a previous answer is likely to be about the best approach.  However, if you decide to use electronic switches to jumper across the remote's switch contacts, consider using CMOS analog switch chips for the purpose.  If each button on the remote connects one contact to a common net, inexpensive chips like 74HC4051 and CD74HCT4067 would serve for 8 or 16 buttons each, respectively.
I don't have a reference for an affordable many-SPST-contacts CMOS switch.  Inexpensive chips with a few such contacts are available.  The 74HC4053, for example, contains three SPDT CMOS switches.  Handling a dozen buttons would use four 4053 chips.  A CD4007 probably could provide three SPST switches also.

Edit: The figure above shows pinouts of CD4051/52/53 devices.  To use a CD4053 as three separate switches, connect V- and GND to Arduino ground, V+ to +5V or +3.3V, and each of COMA,B,C to one circuit contact to be switched.  With NCA, NCB, NCC connected to the other contacts of circuits A, B, C, raise ADDA, B, or C and drop INH to close circuit A, B, or C.
If your remote has dozens of buttons, it's likely that they are arranged in rows and columns for multiplexed scanning.  In this case, follow the printed circuit tracks to identify which buttons attach to which rows and which columns.  Suppose there are eight or fewer of one or the other; eg, suppose there are 5 columns and 8 rows.  In this case, you would hook up 5 CD4051 chips: connect V- and GND to Arduino ground, V+ to +5V or +3.3V, and the COM of each 4051 to a different column line.  Connect NO0–7 to row lines 0 to 7.
To close circuit j in column k, put j in binary on ADDA,B,C of all 4051s and drop INH on 4051 #k.  (Either use one DIO line per INH, or use a DM74LS138 or MM74HC138 (etc.) and put k in binary on the A,B,C select lines of the '138.)

That sounds good, could you give me draw me a quick schematic of how to connect the chip?

Hoytman, see edit. Please remember to upvote useful answers.

Great answer, but I really should do as the other answer recommends.


text:
Can I damage an arduino by setting pins high with no load
I have an Arduino project that has 15 different output pins set.  Some are currently attached to devices and others are not.  Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?

Nope, you should be just fine.
Having a pin set to any state while unplugged will not cause any problems with your microcontroller.


text:
IR trouble with raw buffer
I am attempting to send a RAW IR code using the IRremote.h library.  The process for capturing IR pulses is easy to find on the web, but the process for sending them again is not.  After a few days, i pieced the following code together:
#include <IRremote.h>
 IRsend irsend;

void setup() {

}

void loop() {

  int IRsignal[] = {

// ON, OFF (in 10's of microseconds)

    90, 86,

    174, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 174,

    88, 86,

    174, 88,

    86, 2340,

    88, 86,

    174, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 174,

    88, 86,

    174, 88,

    86, 0};

      irsend.sendRaw(IRsignal, 10, 38);

      delay(1000);

}

When I run it, i get the following error:

ir_test.ino: In function 'void loop()': ir_test.ino:65:38: error:
  invalid conversion from 'int*' to 'unsigned int*' [-fpermissive] In
  file included from ir_test.ino:3:0:
  /Applications/Arduino.app/Contents/Resources/Java/libraries/RobotIRremote/src/IRremote.h:143:8:
  error:   initializing argument 1 of 'void IRsend::sendRaw(unsigned
  int*, int, int)' [-fpermissive]    void sendRaw(unsigned int buf[],
  int len, int hz);
          ^ Error compiling.

I am not sure what I did wrong, or how to convert the data types.  Any tips or ideas?

Most IR protocols start with a long signal at the beginning. Yours has a 2340 right in the middle.

Use unsigned int IRsignal[] instead.
Also, your array is 48 items long, not 10. So irsend.sendRaw(IRsignal, 48, 38);

Now the code compiles and appears to work... no response from the remote device though.... guess the number are a little off

If you have a second arduino, you could try to capture the signal being send by the first arduino.


text:
Can I connect an RFID reader to the ICSP header?
I am connecting an RFID reader to my Arduino mega.  The directions that I have found say that I need to use pins 50-53.  I also noticed that the ICSP header contains (what looks like) a secondary connection to these pins:
http://arduino.cc/en/Reference/SPI
Can I connect my RFID reader to the ICSP header:

Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)


text:
How do I send a string to master using i2c
I want to write an Arduino program that simply recieves a string (via the I2C wire library) from a master Arduino, then waits for a request, and sends that string back.
Here is my code:
#include <Wire.h>

void setup()
{
  Wire.begin(4);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

String data = "";

void loop()
{

}

void receiveEvent(int howMany)
{
  data = "";
  while( Wire.available()){
    data += (char)Wire.read();
  }
}

void requestEvent()
{
    Wire.write(data);
}

I read in the API that the write() function accepts a string, but I keep getting a "No matching function for call" error.  I tried to simply replace
Wire.write(data);

with
Wire.write("test");

and that worked without error.  Why is this the case?

Try this instead of wire.write(data); wire.print(data);

data is a String. "test" is a char*. Wire.write() has no prototype that takes a String.
Wire.write(data.c_str());

working perfectly :)