Voltage increasing when charging a battery using arduino

In order to charge a battery you have to apply a voltage to the battery terminals that is higher than the batteries own internal voltage. That's pretty much the definition of charging a battery.

Basically you're trying to do the impossible, you can't measure the batteries off charge voltage while charging it because as soon as you start charging the voltage at that point changes.

When charging your supply is 3.5V and your supply measurement is 13.15. That means you're loosing 0.35V in battery cables and F1.
The battery voltage is 12.7V so that's 0.45V loss in D1 and Q1.

That first loss seems too high and the second one too low, D1 should drop typically drop 0.58V, so you may have some resistor tolerance or noisy reading issues. The total voltage drop seems reasonable but the split looks wrong.

The best solution to what your are trying to do is to measure the charge current.

Move D1 to the other side of R1 so there is no diode drop between your two voltage measurements and add a small resistor in series where D1 used to be. The difference between the two measured voltages and the resistance between those points now tells you the charge current. Stop charging when the current drops below a certain threshold. Larger resistors make it easier to measure accurately but have an obvious efficiency hit, make sure you check the resistors power rating.

You may be able to avoid adding the resistor and simply use the on resistance of Q1 as your resistor. This will be a little variable between devices so it's not suitable for mass production but for a one off it should be good enough as long as it's not too small for you to measure the current accurately.

One further note: With a supply of 13.5V you will never get the battery to 13V. You have a diode in there with a 0.6V drop so the highest you could get is 12.9V. On the plus side this means you can keep charging until the current drops to 0 with no risk of overcharging.
Or alternatively switch D1 for a schottky diode with a drop of around 0.2V


Timeout error uploading code to Arduino Mega 2560

Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.


Please explain this OneWire communication with Arduino Uno and DS2502-E48

I found a nice writeup on this on a blog.  To quote his experimental findings:

  Comparing to the OneWire spec, we can tell it’s writing 0xCC, which
  should be SKIP_ROM. Following that is 0xF0 (ReadMem), and two bytes
  starting address: 0x08, 0x00.

Based on this, the zero and 10 that you are writing are apparently an address value.


I2C is not used to get the pixel data. That is used only to configure the ov7670. You can read the pixel data by reading the IO PORTS and then send the data via SPI.


Which board/shield to generate (non-PWM) analog outputs?

For 12-bit dual DAC you want the MCP4822 which has two channels of 0-4.095V in 1mV steps.

The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V.  The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V.  If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.

It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.


Control DC motor in both directions with two relays

In short, you're probably overloading your regulator.
It's difficult to say for sure, but I have a suspicion and can give a framework for thinking about it with some very crude numbers.
If you're powering the Nano from a 12 V source, you are dropping 7 V across the regulator.  If you do the math on this 7 V drop, it means every 14 mA drawn through the regulator induces nearly a tenth Watt of heat in the regulator.  7 V * 0.014 A = 0.098 W.  I'm guessing you have a budget of perhaps 300mW based on the way the Nano's regulator is set up.
The ATmega328P says it uses 5.2 mA (typical) or 9 mA (maximum) at 5 V and active at 8 MHz.  But really it will use more at the 16 MHz frequency.  For sake of argument, I'm just going to say it's using 14 mA, because it makes the math easy and because power usage scales somewhat linearly with frequency.
Just the power led will use about 3 mA, if it's an official Nano, but for simplicity sake, I'll call it 7 mA, being half of 14 mA and we'll ignore the fact that there are other loads on the board like the serial transceiver.
Your relay coils will use at least 30 mA, but likely more, perhaps a lot more.  But for ease of calculation lets go optimistic and say they only use 28 mA (cause 2 * 14 mA).
So we have the ATMega328P inducing 100 mW in the regulator, the power led and some extras adding 50 mW. at at least one relay coil energized for another 200 mW.  So right there you're already at 350 mW.  If you screwed up and managed to energize both relays, 550 mW.  Hopefully the regulator will enter thermal shutdown when this happens, in which case all you need to do is let it cool down and, you know, stop doing that.  But it may also just die,which is more likely if you have a clone that happens to use a crappier regulator.
But, I think these numbers are conservative.  For example, a datasheet for a Songle SRD-05VDC-SL-C relay that a lot of these modules use seems to say it will use closer 70 mA each, rather than 28 mA.  This means operating just one of these coils by itself, nevermind the rest of the Arduino, will cause nearly half a Watt to be dissipated in the regulator if you're powering from 12 V.  If you managed to turn on both coils well... nothing good.
If this is not the problem you're having, it is a problem.  You can save yourself a fair bit of trouble by powering your Nano from USB with a powered hub or reasonable quality USB-output wall adapter.  Doing so bypasses your regulator altogether.
If you're going to continue staging down 12 V to 5 V for the relay coils, then you may need an external regulator to operate the relay modules, just to unload the the Nano's regulator.  Exactly how you'd go about that depends somewhat on the construction of the relay module.  Some of them make it a bit easier on you and are design to accept voltage from a second source for the coils.


At the bottom of the page for the client code link you provided, there's a link to a Chat Server example. If you study the code I think you'll see how to send and receive the potentiometer reading. Hint: Look in the code where it echoes what it receives.

mkr1000 WiFi Chat Server


Is Arduino Ethernet shield compatible with arduino due?

The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can tolerate connection to a 5v Arduino.

Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.

However, you should review the the full schematics and make your own determination that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.

It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.


Control multiple WS2812B strips with different leds count

The WS2812 chip requires highly timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.

I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.

What you could do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the data and ground would need to go from the Arduino into the first strip, then out to the second one, and so on.

Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

Possible alternative

Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.

I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.

You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.


Hooking up 12v Push button to arduino uno/nano

Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.

Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.

Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.

The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).

The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.

Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.

Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.


There is a Time library which you can import.

Here are things that I found on the Arduino website.

hour();            // The hour now  (0-23)
minute();          // The minute now (0-59)
second();          // The second now (0-59)
day();             // The day now (1-31)
weekday();         // Day of the week, Sunday is day 1
month();           // The month now (1-12)
year();            // The full four digit year: (2009,
                //  2010 etc)
setTime(t);              // Set the system time to the
                      //  give time t
setTime(hr,min,sec,day,month,yr); // Another way to set
                               //  the time
adjustTime(adjustment); // Adjust system time by adding
                     //  the adjustment value

timeStatus();   // Indicates if time has been set and
             //  recently synchronized
             //  returns one of the following
             //  enumerations:
* timeNotSet    // The time has never been set,
             //  the clock started at Jan 1 1970
* timeNeedsSync // The time had been set but a sync
             //  attempt did not succeed
* timeSet       // The time is set and is synced
             //  Time and Date values are not valid if
             //  the status is timeNotSet. Otherwise
             //  values can be used but the returned
             //  time may have drifted if the status is
             //  timeNeedsSync.

setSyncProvider(getTimeFunction);// Set the external time
                              //  provider
setSyncInterval(interval);    // Set the number of
                           //  seconds between re-sync

