What you heard (about double integration and accumulating errors) is correct. Mathematically, you can do this, by integrating each device's acceleration to get its current speed, and integrating the speed to get it's current position, then taking the vector difference in the their positions to get the distance between them.

If you had highly accurate accelerometers in a very noise-free environment (both mechanical and electrical noise), you could do it for a (short) while before the inevitable tiny errors (which are also being integrated!) begin to dominate the data and make the results useless. But as a practical matter - especially for us experimenters using inexpensive equipment and subject to a lot of mechanical and electrical noises on the experimental platform, plus environmental electrical noise - this will happen even more quickly.


op amp circuit single sourced from arduino power

The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v...
One can use an old LM324 or LM358, but output is not going up to VCC...
OPA140 is a correct choice.
Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.


pubsubclient won't compile in Arduino and VSCode IDEs

The library is somehow modified. There should be no {} in virtual size_t write(uint8_t) {}; or the whole line shouldn't be in this .h.

Reinstall the library.


Powering 4 servos with an external source

When choosing a power source, you'll have to consider a few requirements:

Required max amperage (max draw of power)
Required voltages (AC or DC, and available voltages)
Does it have to be mobile?

How long does it have to be powered? (how to recharge/refuel?)

Also see this tutorial it explains that you need a certain voltage for a device to work, too high voltage can result in permanent damage. For amperage, you need to have at least the minimal required, too much is no problem.

Since you don't really have a problem to fix, I can only tell you what I've worked with or what I've liked.

Bench supplies

Bench supplies are great while prototyping, they don't run out (like batteries) and can have a large range of voltage and supply a lot of power. I've looked around to get a nice bench power supply, but I found that they're quite expensive. If you want a variable supply that can do up to 5A, it'll cost you some real money (though it usually is well worth it).

Though my setup has always worked great for me, I use:

converted PSU (PC power supply)
Adjustable step down module

For the PSU, you could also add indicator LED's, they're great because they can supply very much power at very convenient voltages (12v, 5v, 3.3v, -12v). Also since it's a PSU it has overcurrent protection and thus is reasonably safe.

I've also bought the "adjustable step down module" from E-bay, you can power it from a 24V or 19V source like a laptop charger. You can set the output voltage and output max amperage. You can even see when the supply is limiting on power or on amperage. (So you can check if your device is taking more current than set)

"Moving" projects

The easiest thing here is (multiple) batteries, check the tutorial of sparkfun again. If you put them in series, you will sum up the voltage. If you put them in parallel, you will sum up the capacity.

I think batteries are the easiest way to power your device. You can check different types of batteries, they have different voltages and "ampere hours". Battery holders are cheap and you can easily replace them if they run out.

On the subject of rechargeables, I would go with an Ni-Mh pack. I've got a Ni-Mh pack for airsoft and it's very reliable and easy to charge. Li-Ion requires much more care in handling and charging.

Other options can be solar-cells or other harvestable energy, but these often aren't really viable.

Extra

When starting to move, a servo can suddenly pull a lot of power. Not all supplies can handle this well. So the other servo's may "jiggle". Often, it's good to have a capacitor that can act as a "reservoir" or for smoothing. Same goes with devices that reset in some scenario's.

*I hope this gives you an idea on some possibilities, I haven't highlighted all options (there are too many), you should check tutorials/video's and see what works for you.

For example, check this instructable that focusses on some (analog) points that I didn't mention.*


Does a graphical driver chip exist for this project?

I have no idea if there is a chip or not, but I doubt it.

But then, why do you need one?

You already know how to communicate with the screen, so why not off-load those functions on to another Arduino (make your own small ATMega328P based board to do it) and then communicate with that through whatever means you like from your Leonardo?

You don't need a dedicated chip to do what you can quite easily program an Arduino to do.


Can't replace SoftwareSerial by Serial1 on Mega board

what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program.
A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?


Read float and long from external EEPROM chip

1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most
significant byte (MSB, here 01011010) comes first.

I recommend against this order. If you can, swap all the bytes and store
the value LSB first, i.e. with the least significant byte first, and the
most significant byte last. This will make your life easier since it's
the order used internally in the Arduino. If you can go little endian,
then you will be able to read the data straight into the required
variable, with no conversion needed, as in:

i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

and it will work identically with any data type.

If you cannot choose the byte order (maybe you cannot control what is
inside the EEPROM), then you will have to reverse all the bytes. You can
do this either with bit shifts or by explicitly moving bytes.

  bytes[1] << 16

This will not work. Per the rules of the C++ language, bytes[1] is
implicitly promoted to int type before the shift, then it is shifted
as an int. But on your Arduino an int is 16-bits long, thus by
shifting it 16 positions you are dropping off all of the bits.
Actually, this is even worse: you are invoking what is known as
undefined behavior, meaning that it is considered nonsense and the
compiler is free to interpret however it wants.

To do this properly, you first have to explicitly cast bytes[i] to
unsigned long. It has to be unsigned because changing the sign bit on
a long by bit shifting is also undefined behavior. Thus, the proper
way of reconstructing the number via bit shifts is:

long j = ((unsigned long) bytes[3] << 0)
       | ((unsigned long) bytes[2] << 8)
       | ((unsigned long) bytes[1] << 16)
       | ((unsigned long) bytes[0] << 24);

This is portable (it should also work on big-endian architectures) but
only works with integral types, not with floats.

For reconstructing a float, my preferred option would be to use a
union, in order to access the bytes of the variable explicitly. Then
you just have to copy the bytes from the buffer to the union in
reverse order:

union { float f; byte b[4]; } data;
data.b[0] = bytes[3];
data.b[1] = bytes[2];
data.b[2] = bytes[1];
data.b[3] = bytes[0];
float x = data.f;

One nice thing about this approach is that it works with any data type.


Is there a thermal sensor with a distance of 10 meters for Arduino

How about this one at £20?

The range depends on what lens you put in front of it - this has to be plastic as IR doesn't penetrate glass, but you can set your own range, like a focus adjustment. Commercial IR remote thermometers generally have aiming dots (laser) so you can see the optimum range - there's a fixed lens.

The actual sensor won't have a defined range, because of this.


How can I concatenate multiple byte Arrays into one Array

You can concatenate with memcpy. You just need to set the pointer at the right place inside the c1 array.

memcpy(c1, a1, sizeof(a1));
memcpy(c1+sizeof(a1), a2, sizeof(a2));
memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));


Vibrating motors with different intervals