And obviously,

#include<Time.h>

Tell me in the comments if you need more help.


How can I use a BlueSMIRF Silver (RN-42) as a HID Keyboard (on IOS)?

I should be able to set and use the HID profile (from the default SPP)

Unfortunately, your assumption is incorrect. From the same documentation you quoted, the previous sentence says:

  To use Roving Networks’ Bluetooth HID profile, you must use a special
  build of firmware, version 6.03 or later.

Poorly phrased, this does mean that you need to have two things:

A special HID firmware
Version 6.03 or later

Your BlueSmirf Silver only complies with the second condition; it does not have the special HID firmware (also note that the Rovnix command reference does not address a specific variant of the BlueSmirf, but speaks generally about all of the variants).

The SPP protocol (Serial Port Profile) is used for emulating a serial cable, and functions as a substitute for the physical RS-232 connection, but cannot stack pure HID profile on top of it. In order for you do talk HID, you will need the HID firmware.

As a side note, the HID version comes with SPP and you can switch between the two modes interchangeably, I have been using the HID version for a while now and it works fine (including the pairing with iOS).

Another misfortune is that it does not appear that Roving Networks officially support any re-flashing of the BlueSmirf firmware, so unless you are willing to reverse the hardware, this is off the table as well.


The answer, as kindly pointed out by Gerben, is that ISP program upload overwrites the bootloader.

Only upload the bootloader via ISP, then switch to USB for uploading Arduino sketches.


Where do class files go in Sloeber Eclipse project?

With Sloeber Eclipse plugin the ino files go to root of the project and the cpp, c and h files can be in root or in subfolders. example:

Folders created by Sloeber: core subfolder is a virtual folder with links to Arduino core files and variant files of the selected board. libraries folder is a virtual folder with links to libraries selected for the project. Release folder contains the generated make file, the .o files and the resulting elf, hex, bin files. (And sloeber.ino.cpp is a file generated by Sloeber)

Project folders: data folder in example picture is a convention for a folder with esp8266 SPIFFS files. utility is a subfolder with additional source files of the project.


Can we use yx5300 to play audio from a file in Arduino?

No. That chip can only play files on an SD card that is directly attached to it.


In any other C/C++ platform, you can use "%f" as a format specifier when you want to print (or convert to string) a float using printf or its siblings. Any, except in Arduino.

To convert a float you need use dtostrf(),

char * dtostrf(
    double __val,
    signed char __width,
    unsigned char __prec,
    char * __s)

  The dtostrf() function converts the double value passed in val into an
  ASCII representationthat will be stored under s. The caller is
  responsible for providing sufficient storage in s.

  Conversion is done in the format "[-]d.ddd". The minimum field width
  of the output string (including the possible '.' and the possible sign
  for negative values) is given in width, and prec determines the number
  of digits after the decimal sign. width is signed value, negative for
  left adjustment.

  The dtostrf() function returns the pointer to the converted string s.

To convert a byte (or anything not float) to ascii, use snprintf()

int snprintf ( char * s,
               size_t n,
               const char * format,
               ... );

  Write formatted output to sized buffer.

  Composes a string with the same
  text that would be printed if format was used on printf, but instead
  of being printed, the content is stored as a C string in the buffer
  pointed by s (taking n as the maximum buffer capacity to fill).

You can read the details by yourself, but here is a demo.

The idea is to produce in buffer a traditional C-style string (null terminated). That string you can print or transmit.

The float value is printed in two step. First, we use dtostrf to convert the float value to his ascii representation. Then we use snprintf to include that value (as a string) inside a whole line, latter to be printed.

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println("Start");

  float value = 123.45;
  byte balue = 128;

  char buffer[80];
  char fValue[16];
  dtostrf(value, 3, 2, fValue);
  snprintf(buffer, sizeof(buffer), "float %s", fValue);
  Serial.println(buffer);
  snprintf(buffer, sizeof(buffer), "byte value is %d", (int) balue);
  Serial.println(buffer);
}

void loop() {

}


Why is their need of response time needed in esp8266 AT commands?

Your esp8266 firmware isn't required to wait before responding to the atmega2560, but the reality is that it simply can't respond in zero-time. The esp will take some processing to interpret the command that was sent to it and to create the reply to the atmega. And that is even if it doesn't have to wait for some distant server.
If the esp has to send a WiFi request to a server (which has the same constraints of processing time, plus other requests ahead of yours), that only adds to the esp's delay in responding to the atmega.
The bottom line is that the esp isn't required to wait any amount of time to respond; its just however much time it takes to acquire any data it needs, plus processing time to format it and send it back to the atmega.


Uno doesn’t get enough power from 5v barrel connector. Why?

Voltage Drop
Well, if you put 5V into your barrel jack, your UNO's onboard 5V regulator is going to drop that down to 3.5V or so.  You must have more than 5V into the regulator to get 5V out of it.  This is referred to as the regulator's "drop out" voltage.
The specs for an UNO say to power it from at least 7V for that reason.
As an experiment you can power it this way without your lights attached and measure the "5V" header to GND to see this happening.
Power Dissipation
Linear regulators like that found on the UNO are not efficient. They waste energy as heat in proportion to the current through it and voltage dropped by it.
If you provide it with 7V at the regulator and your project draws 0.5 amps from the regulator, you will try to generate 0.5A * (7V - 5V), that is 1 Watt of heat.  Your regulator can probably dissipate half that with how it's mounted on the UNO and normal ambient air temperature.
Note this situation gets worse if you put 12V (for example) into the barrel jack, as you'd be dropping 7V across the regulator.
Many linear regulators have thermal overload protection built into them.  They'll stop producing as much voltage at the output as they heat up to try to survive the event.  And that's likely what you're seeing if you're trying to power your christmas lights from the regulator.
If you want to see this yourself might try very briefly tapping the regulator with your finger; it may be blazing hot.  You might just dampen your finger and hold it near the regulator's surface to feel the heat coming off of it.
You will more than likely need to route power around the Arduino board to your lights to prevent this.


Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.


avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

You should re-burn the bootloader. If you have another uno, you can burn bootloader here


AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?

Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for every microcontroller, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere.

If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.
Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself, it this is really a good idea.
I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.
Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.

About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis.
No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.

If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.


avrdude: Error: butterfly programmer uses avr_write_page() but does not provide a cmd() method

After much frustration in trying things, I came across this forum post which advised:

sudo systemctl stop ModemManager.service

If this works, disable the service from starting next boot:

sudo systemctl disable ModemManager.service

It seems like setting ENV{ID_MM_DEVICE_IGNORE}="1" in a udev rule is insufficient.


My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.

The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.

You could try a different Servo library.

This article is useful to understand the timer/pwm/pin relationships


ML8511 Sensor, unable to achieve meaningful results. Output voltages are atypical

I found another, third sensor identical to mine and functioning properly.  By measuring pin output, then cross swapping with one of my two "supposedly abberant" sensors, I have identified my two as being defective, i.e., the other sketch then failed to function properly with one of those so identified sensors, whilst mine now worked as it should.