Like Edgar commented, you need to check out Blink Without Delay (http://arduino.cc/en/Tutorial/BlinkWithoutDelay). Learn what they are doing and you will get this just fine.

Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: http://playground.arduino.cc/Main/LibraryList#Timing --> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!

Here is a complete set of code to answer your question. It should work perfectly for you.

/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015

To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/

#include "Timer.h"

Timer t;

boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;

void setup()
{
  //set pins to outputs
  pinMode(buzzPin1, OUTPUT);
  pinMode(buzzPin2, OUTPUT);
  pinMode(buzzPin3, OUTPUT);
}

void loop()
{
  //UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary

  /**
   * This method will generate a pulse of pulseValue, starting immediately and of
   * length period. The pin will be left in the !pulseValue state
   */
  //Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
  //see here: https://github.com/JChristensen/Timer/blob/master/Timer.h

  if (buzzMotor1Now==true)
  {
    buzzMotor1Now = false; //reset
    t.pulseImmediate(buzzPin1,buzzTime,HIGH);
  }
  if (buzzMotor2Now==true)
  {
    buzzMotor2Now = false; //reset
    t.pulseImmediate(buzzPin2,buzzTime,HIGH);
  }
  if (buzzMotor3Now==true)
  {
    buzzMotor3Now = false; //reset
    t.pulseImmediate(buzzPin3,buzzTime,HIGH);
  }

  t.update(); //update all timer events
}

Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX_NUMBER_OF_EVENTS value in the Timer.h (https://github.com/JChristensen/Timer/blob/master/Timer.h) file.

PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.

If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.


Problems with Arduino + IR + Raw code low memory


AnalogRead too slow... Faster alternative?

Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:
Average your signal before sampling it! This can be done by connecting a simple RC lowpass to your AD input.
With that you get rid off those high frequency noise you don't need, but without wasting CPU time.


Why is my class losing a field in the middle of a method

I think what you mean by stripLength "disappearing" is that your stripLength 2 trace does not appear. This is going to be because you never reach this point in the code.

Look at buf: it's defined as an array in the .h file, but you don't ever allocate any memory for it. buf[stripLength] = {0} doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to.  You want something like

buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

Remember to free it again in the destructor.

(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as uint32_t buf[]. It's more common, and certainly legal, to use uint32_t* buf.)


Http request in interrupt esp8266 not working

Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main loop() function to perform your HTTP request.


Connect one HC-05 "master" to two slaves at the same time

AT+CMODEis mainly used for setting the address pairing purpose. What chrisl stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as 2 you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.


Usbasp Arduino Uno Bootloader Flash Error - Win 10

The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.


Testing tri-state pin - erroneous results with internal pullup

The internal pull-up is around 50k. So, install an external pull-down (to ground) of a somewhat higher value, like 1M.

Now:

Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading changes, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.

You may need a slight delay to allow the low-value pull-down to change the pin state.

Amended code to demonstrate:

// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be

pinMode(pinTest, INPUT);
delayMicroseconds (100);
byte firstReading = digitalRead(pinTest);
pinMode(pinTest, INPUT_PULLUP);
delayMicroseconds (10);
byte secondReading =  digitalRead(pinTest);

if (firstReading != secondReading)
  Serial.println(" - HiZ");
else if (secondReading == HIGH)
  Serial.println(" - HIGH");
else
  Serial.println(" - LOW");

(Only showing the part that detects the pin state, the rest is the same).

Output:

H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH

As you can see, working perfectly. I needed a longer delay after turning the internal pullup off because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.

So:

10 µs delay after turning the internal pull-up on
100 µs delay after turning the internal pull-up off

Theory for the delays

The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where T = R.C.

Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:

50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

And to discharge through 1M (1e6) ohms, discharging should take:

1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.


Did you try:

Reading the SD card in your computer ... if  you can read (or write) files, that means the SD card is intact
Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).


No Information obtained when using 2 x SoftwareSerial ports on Arduino Nano

You cannot use two SoftwareSerial instances at the same time - or not for receiving anyway.

SoftwareSerial is a "last resort" system - only to be used if there is absolutely no other option. And then you need to be aware of certain information and rules:

Only one device can listen at any time, switchable using the SoftwareSerial::listen() method
When a byte is being received nothing else can happen - it takes over the entire CPU for the duration of reception
When a byte is being transmitted nothing else can happen - it takes over the entire CPU for the duration of transmission
There is a minimum required time between successive bytes when receiving that causes problems at higher baud rates

These limitations mean that, when using multiple devices, you have to know before hand which device will be sending you data so you can be ready to receive it. It also means that SoftwareSerial is effectively half duplex - it only really works properly when you are either only receiving, only transmitting, or using a "call-response" scenario like sending "AT" commands and looking for a response afterwards.

So the general recommendation is: use hardware UARTs whenever possible (and if you don't have enough, then consider using a different, more suitable, board with multiple UARTs), and if you must use SoftwareSerial then limit yourself to only one instance of it.

As a last resort you can always use multiple boards and connect them using a different system, such as I2C.


Connect ethernet cable wires directly to pins

I am by no means an expert on this, this answer is ~20 minutes of me googling things, but I would say that in theory it is probably possible to do this with an arduino, at least at the lower transfer rates anyway, and certainly from a "will it kersplode my board" point of view - probably not since ethernet runs at +/- 2v (ish) and ~10mA (ish). However:

The ethernet protocol is exceedingly complex, with many layers needed to actually communicate with anything useful, all of which you would have to implement from scratch (there won't be a library to just drop in) and I'm not completely convinced that an entirely software-based implementation of the stack would fit on the arduino (but I could definitely be wrong there - and actually, on further thought, this probably is wrong, but I reckon I couldn't write it so it fit, but I'm a reasonably average human being).

Arduino is all about hacking and re-inventing wheels just for the fun of it but I am absolutely certain that there is no fun to be had re-engineering Ethernet and TCP/IP and all of the stuff in betweeen from scratch (obviously my opinion, I enjoy all sorts of things others don't, so YMMV).

My suggestion would be - if you don't like ethernet shields, look into getting a 'raw' ethernet controller chip (like the one soldered onto an ethernet shield) and build it directly into whatever device you're trying to make first, that'll give you plenty of exposure to how ethernet works at that level, then you can decide if you're still up for re-inventing the brain that invented the wheel. Good luck!


Error while sending message using gsm sim900a module interfaced with arduino uno

Update your IDE software. You need IDE 1.0.4 or later.
I copied your code into my 1.0.5 IDE and compiled it without any error. So it is most probably your version of the Arduino IDE.


Record Ping time using ultrasonic sensors and calculate speed

You can try this, but I don't know if this gonna works or not since it is "imaginary-based"

const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop()
{
    if (ultraSonicdetect())
    {
        while (ultraSonicdetect(trigPin1,echoPin1)); // wait the car pass ultrasonic 1
        first_time = millis();
        while (!ultraSonicdetect(trigPin2,echoPin2)); //wait the car approach ultrasonic 2
        second_time = millis();

        //here you can calculate the speed, time needed to travel from ultrasonic 1 to ultrasonic 2
        //can be calculated from
        //(speed = second_time - first_time) / sensor range
    }
}

bool ultraSonicdetect(int trig, int echo) {
   long duration;
   float distance;
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration * 0.034) / 2;
   if (distance<35) return true; else return false;
}


I had same problem. You should download Arduino IDE 1.6.8

https://www.arduino.cc/en/Main/Software


AT commands are executed by the AT interpreter firmware. If you've been attempting to flash other firmware to the ESP8266 module, there is no longer any code in it that interprets AT commands. If you want to it to respond to AT commands again, you'll need to re-flash it with that firmware.


How to get data from a device using ethernet connection with arduino

You are out of luck: The device talks SMP (Static Managment Program), which is a close-source product of the same vendor.

The protocol used by SMP is not documented. The only way to access it is via the vendor own Windows software management.

Decoding the protocol is out of question.


Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.

Cheers!


TCP communication between Arduino client and server

you are missing the HOST header in the request, so the server tell you to 100 CONTINUE you request.
Also yes, the final empty row IS mandatory

for example, to ask www.example.com/index.html

GET /index.html HTTP/1.1
Host: www.example.com


Confusion on array definition at Arduino website

1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

  2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

  Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.

So "hello" is actually "hello\0".


Why is there no hex file generated when I "build binary output" from the Arduino IDE?

Based on your setting with the URL for esp8266 package and bin file name with "...generic" I assume you want it for esp8266.

esp8266 doesn't use hex format and "Export compiled binary" creates bin. You can upload it with esptool.

For AVR boards "Export compiled binary" generates hex. You can upload it with avrdude.


arduino & drivers to control 5 brushed CIM motors independently?

You should have just enough I/O with UNO, so long as you don't want to connect any other hardware/sensors.  Since this is unlikely, it would be better to use another board like Mega, but I'll provide solutions anyway in case you want to try them out:

Option 1:  For 5 motors controlled with L298N boards you'll need 15 output pins, 5 of which should be PWM.  Fortunately, there are 5 PWM outputs on the Arduino UNO on PORTB and PORTD.  The remaining 10 outputs need only be digital (PORTB has 1 and PORTD has 5).  You can use DDRC and PORTC commands to change function of the analog inputs labeled A0-A5, making them digital output, thereby gaining 6 more digital output pins for a total of 12 (more than the minimum 10 needed).
Option 2:  It is possible to use other PWM motor drivers that reduce number of pins required.  Examples are DRV8838 (link to supplier) and DRV8833 (link to supplier) where 2 wires are needed per motor channel.  As a bonus, these drivers are also significantly more compact than L298N.


Simple webpage serve with Arduino ethernet shield on SD card

"ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.


how does c++ understand which function must to use?

The compiler decides which function to use based on the variable type information. Imagine you write

str += "test";

If you declare str as a constant, the above line will throw an error. So if you write AdptSendReply(str) instead, the compiler will call the const function. Likewise, if you declare str as a mutable variable, the above line will compile fine, and, should you call AdptSendReply(str), the compiler will use the non-const function.


How to use IRremote library with atmega8a

Changing the internal oscillator to 8MHz helped.


I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.

In other words: the ESP8266 isn't strong enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.


RobotLinking 18B20 pinout and circuit board weirdness

From the look of the board, it is designed to support multiple devices. I'd suspect that the three sets of holes give different mappings of the device pins to the board pins. Could it be that the sensor is soldered into the wrong set of holes?

If you have a meter or can see the traces you could look to see if the middle set of holes is wired the way you would expect. If that is a photo of your board, it looks like you have enough length in the leads on the sensor to move it to the middle holes.


my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.

your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.


Digital I/O threshold voltages for ATmega32u4

LVTTL is Low Voltage Transistor-Transistor Logic. In general, the
term "TTL" is used for a digital signal.
The "Low Voltage" part is special,
the ATmega32U4 switches from low to high (and vice versa)
at low voltages.
Just as it is written. For example, when the ATmega32U4 runs at 5V,
then:
VILmax = 0.2 * 5 - 0.1 = 0.9 V.
VIHmin = 0.2 * 5 + 0.9 = 1.9 V.
Between those values the input signal is seen as low or high,
but the exact voltage when it switches from low to high may
vary.
When the microcontroller is running at 5.0 V and is used
within the specifications of the datasheet, then a voltage
below 0.9 V is always seen as low and
a voltage above 1.9 V is always seen as high (guaranteed).
Those voltages is what a electronics designer must consider.

In the datasheet of the ATmega32U4 at page 403 is paragraph 30.7 "Pin Threshold and Hysteresis" with figure 30-22 and 30-23.
The figures show that at 25°C and 5V, the input switches from low to high typical at 1.55 V and it switched from high to low at maybe a slightly lower voltage.
The hysteresis is almost none and the voltage depends on VCC and the temperature.

(Thanks to Edgar Bonet for the correction/addition)


Trying to run two simultaneous loops that do the same task with different delay cycles

The Arduino Simple Timer library (and other similar timer libraries) are made for exactly this kind of application. Your setup() routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call timer.run() reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). timer.run() will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.

There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)

Your loop function is free to do whatever else, as long as it calls timer.run() frequently enough that your application can meet its timing requirements.


How can I maintain PWM output while still performing other tasks?

PWM just runs once started. It's all managed by a completely separate bit of silicon inside the chip.

Once you have done analogWrite(...) the PWM will just keep going until you tell it otherwise.


DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)

You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.

I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/


Arduino Uno still boots and runs but no serial communication over USB

As @Juraj mentioned, if it's enumerating as a serial port, the atmega16u2 is fine.

You may be able to replace the atmega328p/au. It will take some doing; you'll need to remove the chip, insert a new one, and use another Arduino as an ArduinoISP to program the bootloader into your new blank atmega328p.

Any chance you might have uploaded a sketch that is spamming the serial port on startup? If so, try this procedure (h/t to the Arduino forums, it has saved my bacon a number of times):

Disconnect the usb connection
Begin holding the Reset button
Connect the Arduino
Initiate upload (while still holding Reset continuously)
As soon as you see the RX light flash, release the Reset button.
The first attempt to upload will fail, but with luck, the second try will occur before the 2-second bootloader delay ends (and your sketch begins to execute).

If this works, I'd suggest including a delay(3000); or similar in your setup().


What type of power supply is the Arduino Due’s 5v pin and what is its current?

An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, OR to the output of a step-down buck regulator converting the DC barrel jack to 5V.

None should be considered "high current" for servo or motor use.

Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.

The buck-converter controller chip is a LM2434, whose datasheet specifies 1A maximum output current.

Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.

If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).


Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350)