I typically buy at least two of everything in an effort to isolate such problems, but if from the same batch, two may not be sufficient in some situations.


SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino

You may be getting switching noise between the button wires, which is low-level and brief, but with no debouncing, it could be just enough to cause the effect you're seeing.

I'd suggest 1) writing a short function that debounces and reads any button; and 2) using if/else statements instead of testing each button twice.

A quick test is to hold one pair of wires closer together or farther apart from each other while you press one of those two buttons, and see whether the distance apart changes the effect. If it does, you've found the cause.


The problem is the BIN in your print statement.  Everything is ALWAYS binary.  The BIN means to break that binary up into ascii digits 0 and 1.  So if you send
Serial.print(21, BIN);
then the print function takes 21 as a binary number, 00010101 and then sends those binary digits as ascii.  So what goes out on the wire is 8 separate bytes, it goes 48, 48, 48, 49, 48, 49, 48, 49 as 48 and 49 are the ascii codes for 0 and 1.
What you want to do is just to send the raw byte.  So use Serial.write instead.  The print functions convert things to ascii representations but the write function just sends the raw bytes out.  So if you write:
Serial.write(inches);

Assuming that inches is a byte type variable then it just sends the raw byte out.


How to generate true random numbers over Arduino Uno without any external hardware?

The standard (but not very good) solution is to seed the random number generator from an analogRead() on an unconnected pin. For better options, see this answer to a related question.


Adafruit motor shield + Adafruit stepper not working

As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: Motorshield V2 assembly


toCharArray is a method. It will copy the value from SensorValur to charBuff, it won't return the char array.

Line:

 char msg[7] = sensorValue.toCharArray(charBuf, 7);

Should be:

 sensorValue.toCharArray(charBuf, 7);

charBuf will already have the sensorValue copied.

Check more about "toCharArray" method :

https://www.arduino.cc/en/Reference/StringToCharArray


Continuous Servo not setting speed correctly

Issue was fixed by adding a delay of 100ms between servo writes, smaller values may work, but I haven't tried yet


I need to generate a programmable pulse inside an ISR

you can use delayMicroseconds() inside the ISR if you really need to. It is not usually the best practice to delay inside an ISR, and there may be a cleaner way to accomplish what you need but without some background of what the signal is and what its used for this is your best bet.


How can I power the 12-24V keypad through the arduino without frying it?

If you power the Arduino with slightly more than 12V (through the barrel jack) then you can get 12V (or slightly less than you power the Arduino with) from the VIN pin.

However the Arduino's on-board voltage regulator does tend to get a little hot when such a high voltage is used to power it. Better is just to power the keypad separately from the correct power source.

And don't forget to connect the grounds together.


I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.

Assuming you are using a Uno this code will do it:

// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

void setup()
 {
  pinMode (outputPin, OUTPUT);

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()
  {
  }

You can change the 1000 in the calculation for timer1_OCR1A_Setting, within reason, to get other frequencies.

See my page about timers for more background information.


In the AnalogRead example, would the thing work if I remove or short the A0 and the ground pin?

I think you are confused because the ADC input measures voltage, not resistance.

To convert from resistance to voltage you need to pull in the opposite direction on the variable resistance with a fixed resistor.  As in the following image from this tutorial.


pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You must enable the pullup on the pins (and connect the common to ground) if you want correct operation.

 pinMode(one, INPUT_PULLUP);


Why does this not put my Arduino Mega to sleep?

In idle sleep, the timer interrupts will wake the processor, as  Ignacio Vazquez-Abrams said in his comment.

A "higher" sleep mode works, however I had to add Serial.flush () otherwise it only printed "P" because the processor goes to sleep before the serial output buffer has been emptied.

#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  Serial.flush ();
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

See my page about power savings.


The USB specifications allow a maximum of 10uF total capacitance on the USB power lines. By putting 1000uF you have given it 100x more than is allowed.

This causes a massive inrush current and the USB host (your computer) sees it as a short circuit, so it shuts off the power in a panic to protect itself.

A capacitor does have a role to play in helping to remove power supply noise caused by power-hungry and noisy devices like WS2812B LEDs, but just slapping it across the power supply pins isn't going to really help.

Instead you should increase the impedance of the power supply to the noisy device(s) and use a capacitor to reduce the impedance again. This will help to preferentially draw current from the capacitor to supply the LEDs while smoothing out the draw from the main supply over time.

A simple circuit is to use a resistor with a capacitor:

simulate this circuit – Schematic created using CircuitLab

The values I show there for the resistor and capacitor are pretty random. The smaller the resistor the more demand will be put on the power supply. The bigger the resistor the more demand will be put on the capacitor. If the resistor is too big the capacitor won't be able to store enough power to run the LEDs, and too much voltage will be dropped across  it. If the capacitor is too small it won't be able to store enough power to run the LEDs. Tuning those values depends very much on the amount of noise there is and the current draw of the LEDs.

You must also make sure the resistor can handle the amount of power dissipated by the current flowing through it.


How does one design for the power on transient conditions?

Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.

The recommended use of the watchdog timer does not suffer from these limitations. It is designed to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).

Reference

Atmel knowledge base - Software Reset

  If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.

  You should not try to:

  Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.
  Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.

Their suggested code to reset the processor:

#include <avr/io.h>
#include <avr/wdt.h>

#define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}

int main(void)
{
Reset_AVR();
}


Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly?

The fact that it is possible to set them incorrectly is why, in some projects where I'm concerned about this, I'll add a small series resistance to an inbound signal.  Should the pin become OUTPUT and driven in an opposing direction to the signal, the resistance serves to prevent a short through both devices.  The possibility is always there, whether you have an outright bug, or instability, or flash corruption.
With pinMode the opportunity to accidentally set your port to the wrong direction is maybe a bit worse than for code that directly manipulates the data direction register.  pinMode calls typically don't get inlined, because pinMode on the Arduino is a fairly complicated function at runtime for what it actually does.  So, there's this generic code that can be jumped to that will set various ports to either direction, as opposed to smaller chunks of code that contain instructions that set specific ports to specific settings.
INPUT roughly takes your digital pin out of the circuit.  And INPUT_PULLUP sort of does that, with the exception that internal to the AVR there's going to be 20k - 50k of resistance going to "5V".  Knowing that, you can test your hypothesis three.  When you find your project in the state where the LED isn't lit, take some some resistance (say 1K) and use it to pull the pin toward "5V".  Then pull it to GND.  Watch the voltage at the pin with a meter.  Based on what you have attached and what you see for a voltage, you can determine whether it has entered the INPUT or INPUT_PULLUP state.  You'll also be able to see if it's just being driven to whatever state you're calling "not working" ("off" I'm guessing).
You can take all the guess work out of what voltages to see in each scenario if you upload a sketch that sets the pin in question to the INPUT, INPUT_PULLUP, OUTPUT/HIGH, and OUTPUT/LOW states and measure the voltage at the pin when you pull it to each rail with your resistor.  Later you can consult the table you've built to see what has happened.
There's only so much to say about this, particularly your first two ideas, without seeing the code and other details.  Just that sometimes otherwise simple code has bugs in it.  In an ATMega328P project, 40 bytes is not a lot of free space at all.  To give you an idea what sort of problem this can trigger: The Arduino implementation of new that's in the 1.8.3 core will happily blow away your register file and whatever else it can get to after that, if the underlying malloc reports not enough memory.  Basically new continues to initialize the object it thinks was allocated even when the pointed returned is nullptr.  The __malloc_margin is 128 in the 1.8.3.  So if you try to malloc with 40 bytes distance between the stack and heap, you will trash your program state, perhaps even setting a data direction register in the process.


How many total digital pin outs does the Arduino Yun have

According to the official specification, it has 20 digital IO pins which can be used with digitalRead() and digitalWrite() etc.. As is typical on Arduino boards though, pins 0 and 1 also act as serial Rx and Tx (respectively).

You can program it to use them for either purpose.

The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.

If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.


How do I run multiple vibration motors from an Arduino Mini with PWM?

You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check here about more information on AnalogWrite, and here about Arduino Mini
This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

simulate this circuit – Schematic created using CircuitLab


Arduino ATmega 2560 frequency measurement

TCNT1 = timer1_counter;   // preload timer

When you load the offset (timer1_counter), there are some values in the timer1 prescaler (and potentially TCNT1 if the prescaler isn't sufficient large, or the input pulse train is fast). By assigning a value to TCNT1, you would have written over the values in the prescaler / TCNT1 -> read the datasheet on that.

The solution?

Optimal: use a timer with auto-reload function. a timer with output compare can be adopted here as well.
Increment the counter: TCNT1 += timer1_counter; // preload timer, if timer has a 1:1 prescaler.

Or to use the timer to count the pulse and another to provide the time base.


Your method is completely wrong.

You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis().  When the difference between them is greater than or equal to 60000 * 15 then 15 minutes have passed.

Look at BlinkWithoutDelay in the Examples menu in the IDE - it showcases the technique for you.


Program Arduino via UART from ESP8266 SPIFFS

To answer my own question in case someone else ends up here, the library Juraj suggested (https://github.com/ciminaghi/libdfu) looks like it does the job. I also found another project doing something similar (https://github.com/rene-win/esp_avr_programmer). Also the STK500 docs linked to by Majenko (http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf) are really useful for understanding the nuts and bolts!


Arduino IDE c++ 11 raw string literal have issues with // in http://, complier thinks // is comment

Escape the two quote marks inside the string using a backslash (literal quotes).

Without the escape characters, the URL is "outside" of a string because the quote marks are string delimiters.

char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";


I2C: What is the difference between A4&A5 and SCL&SDA pins?

They are the same pins. They are physically connected to each other on the UNO board. (So SDA is connected to A4. SCL is connected to A5)


Problem with transmitting 2 byte data in correct way

First, you want to determine what you are trying to send. Send data in binary form is rare.

Secondly, you want to wait for each transmission to send before starting the next one.


Fail uploading any sketch to ATtiny85 USB

from Daves Comment
need to download upgrade-t85.hex (which is not t85_default.hex) from link


Wake Arduino (Atmega328) from sleep with ADXL345 interrupt

When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant.  Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino.  Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.

On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino.  By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.

As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,

  The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT_INVERT bit in the
  DATA_FORMAT (Address 0x31) register.

  How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345.  You will need to configure the unit before it does anything, because it powers up into standby mode.  See the second paragraph of POWER SEQUENCING, page 13 in spec sheet, and see Table 6 on that same page:

  At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.


How to Communicate between arduinos wirelessly?

You can use XBees. They are powerful and do provide wifi connections (the recent versions).

And you rely on well-designed devices which guarantee packet retransmission and they achieve up to 1km in an open field.

XBee still works with serial communications making them an excellent tool for your embedded project.

Just plug your Arduinos and write code to send/receive data. This library is a good start point for API mode.

If you don't mind using all the benefits from ZigBee protocol, just use AT mode where all you push in one side is sent to another via serial communication.


Serial.print(lat,lon);

That doesn't do what you think it does.  That is trying to print the latitude encoded in base "lon", which just isn't going to work.

Instead you need to send it as separate operations:

Serial.print(lat);
Serial.print(",");
Serial.print(lon);

Also you should separate out the GPS and GSM routines.  Create a function that gets the latitude and longitude, and another function that sends the two values as a text message.  Then you can keep things as discrete obvious steps and not get confused with what is happening when.


What will happen when I use an invalid pin number?

The compiler will not detect any error and the code will compile and execute. Hence, to see what happens we need to explore the behind-the-scenes magic. For a summary, skip to end.

The second line in your code is where the magic will happen and thats where we need to focus.

pinMode(pin, OUTPUT);

The portion of pinMode relevant to this discussion is:

void pinMode(uint8_t pin, uint8_t mode)
{

    uint8_t bit = digitalPinToBitMask(pin); //The first instance where pin is used
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return;

//Do something
}

(The complete implementation can be found in wiring_digital.c)

So, here, digitalPinToBitMask seems to be using pin to compute an intermediate bit. Exploring further, digitalPinToBitMask is a macro defined in Arduino.h whose definition is this one-liner:

#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This weird looking one liner does a very simple task. It indexes the Pth element in the array digital_pin_to_bit_mask_PGM and returns it. This array digital_pin_to_bit_mask_PGM is defined in pins_arduino.h or the pin map for the specific board being used.

const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
    _BV(0), /* 0, port D */
    _BV(1),
    _BV(2),
    _BV(3),
    _BV(4),
    _BV(5),
    _BV(6),
    _BV(7),
...
};

This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. Or will it?

We still have another line of defense against runtime anarchy. Its the next line of the function pinMode:

uint8_t port = digitalPinToPort(pin);

digitalPinToPort takes us along a similar path. It is defined as a macro along with digitalPinToBitMask. Its definition is:

#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )

Now, we index the Pth element of digital_pin_to_port_PGM which is an array defined in the pin map:

const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    ....
    PC,
    PC,
};

This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.

There is still one last line of defense. That is the if check in pinMode on the return value of digitalPinToPort:

if (port == NOT_A_PIN) return;

NOT_A_PIN is defined as 0 in Arduino.h. So, if the returned byte from digitalPinToPort happens to be zero, then pinMode will silently fail and return.

In any case, pinMode cannot save us from anarchy. 999 is destined to result in doom.

TL;DR, the code will execute and the result of this will be unpredictable. Most likely, no pin will be set to OUTPUT, and digitalWrite will fail. If you happen to have exceptionally bad luck, then a random pin may get set to OUTPUT, and digitalWrite may set it to HIGH.


Can't get Ubuntu to see FTDI cable for breadboarding Arduino project

Check if the driver is loaded, in Terminal type:

lsmod | grep  ftdi_sio