I worked on a project similar to yours. I think you forgot to establish a connection first.
Just add those lines of code at the top of setup() method:

 gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
 toSerial();
 delay(2000);
  gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSDA=2,3");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSND=2,0");
 toSerial();
 delay(2000);

I hope it works for you. Else, you can use AT+UHTTPER=2 after all to check for error source.


Arduino Pro Mini and Electronic Speed Controller (ESC)

The ESC should have no problem with 3v3 signal.


Without a shield? Yes, it's possible.

You send it serially to your computer as you are doing now. Then you write some software for your computer to read that data serially and send it on to your chosen web service.

Can the Arduino magically send data to the internet by itself without you investing in a network connection of some form (WiFi shield, Ethernet Shield, etc)? No, of course not. If it could there would be no market for the network shields, and so they wouldn't exist.


how to use the decoded raw value to send IR signal in arduino

If the signal is reported as "unknown" the library couldn't identify the protocol (RC5, RC6, NEC, SONY, etc).  If the library doesn't know the protocol,  the decoded number is meaningless. Simply put, an IR remote transmission has a frequency; a header; some data (the actual remote command); and a footer.  Without knowing the protocol the library doesn't know the length and shape of each section, so the purpose of the decoded number is only to show quickly if the decoding is receiving the same code at each keypress. You can verify this yourself.  Every time something makes an already known remote code be reported as "unknown", the code received is different from a real code, so simply guessing (or knowing beforehand) the protocol is not going to help anyway.


Error messages while verifying code with Visual Studio Code

It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

You have to downgrade to January release 1.42 AND
Then turn off automatic updates for the moment.

How to get the release: Click here

Before installing /downgrade
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.


int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
  x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1)      setRGBandBlink13(HIGH,LOW,LOW,1);
    else if(c==2) setRGBandBlink13(LOW,HIGH,LOW,2);
    else if(c==3) setRGBandBlink13(LOW,LOW,HIGH,3);
    else if(c==4) setRGBandBlink13(HIGH,HIGH,LOW,4);
    else if(c==5) setRGBandBlink13(LOW,HIGH,HIGH,5);
    else if(c==6){
      setRGBandBlink13(HIGH,LOW,HIGH,6);
      c=0;
    }

  }
}

void setRGBandBlink13(bool newR,bool newG,bool newB,int times){
  setRGB( newR, newG, newB);
  blinkPin13(times);
}

void setRGB(bool newR,bool newG,bool newB){
  digitalWrite(r, newR);
  digitalWrite(g, newG);
  digitalWrite(b, newB);
}

void blinkPin13(int times){
  for(int i=0;i<times;i++){
    digitalWrite(13,HIGH);
    delay (250);
    digitalWrite(13, LOW);
    delay (250);
  }
}


How to protect sensors used on atheletes?

The only way this is ever done is with some kind of product casing. You can buy pre-fab cases for electronic projects, but to get something really slick and appropriate for your purpose, you're gonna have to make something yourself. You might look into 3D printing.

Something like this might work: https://www.sparkfun.com/products/8601

For protection from salt-water, this product is worth a look: http://www.corrosionx.com/

There's some different products there, but I've seen a demo of that product, where we ran an entire RC airplane system, servos, motors, and receiver, UNDER WATER.


The module needs a good 5v supplier as it might have a peak of 1A or 2A, when it registers to the network or connects to 3G.

You need to make sure that you share the ground between the power supplier and you use some 2 pins on your arduino to connect the GSM module.
Dont try to get a fast baudrate as software serial doesnt work, try with 9600 to start then see if it response to the AT command.

SIM800 is a very simple module, try with an FTDI in case you want to make sure you didnt break your Arduino.

For more help, share your schematic how you have connected the arduino.


Why can only some digital ports output PWM and the others not?

Check out the ATMega328p datasheet: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.

It's a limitation, but so is everything else.

If you do not like it, you can always choose a different microcontroller, either AVR or something else.
Certain models might  be designed to have more units of a specific type than you would find on generic microcontrollers.


Using an Arduino as a lithium ion charge controller

If you are going to design your own battery management system here are a few issues you will need to deal with:

You need to understand the methods to determine the End Of Charge (EOC).  This could be monitoring cell temperature, measuring cell voltage or current for patterns, or integrating current over time (coulomb counter).  Different battery chemistries usually dictate which approach to take.
You need to check with the specific battery manufacturer to determine what charge rate you should use for this specific battery.  Knowing the chemistry is good.  But it is usually best to use the charge rate data from reputable manufactures.
Some batteries can not be completely drained.  If not already part of the LION battery, you will need to design a protection circuit to cut the battery off before this happens.
For such batteries, you need to add a trickle charging circuit in case the battery has been overly discharged.  Such a circuit only allows a small amount of current in.  The current is usually so small that normal monitoring is not necessary.  This is a last resort procedure built into most good chargers to recover overly discharged LION batteries.

...this is not a complete list. These are some of the issue which might be considered when designing a secondary battery charger.  There is a lot more good information about batteries here if you would like to research this subject in greater depth.


Undefined reference to stdlib (strtof) while compiling

Its because the "strtof" function resides in "stdlib.h",
"Stdio.h" deals with i/o tasks.

Since you din't include you get that undefined reference error.
Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

  Update1:

  After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.

  Cite:

  https://www.arduino.cc/reference/en/language/variables/data-types/double/
  https://www.arduino.cc/reference/en/language/variables/data-types/float/

Reason:

The size of the double and float is the same, ie: 4 bytes
and even if you use double its actually the float itself and wont gain any precision advantage.

Solution:

Since the size of the double and the float is same there is not point in having two function definition doing the same job.
so

Use "strtod"  instead of "strtof" or
Define a macro #define strtof(A, B) strtod(A, B) in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".


Moving an item on a pole, can an Arduino work for my project?

I am also a software guy by profession. I've always liked tinkering with electronics, and have recently gotten into Arduino. It is an excellent platform for developing hybrid hardware/software solutions for problems like this. It is very easy to use, both hardware and software.

There is a large ecosystem of add-ons called "Shields" that just plug in. You can probably find a motor control shield that will do exactly what you want.

Your biggest challenge, I think, is going to be mechanical. How will you hold the polisher in position, and make a mechanism that will raise and lower it?

Off the top of my head what I come up with is a U shaped metal bar with a threaded rod in the opening of the U. You'd build a "sled" that would grip the bar and would have teeth that would grip the threaded rod. Then your would have a motor on the end of the assembly that would turn the threaded rod to move the sled up and down on the bar. You'd attach the polisher to the sled. You'd probably need a spring or rubber holder so that the polisher would press gently on the surface being polished but with some freedom of motion.


That's not how you compare C strings.
When you write
if (topic == "/home/bedroom/light1")

you're comparing whether the character pointer topic is the same value as the address of the string "/home/bedroom/light1", which of course it is not in this case.
To compare C strings, use the strcmp() function, which returns 0 if they're identical.
if (strcmp(topic, "/home/bedroom/light1") == 0 && p == '0')


Resistors on LCD - does a small difference matter?

No, it doesn't matter. That resistor is just for the backlight LEDs. The larger the resistor the dimmer the backlight will be.  As @VE7JRO suggests, you can always put two 330Ω resistors in parallel, which will halve the resistance to 165Ω, which will give a brighter backlight.


Here is a link. Use google to find more. It is not difficult.


A H-Bridge has 3 modes of operation in addition to disabled. The ENable pin, when driven low, disconnects the power and stops the motor from being actively driven it is true. However that is not the same as the STOP mode of the H-Bridge.

The logical internal connections in the H-Bridge for the three modes are like this:

When in STOP mode the motor is effectively short circuited and the power supply is disconnected. When the motor is spinning and not being actively driven it is generating power. By feeding that power into a load you increase the load on the motor itself, slowing it down. The bigger the electrical load the slower the motor will go - and you can't get bigger than a dead short. So this mode effectively stops the motor in its tracks. It puts the breaks on.

Conversely, if you just disconnect the power, there is nothing much to stop the motor spinning, so it will keep going depending on the amount of friction, wind resistance, inertia, momentum, etc.

If you are happy with that kind of operation then yes, your method will work fine, since you will have access to forward, reverse, and a way of controlling the power to the motor. You just won't be able to apply the brakes, and you will have to either rely on the natural slow-down of whatever you are driving, or do something clever involving using just enough reverse to stop the motor before cutting the power.


Getting my keypad to reset when wrong password is entered

You have the part checking if the key equals the position in the password and if so you increment the position.  But if it is not equal then you don't do anything.  You should probably have an else there that resets the position to 0 and tells the user they entered the wrong password.


The 5110 Nokia LCD display is based on PCD8544. It is not possible to read the device display memory. The controller has only serial data input.

Typically a graphical device driver for that display will use an offscreen bitmap (buffer). To check the pixel status you would need to check the status in the offscreen bitmap.

Some device drivers use only text and copy font bitmap directly to the display memory. In that case you cannot check the status of the pixel (if the text is not buffered).


Need advice on serial bytes reading optimization

In principle it is ok to use your way, but a simple improvement is to change the magic numbers (38, 39) to constants or define:

const int offset_heat = 38;

…

float Heat = (float)data[offset_heat];

or a define:

#define OFFSET_HEAT 38

…

float Heat = (float)data[OFFSET_HEAT];

If all values are consecutive you can keep a variable to read the values:

int offset = 38; // Normally starts at 0 assuming you read values from the start

float heat = (float) readByte(&offset);

…

int readByte(uint8_t* offset)
{
    int value = data[*offset];
    (*offset)++;
    return value;
}

This increases the offset after reading the value.

Some remarks:

It's a convention not to use capitals for local variables (so change Heat to heat)
You don't use the Heat variable in sprintf, maybe this is intentional.


I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called ArduinoSTL.


How do I send tweets with flame sensor and ESP8266?

I guess your baud rate and network connection with the wifi module is working fine. Have to say that it is a bit difficult to get the data sent to ThingSpeak with ESP8266. I actually did some experiments to get the data sent. The problem is actually with the delay. Adding a delay of 5000 ms between sending the tweet length and the tweet content sorts it out. You can use GET format. Check out this Instructable.


What is Clock pin and Data pin, Orientation in Grove LED bar

on the LED circuit board there are a few connections, notably DI and DCKI.

The DI pin is the data pint and DCKI is the clock pin.

According to the header orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.


There is no DRAM, SRAM nor flash interface in ATmega, so you can't extend your chip memory. You can only connect serial (SPI, I2C) or parallel memory (usind GPIO).

Neither SPI nor I2C require any specific libraries.
SPI is much simpler to program than I2C and much faster, but require more wires.

Instead of using rather slow EEPROM, you can try FRAM (non-volatile) or SRAM (volatile, but may be battery-sustained). They are usually available with the same interface as EEPROM, but don't suffer from limited number of erase cycles. FRAM can withstand ridiculous number of erasures, SRAM is virtually indestructible.


Arduino remote-controlled car stops after a few seconds

The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so bluetooth.available() would return more than 1U after a couple of loops. This was fixed by changing the following:

void readCommand(void) {
  command = 0U;
  if (bluetooth.available()) {
    while(bluetooth.available() > 1U)
      bluetooth.read();
    command = bluetooth.read();
  }
}

The 'make-it-run-backwards' problem was also solved, but was unrelated.


Leonardo (32u4): Timer0 problems with CTC mode

You should re-enable interrupts after you finish setting up. Use either

interrupts();

or

sei();

If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.

Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.


for each accelerometer:
   sample the accelerometer;
   low-pass filter its values (current and recent history) to remove noise;
   multiply by the sample interval to get the velocity increment;
   add the increment to a running sum to get velocity;

   sample the velocity (the running sum you just updated);
   maybe low-pass filter, as above;
   multiply by the sample interval, as above, to get the position increment;
   add the increment to a running sum to get position;
end;

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?


Just figured out I didn't have the pin mode set, it works fine now, thanks.


minimal code for multiple buttons de-bouncing

Yes, your code should work as the most basic debouncing, although the
debouncing time may be a little bit short. Note however that, in many
instances, one would like to have a little more that the most basic. One
may also want:

deglitching: when the button is held down, your hand may make the
contacts move a little bit, making spikes in the reading that are not
associated with a real change in the button position; you don't want
those spikes to read as "released and pressed again"
edge detection: many times you are more interested in the button
press event than in knowing whether the button is down or up; this can
be handled by another function, but it can be convenient to integrate
it with the debouncing
non blocking operation: your program may have better things to do
than wasting CPU cycles inside delay().

Those are the reasons most debouncing codes are significantly more
complex. But it's often worth it.

Edit 1: In view of the comments, some clarification seems to be
needed. There are two kinds of glitches a mechanical button can
experience:

when the button is mechanically changing position, i.e. it is being
depressed or released; this is called a bounce
when the button is being held down, especially if the pressure on the
button is low and the finger applying that pressure is somewhat
shaky.

Most debouncing libraries you can find actually address both kinds of
glitches. Thus, they do more than just debouncing, they do what I
called “deglitching”. The previous answers implicitly assume that a
proper debouncing code must address both kinds.
The code posted in the question only addresses the first kind of
glitches, i.e. the bounces in the strict sense. That's why I wrote
that it does the “most basic debouncing”. It is however susceptible to
the second kind of glitches. So yes, with this code glitches can persist
even after debouncing.
Edit 2: As an example, consider the Bounce 2 library. It
provides edge detection, non blocking operation and, in the default
configuration, full deglitching. However, it can be configured to use
an alternative debounce algorithm called “Lock-out
interval”, which is more responsive but does not protect against the
“type 2” glitches mentioned above: it “does not cancel noise”, as the
documentation puts it.


LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.

But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.

The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:

  On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.


ESP8266 (Huzzah Feather) I2C scanner finds nothing

This particular issue was due to a faulty wire on the I2C bus. I replaced the wire and I was able to scan and get an address to the I2C LCD controller.

I still cannot get text to the LCD.  I will start a new question for that.

EDIT:

Upon scrapping my I2C_LCD_DISPLAY library, I downloaded one that was linked in a ESP32/8266 tutorial for the LCD, and finally got it working.


Understanding the meaning of '[](){ /* Code */ }' in an argument

As KIIV kindly pointed out, it has to do with lambda functions


Connect one at a time and run the change address sketch mentioned by Yeti.

Naturally change each one (one at a time) to different addresses (ex. 0x62, 0x64, 0x66).

  i still don't know whats the address of the 2nd one

The address is what you change it to.

Then connect them all back up again and run the I2C scanner. You should see all 3 addresses.

  documents state that address changes will be gone when i power it off

If that is true, save the address for each module in EEPROM. Then use that code to change the module address in setup.

See the address in the code you posted?

#define    LIDARLite_ADDRESS   0x62          // Default I2C Address of LIDAR-Lite.

If you don't want to save the address in EEPROM just upload three versions of the sketch with a different address in each one. Note that the address must be even (eg. 0x62, 0x64, 0x66).

But it would be very simple just to read from EEPROM in setup and keep the address in a variable rather than a #define.


How can I made my Arduino follow the time exactly?

Three things you can do - any combination of these is good, but the more the better:

Use an RTC module to keep more accurate track of the time.
Connect the Arduino to the internet and use NTP to get the exact time.
Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell.
The GPS and internet time are both very accurate.

Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.

To increase the accuracy of your existing method you should count seconds, not minutes.

Start by recording the current millis. When 1000 of them have passed you can increase your seconds.  Don't rely on millis() % 1000 since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it should have happened, not where it did happen.  This can help to combat some clock drift.

static unsigned long mscount = millis();

if (millis() - mscount >= 1000) {
    mscount += 1000;
    seconds ++;
}

Then every 60 seconds you can increase your minutes:

if (seconds == 60) {
    seconds = 0;
    minutes ++;
}


Why isn't this pushbutton program working?

Your code and schematic both seem to be wrong.

Try out this schematic:

And then code:

const int kPinLed = 6; // LED - Pin 6
const int kPinBtn = 7; // Push Button - Pin 7

void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
  {
    digitalWrite(kPinLed, HIGH);   // LED ON
  }
  else digitalWrite(kPinLed, LOW); // LED OFF
}


There are two types of bluetooth devices for Arduino. Some are "slave" only and some are both "master or slave".

There is little difference in price so you should buy one that is master or slave.

This page (HC-05) describes one that appears to be commonly used but there are many and I do not have a recommendation. Some devices are in the form of small boards which connect to the pins on the Arduino (normally serial tx/rx) and some are shields that plug onto an Arduino. The article also shows the connection.

This appears to be an ODBII bluetooth arduino forum thread that uses bluetooth and ODBII. Video

By default Android is in bluetooth master mode. This article appears to show the Android programming required to enable a bluetooth slave.


Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15    (a.k.a. ~/.arduino15) and re-install 1.6.10.


Closely related to To know the state of USB (Serial) connection (connected or not connected)

I would not be using Serial.readString() personally. How do you know where the string starts and ends? Just check for three "A" in a row.

Like this:

const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds
const byte LED = 7;

void setup ()
{
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");
  pinMode (LED, OUTPUT);
}  // end of setup

unsigned long lastMessage;
unsigned int countOfA;

void processInput ()
{
  while (Serial.available ())
  {
    char c = Serial.read ();
    if (c == 'A')
      countOfA++;
    else
      countOfA = 0;
    // do something with the data
  }  // end of while loop
}  // end of processInput

void loop ()
{
  if (Serial.available ())
  {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
  }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
  {
    countOfA = 0;
  }

  // warn if no keepalive received
  if (countOfA >= 3)
    digitalWrite(LED, LOW);
  else
    digitalWrite(LED, HIGH);

}  // end of loop

Note that this will fail (ie. it will light the LED) if it gets something other than "A" which would include newlines, etc.

What it does it count the number of times it gets the letter "A". If it gets something else it resets the count. If 10 seconds elapse without receiving something, the count resets.


Emergency stop button for arduino mega code and circuit attached

The best option is to convert the delay() based code to a millis() based state machine. That way the code will never block and always be going through the loop and the place where you check wether that button was hit.

Then when that button is hit you transition to the E_STOP state which turns off all motors until the restart button is hit which goes to recalibrate the position if needed.

A more quick and dirty solution is to replace every every delay with

unsigned long current = millis();
while(milis() - current < delay){
    if(E_Stop()){
        stopped = true;
        return;
    }
}

And add a if check to bail out to every loop.

 for (/*...*/)
  {
    //...
    delayMicroseconds(50);
    if(E_Stop()){
        stopped = true;
        return;
    }
  }

At the start of loop() you then add a

if(stopped){
    //check for restart signal if true recalibrate otherwise return
}


Do they make 2.54mm 2P Crimpable Micro JST Female connectors?

I've found this product listing on Amazon:

2.54mm spacing JST extension cable.

It resembles the connector you've shown only slightly, but may be the only option out there.

And to contest the above statement, one that looks more like your objective:

Another 2.54mm spacing JST cable

There may be others. I used "jst 2.54 mm 2 pin female cable" as the search terms specifically in Amazon, other sources may have similar results.

Firing up the old Google again, using the last set of search terms, I've found an eBay listing:

eBay product listing

with the source in china. The photo appears correct, although the listing is for two cables, one male, one female, there is a third photo with the circuit board mount type connector.

This particular listing calls them a 2.5 mm connector, close enough? Perhaps a translation error.


No, there isn't - you have to do it manually. And don't forget to flush.

You could inherit HardwareSerial if you really wanted - or just write a couple of functions to do the sending and controlling of the DE pin.


This is how I would write this loop:

for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
{
  JsonObject row = *it;

  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):

for (auto row : root)
{
  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}


Figuring out some numbers for a mini pump

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

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

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


It looks like your main problem is the loop in setup():

for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);

This will call pinMode() with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to i<=9.

However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely must have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.


You can just have a variable that remembers whether the alarm is
supposed to be on or off. Let's call it alarm_on. Then:

bool alarm_on;
static void start_alarm() { alarm_on = true; }
static void  stop_alarm() { noTone(); alarm_on = false; }