If you get no answer then it's not loaded, load it using:

sudo modprobe ftdi_sio

I hope this helps.


Send JSON via POST on SIM900 shield with AT commands

The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):

        //--if autobauding was enabled, send a blank AT
        command:='AT';
        send_gprs;

        //--switch to minimal mode - this is required to reset the SIM card
        command:='AT+CFUN=0';
        send_gprs;

        //--set dce speed
        command:='AT+IPR=57600';
        send_gprs;

        //--turn off command echo
        command:='ATE0';
        send_gprs;

        //--turn off command echo again - sometimes the first command is ignored
        command:='ATE0';
        send_gprs;

        //--turn on extended error messages
        command:='AT+CMEE=1';
        send_gprs;

        //--set module to full function
        command:='AT+CFUN=1';
        send_gprs;

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:

        //--check pin
        command:='AT+CPIN?';
        send_gprs;
        //--right answer is +CPIN: READY
        //--wrong answer is +CME ERROR: 772

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:

    repeat
        //--reset connection
        command:='AT+CIPSHUT';
        send_gprs;

        //--set GPRS APN
        command:='AT+CSTT="internet.vodafone.net"';
        send_gprs;
    until is_ok=1;

And finally, open a GPRS connection:

    repeat
        //--Open gprs connection
        command:='AT+CIICR';
        send_gprs;

        //--Get local address - for some reason this is required
        command:='AT+CIFSR';
        send_gprs;

        //--Suppress "SEND OK" after at+cipsend
        command:='AT+CIPSPRT=2';
        send_gprs;

    until is_ok=1;

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)

Two very important things:

any command can fail - it is a good idea to send back the response to an AT command to your console window
AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.


Arduino: using digital pins to emulate USB device

There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.

I think it may be this library though nothing has happened with that for a number of years.

Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.


Can external interrupts be OR'd together on the '328 (Uno)?

Regarding the notion that “"internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts”, it certainly is true that PCI (pin-change interrupts) libraries PinChangeInt.h (deprecated) and EnableInterrupt.h have high software overhead.  By keeping track of former values, for each pin those libraries support separate callback routines for Rising, Falling, Change, High, and Low.  PCIs are grouped in sets of eight pins per interrupt vector, leading to 40 different cases of callback routines when a PCI fires.  That is, when a PCI occurs, the libraries quickly find out which set of pins changed – because that's what the hardware supports – but then they go through all eight pins on the vector one by one checking if it changed, and how it changed, then calling the callback associated with the particular pin and its particular state.

For reading pins of a rotary encoder, say a KY-040, the overhead described above can cause loss of 10%–20% of rotary counts.  If you are concerned about not losing counts, write your own ISR()-level interrupt service routine.  The example below illustrates a routine using ISR(); this example is from my answer to previous question #18221, with some comments added here and there.  See that answer for discussion of the timing data that is this program's output.  (For rotary encoder quadrature-counting, see discussion below).

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  // Note, if using an encoder without pullups on it,
  // change INPUT in next 2 lines to INPUT_PULLUP
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

Note, for the above you may need to download and install Streaming.h via Streaming5.zip from arduiniana.org.

Rotary encoder quadrature-counting

The program above tracks and reports pulse-length times, instead of decoding the quadrature signals the rotary encoder provides.  The program below reports rotary encoder counts, but does so using INT0 and INT1 instead of PCIs.  You will want to combine relevant portions of the two routines together – ie, use the interrupt setup and handling framework from above, with the body of the service routine from below.  [Note, this program is from my answer to previous question #16420.  The encoder decoding code within it is faster and shorter than other decoding code I've looked at, and is fast enough to support two encoders rotating simultaneously while losing few counts.]

/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Using other pins for PCIs

If you wish to monitor two rotary encoder lines using pin change interrupts on pins other than A0 and A1, you may need to replace vector PCINT1_vect with some other vector, and will need to replace the pins mask with a different one.  The following program can be used to display a table of PCI vectors, masks, etc.  (As noted in my question Why PJ0 and PJ1 are not reporting as PCINT pins, pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)

/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

ISR-framework-generating Sketch

The program below generates frameworks for specified PCI pins and prints them to Serial.  See usage comments within the program.  This provides an easy way to create the basic outline of an ISR to handle PCIs.

/*  pinFunctions -- JW, 1 October 2015 --
 *
 *  Displays direct pin-access and pin-change-interrupt setup code,
 *  for inclusion in a sketch, for specified pin numbers.  The
 *  displayed code can be pasted into a sketch where execution speed
 *  matters.
 *
 *  When called with a call like `genCode ("affix", "9,11");`, genCode
 *  will produce a set of procedures: ISR routines for pins that
 *  support pin-change interrupts; get and put routines to read from
 *  or store to registers; and a setup routine.  The generated get,
 *  put, and setup routines will have names formed by suffixing the
 *  affix to get, put, and setup, respectively.  For example, if the
 *  affix is ML47 the names of generated routines will include
 *  getML47, putML47, and setupML47.
 *
 *  Generated get() and put() code is of the following forms (in which
 *  u, v are port-letters; values mu, mv, ni are numerical constants;
 *  and w is a parameter value) if all the pins, n1, ... nk in the
 *  pins-list are in port u, under mask mu:
 *
 *             return PINu & 0xmu; // Get pins n1, ... nk
 *             PORTu = PINu & ~mu | w & mu;
 *
 * For example, with Uno pins 3, 4, 6, get() and put() bodies are:
 *
 *             return PIND & 0x58;
 *             PORTD = PIND & 0xa7 | w & 0x58;
 *
 *  The following forms arise if the pins are in ports u and v; and so
 *  forth if more than two ports are involved.
 *
 *             return PINu & masku | PINv & mv; // Get pins n1, ... nk
 *             PORTu = w & 0xmu;   // Put pins <u pins>
 *             PORTv = w & 0xmv;   // Put pins <v pins>
 *
 *  genCode() does not require that all pins belong to the same port.
 *  It will produce usually-desired results if bit positions don't
 *  interfere, otherwise may not.  For example: An Arduino Uno
 *  pins-list "2,10" corresponds to port pins PD2 and PB2.  Both are
 *  in bit position 2, so get's result will be the OR of the PB2 and
 *  PD2 values, while put will store the same bit value to both pins.
 *
 *  To use the pasted code: A statement like `w = getAFFIX();` will
 *  read a set of pins and store the value in w.  A statement like
 *  `putAFFIX(w);` will write w to a set of pins.  Also, add a line
 *  like the following in setup():
 *
 *       setupAFFIX(ioMode, enablePCI);
 *
 *  In the `setupAFFIX(ioMode, enablePCI);` call, substitute an
 *  appropriate affix in place of AFFIX; substitute one of INPUT,
 *  OUTPUT, or INPUT_PULLUP in place of ioMode; and substitute 1 or 0
 *  for enablePCI, to enable or not enable pin-change-interrupt setup.
 *
 *  If you want to save room and don't plan to use pin-change
 *  interrupts, instead of merely not enabling PCI setup, you can
 *  remove the ISR routines and the `if (enablePCI) {...}` section
 *  from the pasted code.
 *
 *  Each generated ISR routines contains one line, of form
 *
 *        byte datum = PINu & mu; // Read pins <list>
 *
 *  The idea is that you will paste the generated ISR into your
 *  sketch, then populate it with appropriate interrupt processing
 *  code.  Note 1: datum contains data from one port, a port which
 *  belongs to the interrupt vector.  If you need data from other
 *  ports as well, then paste appropriate lines from the get() routine
 *  into the ISR.  Note 2: This version of pinFunctions does not
 *  announce pins that don't belong to PCI vectors, if any.
 *  (Processor pins with functions like PCINT0 ... PCINT23 belong to
 *  PCI vectors.)  You can compare the masks used in get() to those
 *  used in the ISR's to detect this.  If the masks differ, some pins
 *  aren't PCI pins.  Note 3: If multiple ports' pins belong to one
 *  vector (eg Ard#0 or PE0 for PCINT8 and Ard#15 or PJ0 for PCINT9,
 *  both on vector PCINT1_vect), a code-generation error of form "Pin
 *  x's port #y isn't #z" will appear and you will need to paste in
 *  appropriate lines from get() or otherwise manually prepare correct
 *  code.
 */

char buffi[128];        // We create text-to-write in buffi
char buffn[32];         // also in buffn
byte nbuff=0;           // #chars used in buffn
char *c;            // c points into pinsList
byte pin;           // pin number
byte nPCICR;            // 0, 1, or 2 for mask-register #
byte vecmask;           // OR of 1<<nPCICR values
byte intmask[3];        // OR of int. enable masks
byte maskBitPC;         // 0 to 7 for bit in PCI mask
byte maskBitIO;         // 0 to 7 for bit in I/O mask
byte pinPort;           // pin's port #, in range 1 to 12
byte PCInum;            // PCINT# if pin is a PCI pin

// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}

// Get next pin number from pinsList, and its associated reg numbers
byte getPinNumber() {
  byte cc=*c;
  if (!cc)
    return 0;
  pin=0;
  for (; '0' <= cc && '9' >= cc; cc=*++c) {
    pin = 10*pin + cc - '0';
  }
  pinPort = maskBitIO = PCInum = nPCICR = maskBitPC = 0;
  if (pin < NUM_DIGITAL_PINS) {
    pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
    maskBitIO = digitalPinToBitMask(pin);
    if (digitalPinToPCICR(pin)) {        // Is it a PCint pin?
      nPCICR  = digitalPinToPCICRbit(pin); // 0, 1, 2 for p's PCICR bit#
      maskBitPC = digitalPinToPCMSKbit(pin);
      PCInum =  nPCICR*8+ getBitfromBV(maskBitIO);
    }
  }
  if (!cc)         // At end of string? If so,
    --c;           // allow for caller incrementing c
  return 1;
}

void genCode (char *affix, char *pinsList) {
  char *portLet = "?ABCDEFGHIJKL?";
  enum { portMax=12 };
  byte readmask;        // Input-bits mask
  byte port;            // Port #

  snprintf(buffi, sizeof(buffi), "\n// %s : pins %s", affix, pinsList);
  Serial.println(buffi);

  //==================================================================
  // Generate  "byte get<affix>() { // Get pins <list>"
  //              return PINu & mu | PINv & mv | ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "byte get%s () { // Get pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of get...() function
  nbuff = snprintf(buffi, sizeof(buffi), "  return");
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask)
      nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PIN%c & 0x%02x |",
            portLet[port], readmask);
  }
  snprintf(buffi+nbuff-2, sizeof(buffi)-nbuff, ";\n}"); // -2 loses extra " |"
  Serial.println(buffi);  // Print last two lines of get...() function

  //==================================================================
  // Generate  "void put<affix>(byte w) { // Put pins <list>"
  //              PORTu = PINu & ~mu | w & mu;
  //              ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "void put%s () { // Put pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of put...() function
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask) {
      snprintf(buffi, sizeof(buffi), "  PORT%c = PIN%c & 0x%02x | w & 0x%02x;",
           portLet[port], portLet[port], (byte)(~readmask), readmask);
      Serial.println(buffi);  // Print a port-setting line of put...() function
    }
  }
  Serial.println("}");  // Print last line of put...() function

  //=================================================================
  // Generate ISR's:  Process 3 possible pin-change interrupt vectors
  vecmask = 0;
  for (byte ivect=0; ivect < 3; ++ivect) {
    byte sinPort=15;        // currently-in-use same port #
    intmask[ivect] = 0;
    byte busyvect=0;              // Assume vector not used
    byte readmask=0;              // Input mask
    // Loop to see if vector is used
    for (c = pinsList; getPinNumber(); ++c) {
      if (nPCICR == ivect) {
    ++busyvect; sinPort = pinPort;  // Bits on same port get read once
    vecmask |= 1<<ivect;
    intmask[ivect] |= 1<<maskBitPC;
      }
    }
    if (busyvect) {     // If vector is busy, create its ISR
      snprintf(buffi, sizeof(buffi), "ISR(PCINT%d_vect) {", ivect);
      Serial.println(buffi);
      nbuff = 0;
      for (c = pinsList; getPinNumber(); ++c) {
        // See if it's a PCint pin, and on the current vector
    if (digitalPinToPCICR(pin) && nPCICR == ivect) {
      intmask[ivect] |= 1<<maskBitPC;
      readmask |= digitalPinToBitMask(pin);
      nbuff += snprintf(buffn+nbuff, sizeof(buffn)-nbuff, " %d,", pin);
      if (pinPort != sinPort) {
        snprintf(buffi, sizeof(buffi), "Pin %d's port #%d isn't #%d",
             pin, pinPort, sinPort);
        Serial.println(buffi);
      }
    }
      }
      snprintf(buffi, sizeof(buffi), "  byte datum = PIN%c & 0x%02x; // Read pins %s\n}",
           portLet[sinPort], readmask, buffn);
      Serial.println(buffi);
    }
  }
  snprintf(buffi, sizeof(buffi), "void setup%s(byte ioMode, byte enablePCI) {", affix);
  Serial.println(buffi);
  for (c = pinsList; getPinNumber(); ++c) {
    nbuff = snprintf(buffi, sizeof(buffi), "  pinMode(%2d, ioMode); // %2d, P%c%d",
         pin, pin, portLet[pinPort], getBitfromBV(maskBitIO));

    if (maskBitPC)
      snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "   PCINT %d", PCInum);
    Serial.println(buffi);
  }
  Serial.println("  if (enablePCI) {");
  for (byte ivect=0; ivect < 3; ++ivect) {
    if (intmask[ivect]) {
      snprintf(buffi, sizeof(buffi), "    PCMSK%d |= 0x%02x;", ivect, intmask[ivect]);
      Serial.println(buffi);
    }
  }

  snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0x%02x; // clear PC interrupts if any",
       vecmask);
  Serial.println(buffi);
  snprintf(buffi, sizeof(buffi), "    PCICR  |= 0x%02x; // enable PC interrupts\n  }\n}",
       vecmask);
  Serial.println(buffi);
}