void loop()
{
    if (alarm_on) alarm();
    if (some_condition()) start_alarm();
    if (some_other_condition()) stop_alarm();
}

For a better approach that allows you to sound the alarm without
blocking the whole program, see the Blink Without Delay Arduino
tutorial.

Edit: I just wrote (but did not test) a non-blocking version of this
alarm, based on a state machine and the timing technique from the Blink
Without Delay tutorial. Here it is, as a class:

class TwoToneAlarm {
public:
    static const uint16_t HIGH_FREQ = 3300;
    static const uint16_t LOW_FREQ  = 3000;
    static const uint16_t TONE_DURATION = 200;

    TwoToneAlarm(uint8_t output_pin)
    : state(OFF), pin(output_pin) {}

    // Start the alarm.
    void start()
    {
        tone(pin, HIGH_FREQ);
        state = HIGH_TONE;
        last_tone_change = millis();
    }

    // Stop the alarm.
    void stop()
    {
        noTone(pin);
        state = OFF;
    }

    // Call this periodically to handle the tone changes.
    void update()
    {
        if (state == OFF) return;
        if (millis() - last_tone_change >= TONE_DURATION) {
            switch (state) {
                case HIGH_TONE:
                    tone(pin, LOW_FREQ);
                    state = LOW_TONE;
                    break;
                case LOW_TONE:
                    tone(pin, HIGH_FREQ);
                    state = HIGH_TONE;
                    break;
                default:
                    break;
            }
            last_tone_change += TONE_DURATION;
        }
    }

private:
    enum { OFF, HIGH_TONE, LOW_TONE } state;
    uint16_t last_tone_change;
    uint8_t pin;
};

It could be used like this:

TwoToneAlarm alarm(8);

void loop()
{
    if (some_scary_condition()) alarm.start();
    if (some_other_condition()) alarm.stop();
    alarm.update();
}

Note that the whole program must be non-blocking (delay()-free),
otherwise the tone changes will not be done on time.

Edit: more about being non-blocking.

There is normally no reason for you to use delay() at all in your
program. The only reason for this function to exist is to help complete
beginners write their first blink-the-LED program. As soon as you start
writing anything non trivial, you should ban it from your vocabulary.
The Blink Without Delay tutorial is here precisely to teach you how to
get rid of delay() by using millis().

In this particular case, however, the drawback of delay() may not be
too severe: if the alarm is sounding and you delay a tone change, you
may hear it as a glitch that breaks the rhythm of the sound. If the
delay is short enough, maybe up to 10 ms or so, you are unlikely to
notice it. Longer delays will be noticeable, and it's up to you to
decide whether you find them annoying or not.

It is possible to ensure a very steady rhythm despite the delays by
using interrupts, but this will cost you your 16-bit timer. Or you could
write your own implementation of tone() that does both the pin
toggling and the tone changes using a single timer. Any such option will
require you to learn about low-level timer
programming, which is significantly
more demanding than learning to use millis().


You could have used SoftwareSerial instead of AltSoftSerial.Since you are using AltSoftSerial please go through its library file to check how you need to deal with it.
For Software Serial you need to use predefined Rx , Tx pins of Arduino rather than defining any other pins of it for Rx,Tx
for connecting those to Rx Tx of tempterature sensor.
For GPS try to define any 2 pins of Arduino as Rx Tx so that you can connect them to Rx Tx of GPS.Hope this helps you.


Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?

I installed a library from within the IDE as StarCat suggested.

https://github.com/Makuna/Rtc

#include <FastLED.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

ThreeWire myWire(3,4,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

CRGB leds[NUM_LEDS];

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

void loop() {
   RtcDateTime dt = Rtc.GetDateTime();

   for (int i=0; i<NUM_LEDS;i++) {
     leds[i] = CRGB::Red;
   }

FastLED.show();
delay(100);
}

I am able to get and use the time, and the LED output works.


How to measure water turbidity with arduino

http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886
is a good one according to http://forum.arduino.cc/index.php?topic=299993.0

But it might be easier to buy a COTS sensor, its a bit more expensive but much easier.  http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_9868_10005_10006_10034_10021_507_10022_10020_1000020_10018_10019,searchweb201603_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509

BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)


Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible

For me, it's extremely hard to tell if you did or did not fry a device.
Even if you have the device right in front of you, it's often hard to tell.

You've got two options:

Attempt to diagnose it

First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.

If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.

Buy a new one

This will cost you some money. But if you get the new one working, you can test the same code on your old one.

Tips

First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
Check the devices datasheets (which pins, what maximal voltage)
Try to use female connectors as power-output. (They don't short everything they touch)
Try to use irreversible connectors.
Don't have loose leads dangling around.
Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.


The IDE runs a "preprocessing" routine. As well as adding prototypes it also:

Adds #include <Arduino.h> to the start of your sketch
Removes comments (or the older versions did, I am not sure about arduino-builder)
Identifies the libraries #included in the sketch

The latter is used to build the list of -I ... directories to add to the command line. Removing of comments was chiefly to make finding functions easier for making function prototypes (though there are better ways of doing both those and arduino-builder might use them).

Can you disable it? No. Not for .ino files. However, any .cpp files added to your project are treated as vanilla C++ source code and aren't preprocessed in this way.


If you want to output preset voltage levels in distinct steps, rather than an 'analogue' range from X volts to Y volts, then the answer is in the datasheet for the LM317:

Connect each of the INPUTS through a 1k base resistor to your Arduino pins. Selecting different values for all the resistors will of course allow you to vary Vout by turning each transistor on or off, by themselves or together. You can use any standard transistor: 2N3904, 2N2222, BC548, etc., but I might elect to use a (low power) MOSFET like a BSS138 instead (and omit the base resistor). Of course you can use add more resistor/transistor lines if you want more output options. I recommend using R2 so that Vout is always limited, otherwise - if Vin is quite high - you may damage whatever Vout is powering due to some runaway voltages.

Calculating resitor values is your mathmatical challenge. If you really apply some brainpower you can change Vout in linear steps with minimal Arduino pin usage:

'Input' states            Vout
  A  B  C  D            (/volts)
  0  0  0  0              5.00  [Vmax set by R2]
  0  0  0  1              4.75
  0  0  1  0              4.50
  0  0  1  1              4.25
  0  1  0  0              4.00
   ...  ...                ..
  1  1  1  0              1.75
  1  1  1  1              1.50

This shows that with N Arduino pins you can have (N^2)-1 levels. Using R2 gives your final level whne all INPUTs are off.

If you want to be able to drop Vout down to 1.25V, add transistor/MOSFET that connects R1/ADJ straight to ground. Turning this on will drop Vout to 1.25V, irrespective of the state of the other INPUTS.


The simple way would be to format the string with sprintf - however sprintf on the Arduino lacks floating point support (although it is possible to enable it).

So if you convert your floating point numbers into strings first (remember to provide room for the NULL terminating character!) you can then use sprintf to format those converted numbers into what you want:

float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[5];
dtostrf(a, 4, 1, a_string);

char b_string[5];
dtostrf(b, 4, 1, b_string);

char out[12];

snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);

%4s is replaced by a string which is padded to at least 4 characters wide. The padding is to the left of the string. If you want the padding to the right you can use %-4s instead.

Addendum:

In your new posted code you are making a fundamental error:

char out[12];
snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
return out;

out is a local variable to the function. Its memory is allocated on the stack. You fill that with data and then return the address of that location on the stack. As soon as you leave the function that memory allocation is lost. Yes, the data is still there, but the moment you call another function that memory gets overwritten with the call frame of the new function you have called - thus corrupting your data.

You have two main options:

Make out global
Make out static

The effect of the two options is pretty much the same, except that in the second option the scope of out is restricted to the function which means you can use the name out elsewhere without it conflicting. In both options though the memory allocated to out is in the BSS not the stack and thus won't get overwritten.


AT command is not responding on serial monitor