void setup() {
  Serial.begin(115200);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("Starting Code Generation");
  genCode ("A0A1",  "14,15\0"); // A0, A1 on a nano
  genCode ("Pair78",  "7,8");
  genCode ("Trip346",  "3,4,6");
  genCode ("Quad789A", "7,8,9,10");
  genCode ("Hex8toD",  "8,9,10,12,11,13");
  genCode ("LotsSmall", "2,6,7,8,9,10,11,12,13,14,15,19,20,21,22,28,29,30,31,37");
  genCode ("LotsBig",   "31,37,38,37,38,45,46,52,53,54,55,61,62,63,69,70,71,76");
  Serial.println("Ending Code Generation");
  Serial.end();
}

void loop() {
}


In principle not. However, the voltage regulators may become quite hot, since you are going down from 12 V to 9 V and 5 V (especially the step from 9 V to 5 V is quite a lot). It depends on the current (in (milli)Amps) how hot they get.

For the adapter it does not matter, if it is 1 A or 10 A, the microcontrollers will only take whatever they need. Only if the adapter can deliver less than needed by both microcontrollers there is a problem.

The voltage regulators are not of switching type I guess, so they will use the same amount of amperes. Assuming the Arduino Uno takes 300 mA (at 5 V) and the NodeMCU 200 mA (at 12 V), you can add them together: 200 mA + 300 mA = 500 mA. Since this is less than 1 A the adapter can deliver, you are ok.


What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.

Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.


Best way to read CSV from SD card and store values by date

I highly suggest checking out this YouTube video (https://www.youtube.com/watch?v=5v5A3j7Rrco), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:

float id = 0; //used to provide a numbered ID to each data point

void setup(){
//initialize all your once-run variables and such
}

void loop(){
  //Write Log File Header
  File logFile = SD.open("NAME.csv", FILE_WRITE);

  if (logFile){
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

    String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }

  else {
    Serial.println("Couldn't open log file");
  }
}
}

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:


Nodemcu ESP12-E (ESP8266), Can I reprogramming when the UART pins are defined as GPIO?

Sure, you can use the UART pins as general purpose IO pins - however, it's far from ideal - for one simple reason:

The ROM issues messages on the UART at boot time.

This means that when you power the chip up whatever is connected to the UART TX pin will receive pulses of HIGH and LOW.

That may or may not be a problem, depending on what is connected. It's something you need to bear in mind though.


This is SOME of the code. We are missing the avergearray() function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..

From another source, I got this:

/*
# This sample codes is for testing the pH meter V1.0.
 # Editor : YouYou
 # Date   : 2013.10.12
 # Ver    : 0.1
 # Product: pH meter
 # SKU    : SEN0161
*/

#define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
unsigned long int avgValue;  //Store the average value of the sensor feedback
float b;
int buf[10],temp;

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");    //Test the serial monitor
}
void loop()
{
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(10);
  }
  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  avgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];
  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value
  Serial.print("    pH:");
  Serial.print(phValue,2);
  Serial.println(" ");
  digitalWrite(13, HIGH);
  delay(800);
  digitalWrite(13, LOW);

}

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?


How to read RC receiver channels without using pulsein() command with arduino

The keyword you are looking for here is interrupt.  What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?

Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what pulseIn() does, you need to attach the signal to an interrupt pin.  Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.

If the signal has risen from low to high then you record the time it happened.  If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose.  That difference is then the width of the pulse, which you can store in an integer to read in your main loop.

If you have a number of signals you want to monitor you might want to look into using the pin change interrupt which allows you to use any pin as an interrupt source.


Need help in the project "Arduino for audio processing"

The replacement microphone you link to contains all the circuitry in that instructable*.  You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.


Is it possible to use the same power source for the arduino and a high current

If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.


Placing decoupling capacitors when building an Arduino PCB with Atmega328-PU

The Autodesk link explains it very well.

You should place small/fast decoupling capacitors (0.1uF) close to the power pins of your on-board ICs to deal with local spikes in power consumption of those devices.

Place a larger/slower decoupling capacitor (1uF or larger, depending on many factors such as distance of the power supply from the board and expected power consumption) somewhere on the board to deal with varying loads and ripples in your power supply.

This has been common practice at least since I’ve started with electronics about 40 years ago (and probably much longer).


I suggest having simpler file names (same size, always 3 digit numbers)

/// Return a text "n000.wav" ... "n255.wav"
/// depending on the parameter
char* makeFileName(byte i) {
  static char name[9] = "nxxx.wav";
  byte digit = i/100;
  name[1] = '0' + digit;
  i -= digit*100;
  digit = i/10;
  name[2] = '0' + digit;
  i -= digit*10;
  name[3] = '0' + i;

  return name;
}


Printing the messages having problem in SIM 900A to Arduino

Hello Guys i found the issue. Serial.read() function reads only 62bytes. After i have update the serial buffer size in library file C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.H ... It shows the messages which is stored in serial buffer.


Can i send sensor data from arduino to cloud without sending it via PC

To connect to the cloud directly while the tracker is on the move, you'll need to use GSM & GPRS technology, ie. a SIM card to make a 3G/4G connection to the Internet. GSM gets you connected, GPRS does the Internet traffic. Using WiFi to connect to a router won't work since you'll soon get too far from the router.

I suggest initially investigating the SIM908 and SIM800L (there are others).

Here are 2 projects which both use the SIM908 (GSM, GPRS AND GPS):

Geolocation Tracker (GPRS + GPS) with SIM908 over Arduino and Raspberry Pi

Where is my car? Realtime GPS+GPRS Tracking of Vehicles Using Arduino

The cheaper SIM800 is also popular GPRS/GSM module (no GPS capability, but you already have that?):

QUICKSTART SIM800 (SIM800L) WITH ARDUINO

This technology is moving quickly, so you may find better options, for instance see:

Difference between SIM908 vs SIM808 modules

Hope this helps,
Regards, Geoff


What protocols and tools does Arduino Due use for flashing and debugging?

The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).

I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source BOSSA.  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.


Mega pin stuck high after driving optocoupler

Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)

Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current.  If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working).  Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.

(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)


Problem in RS485 Communication between Arduino and PC

You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on MAX3222.

Cheers!


What would be the best way of dynamically 'change' instances regarding dynamic memory?

I don't know what you'll make of this, but:
If you can set aside a properly aligned and sufficiently large memory block you can use the placement form of the new operator.
Placement new is essentially new without the the part that behaves like (and typically is) malloc.  Or put differently, it lets you construct an object inside of already allocated memory.  By "already allocated" I don't mean already allocated on the heap; the memory can come from whereever you want.  This more or less lets you make your own custom allocator with predictable behaviour that you don't get from generic heap allocator like malloc.
So you can set aside memory however you want.  It can be an array of unsigned char in static storage duration (global, static local, static member).  And placement new can put an object into it, or importantly, into part of it.  Basically you're making your own arena for your allocator.
It's up to you to align the memory correctly.  There are compiler keywords that can help with that.  You can also resort to an older technique oversizing the block just large enough so that a properly aligned sub-block exists and can be found within it.  However, on an 8-bit microcontroller like the AVR, there are no alignment requirements to speak of.
When it comes to using delete, well, you don't.  You just call the destructor on the object directly.  There are ways you could try to clean that up also.
If I become awake enough to completely understand your specific usage, I may try to make an example.  But that is the basic technique I'd consider.

Regarding avoiding new/malloc: the case against them it is often slightly overstated.  For example, doing a set of malloc / new at the beginning, and only the beginning, of your program and not thereafter is normally fairly stable and predictable.  For example, you can read a configuration out of eeprom in setup() and use that information to allocate say three "dynamic" "arrays" with malloc, that you know they won't total more than some testable maximum.  Maybe a slightly more accurate warning for them is something like: you will get into trouble if you don't have a reasonable understanding of your maximum heap usage and if your usage pattern requires that you free/delete/remalloc.
I mention this in part also because it's not completely unreasonable to malloc/new once, early in your execution, to acquire an arena to use with placement new calls.


The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.

So begin transmission 0x74

Write 0x01

End transmission

Begin transmission 0x74

Read n

End transmission


Arduino mini requires uploading on every power up?

There was a defective bootloader that shipped on some Arduino devices which caused the symptom you describe. See:

http://forum.arduino.cc/index.php?topic=51172.0

http://forum.arduino.cc/index.php?topic=74090.0

If that's the case, your options are to re-write the bootloader yourself (if you have the capability) or return to the manufacturer.


Here is some code that demonstrates both output and input methods
It used an I2c interface board, rather than connecting a lot of pins you only need 2.SDA and SCL on the board, Google "Arduino I2C" and you will find the interface board, or on EBay, usually costs $1.00.

/* YourDuino.com Example Software Sketch
 16 character 2 line I2C Display
 Backpack Interface labelled "YwRobot Arduino LCM1602 IIC V1"
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here:
// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
#include <LiquidCrystal_I2C.h>

/*-----( Declare objects )-----*/
// set the LCD address to 0x27 for a 20 chars 2 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f , 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);  // Used to type in characters
  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------
  for(int i = 0; i< 3; i++) {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.setCursor(0,0); //Start at character 4 on line 0
  lcd.print("IF YOU CAN READ");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("THIS,I'M WORKING");
  delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
  lcd.clear();
  lcd.setCursor(0,0); //Start at character 0 on line 0
  lcd.print("Use Serial Mon");
  lcd.setCursor(0,1);
  lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }
  }

}/* --(end main loop )-- */

If you need to find the address of the interface board you can use "I2C Scanner". There are many versions of this available on the web. Hope this helps


Is it possible to insert your own routine into the Reset procedure

Yes, it is possible. See the documentation on memory
sections, from the avr-libc manual. For example:

// Run this after initializing the stack pointer and zero_reg, but
// before initializing the RAM.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    // Whatever...
}

Note that this runs after both a warm reset and a cold boot. See
Gerben's answer if you want to tell the difference between these two
reset conditions.

Note also that, if you just want some data to be preserved through a
reset, you can put it in the .noinit section, no need to use the EEPROM.

Edit 1: In response to the OP's comment, here is a small program
demonstrating the technique. It just quickly blinks the LED three times
early in the program initialization, then three more times, more slowly,
during setup():

#include <util/delay.h>

// Blink the LED three times, fast, early in the initialization.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    DDRB |= _BV(PB5);      // pin PB5 = digital 13 as output
    for (int i= 0; i < 6; i++) {
        PINB |= _BV(PB5);  // toggle PB5
        _delay_ms(100);
    }
}

// Blink the LED three times, slowly.
void setup()
{
    pinMode(13, OUTPUT);
    for (int i = 0; i < 6; i++) {
        delay(300);
        digitalWrite(13, !(i & 1));
    }
}

void loop(){}

I tested it on an Uno, and it works.

Note that magic() runs before the Arduino core library has been
initialized. At this point, many core function, like delay(), do not
work. Any job that is done here should be done low-level, using only
direct port access and avr-libc calls.

Edit 2: In the previous version of this answer I forgot the used
attribute. It worked with the old Arduino setup I tested with, but not
with the newest IDE. Adding the used attribute fixes this.


code for line following robot not working perfectly

This test:

if (tmp = 1)

is always true. You are assigning 1 to tmp and that value (1), when
interpreted in a boolean context (i.e. as a truth value), is true.

You probably mean

if (tmp == 1)

and similarly for the next test.


circuit breaker/fuse necessary for IoT home monitor?

Is there a reason overcurrent protection is not needed in these projects?

You're comparing apples and oranges.
The two systems are completely different and have different concerns.
Case in point:

You want to burgle somewhere with CCTV installed. You can creep up on one camera unobserved.
You know a little about electronics and figure if you cut the feed to the camera you can short out the power and blow the whole system, thus letting you wander in unobserved.

But there's fuses on each feed, so all you do is disable the one camera and everything else is fine, catching you red handed.
Go directly to jail. Do not pass go. Do not collect £200.
Now... do you really care that much if all your home temperature sensors lose power because of a fault in one? Probably not. And the chances of there being a fault other than from human negligence is slim. Sure, you could add fuses, but why add the expense? It's really not needed for such a non-critical system.

edit: I'm thinking specifically about fire safety. e.g. the risk of a short circuit overheating 22awg wire run through the house?

22AWG wire has a resistance of about 53Ω per km. Say you have a loop of cable 20m long (10m there and 10m back again) and it shorted out at the far end. That's round about 1Ω.
At 5V you'd be drawing 5A of current.
If you have a really powerful power supply then it would try and supply that, and the wire would warm up - giving off about 25W of heat over the entire length. You might feel a bit of warmth from it.
Of course, most people would be using a smaller power supply than that for simple IoT things, so the power supply would just go "No. You're not having that!" and would die, or its internal fuse would blow. Or it would drop the voltage and get hot itself.
The chance of being able to start a fire from 5V over 22AWG from a normal power supply is pretty much zero. You're more likely going to start a fire from using a low quality power supply that itself melts and catches fire (i.e., a counterfeit Chinese phone charger).
With a very powerful power supply (tens of amps or more) and a short circuit close to the source (so low resistance) the wire will melt. Just that. It'll melt. Once melted there's no circuit, so nothing else happens. There's your fuse right there.
Once a wire has melted it doesn't continue to burn. And you don't get arcs at low voltages. It takes a lot of work to start a fire from low voltages. A lot of work and a lot of current.


Getting the voltage of an 18650 battery with an Arduino

Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:


Arduino UNO WiFi "wifi shield not present"

That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C->UART converter chip.

You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

  If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE.
  Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.