The ESP's AT firmware is probably configured for a higher baud rate, 115200 is typical. SoftwareSerial only works reliably up to 9600 baud. It can transmit "reliably enough" at 115200 for you to blindly send change-baud commands, though the ESP's response will probably be garbled. So you need to either: Reduce the ESP's baud rate or use the Uno's hardware serial port for the ESP, which means giving up the Uno's terminal output and makes it a pain to reconnect your PC each time you need to update the Uno's code. I've described the process of changing the ESP's baud-rate in more detail in
this answer.

Update: I'm not familiar with various AT comand-interpreter revs; my ESPs are all running with the firmware rev came on them; "AT+GMR" (show version info) replies:

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

There is no AT+CIOBAUD command listed in my ESP8266 AT Instruction Set document rev 1.5.3). The only one listed that affects baud rate - and the one I  use - is:

AT+UART_DEF=<baud>,<databits>,<stopbits>,<parity>,<flowcontrol>

, or:

AT+UART_DEF=9600,8,1,0,0

for 9600 baud, 8 bits, 1 stop-bit, no parity, no flow control. You probably know, but just in case, note that you will lose communication immediately after you change the ESP's baud rate, until you then change the local baud rate to match.

Update2:

  This is program pastebin.com/dquCNYJj I am not sure what wrong I am
  doing

That code sets SoftwareSerial to 115200 baud; it can not run fast enough to receive data at that speed.

Update 3:

Since you've updated the ESP's firmware unsuccessfully, it's hard or impossible to know what's going on. The output in your screenshot looks rather like the result of a baud mismatch between the ESP and your terminal. You need to get a clean firmware update to the ESP before you can expect it to respond correctly and rely on its output to diagnose any other problems.

Update 4:

I'm not sure if we're talking about the same thing so please forgive me if you already know this; we might be talking about (at least) three different baud-rates:

The rate in use during flashing of new firmware to the ESP;
The default rate that new firmware will start listening at, whenever it is booted;
The actual rate used at any given time between the ESP with its new firmware and the Arduino or some other device external to the ESP.

My own experience is with using the factory-installed AT Interpreter firmware. I have never needed to update it so I don't have personal experience with (1).

(2) and (3) are programmable by the Arduino. When I first use a new ESP (or after you've just re-flashed its AT Interpreter), it will listen at a factory-default baud rate (mine have all defaulted to 115200). There are commands to change the current rate (not saved across a reboot) and/or the default baud (saved for all future sessions).

I almost always change its default rate to 9600 to use it with an Arduino software serial port. This is my initialization for a new device, using an Arduino to talk to the ESP. (Don't transmit my '#...' comments):

# Start talking at the ESP's default rate (115200 on my factory-fresh ones).
AT+RST                         # Reset
AT+UART_DEF=9600,8,1,0,0       # Default baud to 9600,N,8,1,no flow ctl
# Here, change the Arduino's port to match: 9600 in this case.
AT+CWMODE=1                    # Station mode (client)
ATE0                           # Command echo off

From now on, the ESP will wake up listening at 9600 baud, in Station Mode as a client, with no command echo.


I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."

The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.

When you build your sketch, there is a .hex file created that you can send to your client.

There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:

Sketch > Export Compiled Binary
The sketch will compile.

Sketch > Show Sketch Folder
The .hex file will be in the sketch folder.

You can send this hex file to your customer.

If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support import of hex files at this time.

Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.

If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.


Purposely create compile error to fail the upload

To answer the question asked in the title:

#if some_condition
# error Some error message
#endif

But note that this technique only works at compile time, which
probably makes it useless for you.


Let us do this with a template class and avoid malloc, etc.

#define membersof(x) (sizeof(x) / sizeof(x[0]))

const byte dataPins[] = { A5, A4 };

class B {
public:
  byte getPin() { return (_pin); }
  void setPin(byte pin) { _pin = pin; }
private:
  byte _pin;
};

template<unsigned len>
class A {
public:
  A(const byte sensorPins[]) {
    for (unsigned i = 0; i < len; i++)
      _vec[i].setPin(sensorPins[i]);
  }
  unsigned getLen() { return (len); }
  B* getB(unsigned ix) { return (ix < len ? &_vec[ix] : NULL); }

private:
  B _vec[len];
};

void setup() {
  Serial.begin(115200);
  A<membersof(dataPins)> test(dataPins);
  unsigned len = test.getLen();
  Serial.print(F("test.getLen()="));
  Serial.println(len);
  for (unsigned i = 0; i < len; i++) {
    B* bp = test.getB(i);
    Serial.print(F("test::B["));
    Serial.print(i);
    Serial.print(F("].getPin()="));
    Serial.println(bp->getPin());
  }
}

void loop() {
}

Cheers!


Problem with a seven segment display. The segments blink then turn off

The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with).

To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments.

I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.


Module that can both detect Voltage (12V) and Control current

You don't need another module to detect voltage on an Arduino.  The UNO, which I assume you are using, has 6 analog inputs (A0-A5) that can directly read voltage.  The only problem is that you want to measure a voltage up to 12V and the Arduino can only handle 5V.  So the solution is to DIVIDE that using two resistors in a voltage-divider configuration so that you only see 5V at the Arduino when there is 12V on the signal.
From here: https://www.electroniclinic.com/what-is-a-voltage-divider-or-potential-divider-formula-and-practical-uses/
you can see how to make one:

As far as controlling a "current" that is usually done with a relay.  There are no on-board relays but there are the digital outputs that can drive a small relay or can be connected via some other circuitry like a couple of transistors to drive just about any size relay.


Arduino Joystick Library not Recognized by Games (Steam)

There is an Arduino Xbox 360 (XInput) library. But I do not use Steam so I have
no idea if this works.
https://github.com/dmadison/ArduinoXInput


How can I make ultrasonic sensors resistent to splashes and dirt?

I don't think you'll be able to cover that sensor in a way that will still allow it to work. There are waterproof ultrasonic sensors out there, here's one on Amazon, for example.

The other thing you might want to look at is IR instead of ultrasonic. That's easier to weatherproof since the IR emitter/receiver are already covered. You'll probably have less range with IR, though.


Use constructor Adafruit_ILI9341(10, 9, 8); to make the reset that works with software SPI.

To SD card as second device on the bus:

Every SPI device on SPI bus must be controlled by slave select pin. If a device is connected to the bus and the SS pin is left floating the device disturbs the bus.

The empty SD card adapter is not a device on the bus, only the inserted card is a device. If it is on the bus the corresponding SS pin must be set HIGH. If you use the SD libray SD.begin(SD_SS_PIN), the library initializes the pin. If you don't use the library in the sketch (because it takes much memory), remove the SD card or set the SS pin to OUTPUT and HIGH.


Does Serial.read() ever return a character?

On an 8 bit arduino a character is a byte.  A byte can represent values between -128 and 127, or between 0 and 255, depending on how you "look" at them (signed or unsigned).

The whole concept of a character is a purely human thing. The Arduino only knows numbers.

For instance the character 'A' is actually the number 65. We, as humans, choose to represent it as an 'A' and call it "ASCII".

Again, the character 'a' is actually the number 97. You can also subtract characters from each other.  'a' - 'A' = 32


SAMD21 Programming with Atmel ICE Fail to Write

Whats is the fuse setting of NVMCTRL_BOOTPROT?

it should be:

NVMCTRL_BOOTPROT = 0x07

which will set your memory location to 0x00 (no bootloader).

NVMCTRL_BOOTPROT sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.


How to override automatic control in Blynk app?

Roughly like this:
Make a global variable int mode;
Read a Blynk app 3-way switch in the loop();
Set mode to the 1, 2 or 3 received from the Blynk app (for ON/OFF/AUTO);
Replace this bit of code:
if (waterTemp < 16) {
  digitalWrite(RELAY_PIN, HIGH); //turn on IoT relay
} else {
  digitalWrite(RELAY_PIN, LOW);  //turn off IoT relay
}

with
if (mode == 1) {
  digitalWrite(RELAY_PIN, HIGH);
} else if (mode = 2) {
  digitalWrite(RELAY_PIN, LOW);
} else {
  if (waterTemp < 16) {
    digitalWrite(RELAY_PIN, HIGH); //turn on IoT relay
  } else {
    digitalWrite(RELAY_PIN, LOW);  //turn off IoT relay
  }
}

You will still have to decide what happens when DEVICE_DISCONNECTED_C == TRUE, etc, but that is the gist of it.


Void value not ignored as it ought to be

Something changed while you were looking away. This is the updated description of read(). As you can see, it not longer returns a bool.
Use available to determine if packets are available:

/**
   * Read the available payload
   *
   * The size of data read is the fixed payload size, see getPayloadSize()
   *
   * @note I specifically chose 'void*' as a data type to make it easier
   * for beginners to use.  No casting needed.
   *
   * @note No longer boolean. Use available to determine if packets are
   * available. Interrupt flags are now cleared during reads instead of
   * when calling available().
   *
   * @param buf Pointer to a buffer where the data should be written
   * @param len Maximum number of bytes to read into the buffer
   *
   * @code
   * if(radio.available()){
   *   radio.read(&data,sizeof(data));
   * }
void read( void* buf, uint8_t len );


The Arduino Mega doesn't support USB-host, so you can't connect a USB stick directly.

The easiest way is to connect it to a computer, and send the data over the serial connection.


1) How exactly do they work (connection wise)?

Physically they all sit on the GPIO sockets of the Pi, sitting on top of the pi. The Gertduino and AlaMode seem to have the same form factor as the Pi which makes them a little more appealing to me but I guess then is personal choice.

Communication appears to differ but it will use Serial, SPI or I2C. I would imagine that you'd be able to choose an alternate one but not read enough about them to know for sure. Serial appears to be fairly simple, and it would be easy to debug, however you might struggle if you wanted to receive data on the Pi without the communication being initiated by the Pi.  I2C would overcome this as you can run it in multi-master mode.

  2) is it possible to write one python code in the raspberry pi that
  when run can load the specific ino code into arduino?

As you can call external programs with python I would say that even if you have to resort to this mechanism then it would be possible. You can turn on the debugging in the Arduino IDE to see what it actually does, then either script it or make the calls from your python program.

  3) which bridge would be the most suited for my project? (eg:
  Arduberry, alamode, gertduino, etc?)

I'd go for either the gertduino or alamode purely on looks particularly the matched form factor.


How to boil down analog input to just three cases?

The simplest fix to your problem is to change the map() call to

byte alrmSet = map(alrmSwState, 0, 1024, 0, 3);

In the call above, the mapped intervals are of the semi-open type, e.g.
[a, b), where the start values (namely 0) are understood as being
inclusive and the end values (1024 and 3) are exclusive.

Although not clear from the documentation, this is the proper way to use
the map() function. Otherwise, the truncated division gives you very
uneven intervals. Compare:

     x       map(x, 0, 1023, 0, 2)
----------------------------------
   0 –  511     0
 512 – 1022     1
1023            2

     x       map(x, 0, 1024, 0, 3)
----------------------------------
   0 –  341     0
 342 –  682     1
 683 – 1023     2

The result you get is very close to Jeff Wahaus’ answer.

What I find annoying about this approach is that a 32-bit integer
division, which map() uses internally, is a very expensive operation
on the small 8-bit Arduinos. If instead of 342 and 683, you use 256 and
768 as thresholds, then you can make the decision by just looking at the
high byte of the analog reading:

uint16_t alrmSwState = analogRead(alarmSwitchPin);

alrmSet = alrmSwState / 256;

if (alrmSet != alrmPrevSet) {
    switch (alrmSet) {
        case 0:
            Serial.println("Low");
            break;
        case 1:
        case 2:
            Serial.println("Medium");
            break;
        case 3:
            Serial.println("High");
            break;
    }
    alrmPrevSet = alrmSet;
    delay(200);
}

Note that the division by 256 is optimized by the compiler into a much
cheaper bit shift, but this is the case only if alrmSwState is of an
unsigned integer type. That's why it is declared above as uint16_t.


Can you connect BH1790GLC and TMP117 sensors to an Arduino board?

Yes, the sensors will work with microcontroller(s). What you look for is the interface they use. In this case it is I2C interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

Choose 3V powered microcontroller
Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


Programmatically-adjustable buck converter module?

The hack you described is most likely just feeding voltage from filtered PWM signal generated by microcontroller to the feedback loop of LM2596. I think you can get good enough noise performance with this approach if voltage change rate is not a concern. It all comes down to the PWM filter parameters. You can decrease noise by adjusting RC filter parameters (increasing capacitor and resistor values). It will cause increased delay in voltage change, but it will reduce the noise from PWM signal. Also, you can increase the PWM frequency by avoiding standard analogWrite which has pretty low frequency and configuring a separate timer for PWM generation.
Alternatively, if you need some specific voltages, you can replace the potentiometer with a fixed value resistor array connected in parallel and connect each resistor though separate low power MOSFET. This way, you can connect and disconnect a specific resistor which will change the total resistance of the array, changing the output voltage. It will only allow changing voltage by steps and the step size is dictated by the number of resistors, but the noise performance will be the same as using a potentiometer.


How do I view Serial Output on an Android Device?

These steps will allow your Android device to function as an Arduino Terminal.

Download a Serial Terminal app.  I'm using Android Hyperterminal, English version.
Attach an OTG ("On The Go") cable to your Android device.
Attach your Arduino to the OTG using your regular USB cable.
Make sure the terminal program is set to the same baud rate as your sketch.
Run the terminal App and select the USB port.


I get an error saying, "exit status 1 expected initializer before 'void'."

Functions must have a body. So instead of:
void setup()

You need:
void setup()
  {
  // do nothing
  }

You have other issues, for example this is not C++:
  int (n,i,j,result);

That should be:
  int n,i,j,result;

Also you are returning 0, when void functions don't return a value.
Also, here:
  printf("enter N Value");

  scanf ("%d", &n);

Where is this value coming from? There isn't a keyboard on the Arduino.
See: scanf

The C library function int scanf(const char *format, ...) reads formatted input from stdin.

The Arduino is a microprocessor. It doesn't have stdin.


What you want to implement is described in Blink Without Delay.  Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has.  In the mean time, you can check on other things and do those in the mean time.


Try with this address 0x3F or 0x27

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // or 0x27
void setup() {
lcd.begin(16, 2);
}
void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}


character on 16X2 LCD is not visible properly

Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.


HTTP POST from Arduino/ESP8266/ESP32 How to send parameters (x-www-form-urlencoded)

What format of message does the server expect? As you send "x-www-form-urlencoded" it should probably look like:

 "from=+XXXXX&to=+XXXXX&message=Hej"

where the different parts are

 "param1=paramValue1&param2=paramValue2&param3=paramValue3"

 param .... Name of the expected parameter
 = .... divides the param pair
 paramValue .... Content/value of the parameter
 & .... links the param pairs

so in your case

 int httpCode = http.POST("from=+XXXXX&to=+XXXXX&message=Hej");


What happens if there is a runtime error?

First, let's see a few examples of what can go wrong.

Uninitialized local variables

void setup() {
  int status;
  pinMode(13, OUTPUT);
  digitalWrite(13, status);
}

As pointed out by Edgar Bonet in the comments, local variables like status in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.

Things are a bit different with global and static variables:

  Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?

That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.

Memory overflow

int array[10];
int v = array[100];
array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of array.

Jump to an illegal instruction

void doSomething( void ) {
    for (int i = 0; i < 1000; i++);
}

void setup ()
{
    void (*funcPtr)( void );

    funcPtr = &doSomething;
    funcPtr(); // calls doSomething();

    funcPtr = NULL;
    funcPtr(); // undefined behavior
}

The first call to funcPtr() will actually be a call to doSomething(). Calls like the second one may lead to undefined behavior.

Other bad things that may happen

Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.

Kinds of Protection

In computer systems, problems like these are usually dealt with at various levels:

By the compiler
By the programming language runtime (as in Java for example).
By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.

The Answers

The assumptions are the all of the problems I stated above are runtime problems.

  What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

  Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's highly unlikely).

  Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.

The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).


Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: arduino.cc - tone().

noTone() Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated. Source: arduino.cc - noTone()