ModemConfig * config is a pointer to a ModemConfig struct.

You need to create a ModemConfig struct, populate it then pass a pointer to it in the call to the setModemConfig() function.

Something like this:

// create the struct
ModemConfig mc = ModemConfig();

... //populate the struct values

// then call the function
setModemConfig(&mc);

The datarate is the rate at which you are sending information over the radio channel (not between the MCU and the Si4463).

The bandwidth is the range of frequencies used in the radio transmission (e.g. in FSK if a low/0 is 99.95MHz and a high/1 is 100.05Mhz then the bandwidth would be 100Khz)


Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?

No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.

Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.


Multiplication, division. What is wrong?

300

and

1000

are integers.

What

long V2 = (300 * 1000)/30000;

really does is take the integers 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.


The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding

Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:

client.print(
  String("GET ") + url + " HTTP/1.0\r\n" +
  "Host: " + host + "\r\n" +
  "Connection: close\r\n\r\n"
);

Dunno why it worked for one API but not the other though.


Android, Raspberry, Atmega, SQL communication

If I understand correctly:

You have a Pi hosting MySQL and a web server.
A Mega writes temp/humidity data to the server.
An android device reads data from the web server.
The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go?
What you have is a tried an tested design, a central server responsible for collating at serving the data.  My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that.  What happens if you want to add a second Mega to report a different sensor?  You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more.  I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.

You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.

But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.


There are a few ways of doing what you want.  One would be to use an analog multiplexer as in this answer: Expanding analog inputs to the Arduino

Another would be to use digital I/O pins to control the power and ground to the potentiometers.  Note that both sides of the pot need to be controlled, not just one, since any connection of one will interfere with the other.

So you will need four IO pins - one for the +5v and one for the GND of each potentiometer.

In this example set D3 to OUTPUT and HIGH, D4 to OUTPUT and LOW, and D5 and D6 both to INPUT.  You will now be reading from the top pot.

Then change D3 and D4 to both be INPUT, and D5 to be OUTPUT and HIGH and D6 to be OUTPUT and LOW.  You will then be reading from the bottom pot.

A bit wasteful of IO pins though.


Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega

There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your project is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet here
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):

and find proper pin and corresponding register from ATmega2560 datasheet.
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:

and

You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)


Why is my SRAM so quickly filled? There are not more than 60 bytes

When you are asking yourself what is eating so much RAM, the first step
is to look at the symbol table in the ELF file. If you use a makefile, you
probably know where to find the ELF file. If you are using the Arduino
IDE, go to File / Preferences, check “Show verbose output during
compilation”, compile and look at the output: you will see the temporary
directory where the compiler puts your ELF file.

Now run the command avr-nm -Crtd --size-sort your_elf_file and look
for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either
upper or lower case. On a Unix-style OS you would pipe through
grep -i ' [dbv] '. Running this on your program gives:

00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000021 B lcd
00000016 V vtable for HardwareSerial
00000008 V vtable for LiquidCrystal
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 D __malloc_margin
00000002 D __malloc_heap_start
00000002 D __malloc_heap_end
00000002 B __flp
00000002 B __brkval
00000001 b timer0_fract
00000001 D encr
00000001 B debug
00000001 B EEPROM

Obviously, this cannot account for the 1,023 bytes of static RAM your
program is using. What this command misses is the literal arrays and
strings. These can be seen with the command
avr-objdump -j .data -s your_elf_file. The literal strings are quite
obvious in the output, the literal arrays less so. Running this on your
program gives a long listing starting with

Contents of section .data:
800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
800110 0a060c05 09000700 0f07040e 020d010a  ................

Now, on the source code we see:

const uint8_t SBoxes[8][4][16] PROGMEM = {
{{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
 { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
 { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
 {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
 ...

If you translate this to hexadecimal, you get 0e 04 0d 01 02 0f...,
which appears also by the end of the first line of previous listing. So
there is your culprit: all the big PROGMEM arrays. The compiler does not
honor the PROGMEM attribute on local variables.

My first thought was to make the arrays global, and this does solve the
problem. However, as pointed out by Mikael Patel in a comment, the
documentation on PROGMEM states that “variables must be either globally
defined, OR defined with the static keyword, in order to work with
PROGMEM.” Then, making the arrays static const PROGMEM is a cleaner
solution.


DS3231 rtc.begin() always returning false

No fault is there in code. Rather, it was an faulty connection which prevented RTC module from working. Now, after restoration, the RTC module is working fine.


Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?

If so, you did not write any "select this led" code, so it can't work.

I fixed a couple of things in your code. Mainly:

added the circularity to the ring (with variable currentlyOnLed)
fixed some types (use the byte unless you need a bigger type)
removed some constrains, which were reduntant
frequency*interval instead of frequency/interval (I guess it was a typo)
I prefer summing the step instead of setting previousMillis to currentMillis, so you will not add error with time passing
moved FastLED.show() outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.

So, here is the fixed code. Let us know if it works for you

#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure;
int high  = 0;
int low   = 600;
byte barometricToRGB;
int frequency = 0;
byte interval = 50;
byte currentlyOnLed;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(115200);
    pinMode(SENSOR_PIN,INPUT);
    FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    currentlyOnLed = 0;
}

void loop() {
    airPressure = analogRead(SENSOR_PIN);
    autoTune();

    unsigned long currentMillis = millis();
    Serial.print("frequency ");
    Serial.println(frequency);
    Serial.print("Time to beat ");
    Serial.println(frequency*interval);
    Serial.print("Last Called ");
    Serial.println(currentMillis - previousMillis);

    if(currentMillis - previousMillis > (frequency*interval)) {
        previousMillis += (frequency*interval);

        //Set next on led
        if (currentlyOnLed >= NUM_LEDS - 1)
            currentlyOnLed = 0;
        else
            currentlyOnLed++;

        for (byte i=0; i<NUM_LEDS; i++) {
            if (i == currentlyOnLed)
                leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
            else
                leds[i] = CRGB::Black;
        }
        FastLED.show();
    }
}

void autoTune() {
    airPressure = constrain(airPressure, low, high);
    barometricToRGB = map(airPressure, low, high, 1, 255);
    frequency = map(airPressure, low, high, 1, 100);
}


Yes, it is perfectly do-able through the serial monitor.  However the serial monitor is very very basic and you will be able to create a much better user experience using a proper serial terminal emulator (such as TeraTerm, Putty, etc) and using ANSI control codes to lay the screen out as a proper text-based application.

A useful resource is on Wikipedia: https://en.wikipedia.org/wiki/ANSI_escape_code

I have a little library that I started a while back and never finished that performs two basic ANSI control sequences - clear screen and set cursor. You can look at it to see how to perform ANSI control codes: https://github.com/MajenkoLibraries/ANSI


What is the output of Software Serial .read() function

It is just like https://www.arduino.cc/en/Serial/Read :

The monitor.find("OK"); already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive monitor.read()s, then zero more bytes in monitor.available().


Incompatible types in assignment of 'uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]}'

atoi is for converting a textual representation of a number ("123" for example) into an actual integer.

The c_str() function gives you a pointer to the internal buffer of the String (assuming you actually have a String) which is no different to a uint8_t[] or uint8_t * (other than the signedness).

Without knowing exactly what the destination function for this buffer requires it's very hard to help you, but you may want something like:

LoRaWan.send((uint8_t *)myString.c_str(), myString.length());

If you need to copy the data into a fixed length buffer then you need to first create a buffer of that actual size - then copy the string data into it:

// Create a buffer of 32 bytes
uint8_t myBuffer[32];
// Copy at most 32 bytes, but no more than there actually is, into the buffer
memcpy(myBuffer, myString.c_str(), min(myString.length(), 32));


Can we use analog input pins as a parameter of analogWrite() for PWM?

On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable.
If you try to analogWrite() to any other pin, you will get either
0 V (if you write any value less than 128) or 5 V (for any
other value).

If you get 3.7 V when 5 V is expected, that's because either
your power supply is too weak, or you are putting too a heavy load on
the pin.


Can Digital/Analogue pins double as power supplies?

Only for very light loads (a few mA).

But why would you want to? The number of power pins doesn't dictate the number of devices you can power. Power pins can have as many things connected to one pin as you like. As long as you stay within the board's total power budget you are fine.


Can I run two function in arduino simultaneously?

You can imagine a program as a procedure that a CPU executes, reading and doing step by step.
When you compile any program, the compiler checks it, and when it finds some error it can tell you exactly where (the line) in which you made this error.
It can be done simply because the program is a series of commands.
Also if, in some cases (interrups, callbacks, asynchronous functions etc.), it seems to be different, the code is always executed step by step, like when you follow a recipe when you're cooking.
You don't have to worry about that, in fact these steps are done by the CPU very quickly and you can do many things as they would be done seemingly simultaneously.
The Arduino Uno (Atmega328) works at 16Mhz.
As you can read here: "an almost empty loop() is seen about 150k times a second".
So don't worry about the simultaneity of your functions.
You can write a function for detecting the earthquake that calls other functions (like alarms, procedures, etc.) without much time lapse (the best logic I think is: first check the event, then do stuffs).
The only thing I suggest you do is to reduce the code to let it become as small (and fast) as possible, but we are talking about a few milliseconds of lapse from earthquake to alarm.
If you need to register the exact time of the earthquake (absolute precision) you can use the micros() command.
In this case remember to do that as the first instruction (to reduce delay, of course).


Specific values not showing when using a numeric keypad

A row against a row does not work, or a column against a colum.
That means there is a logical explanation. Row #2 is swapped with column #2.
Button 5 does work, because that still has a row against a column (but then the other way around).


Clearing string buffer with memset after a serial read

Instead of clearing your buffers, make use of the bytesRead property.  Have a look at how they print the received string in the example code from the library using a for loop.  I don't know that it is null terminated or anything.

Example from the library's github page:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }


Most coders would your while (1 < Wire.available()) { write as while ( Wire.available() > 1) { and read it "repeat while there is more the 1 byte available". but wait, why leave that one byte there? you want "repeat while there is no more byte available".

you need while (0 < Wire.available())


How to connect a simple wall switch to arduino GPIO

jose can u c is absolutely right, you need a pullup. No need to change your wiring however: the Arduino has built-in pullups on all the inputs. You just have to activate them:

const uint8_t buttonPin = A0;  // or any other pin for that matter

void setup()
{
    pinMode(buttonPin, INPUT_PULLUP);
}


How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals

It is not perfect for your simpler task, but here is a link to a sketch that I have used to record pulses, using the Timer1 Input Capture.

In short setup the Interrupt

void initTimer(void) {

  // Input Capture setup
  // ICNC1: Enable Input Capture Noise Canceler
  // ICES1: =1 for trigger on rising edge
  // CS10: =1 set prescaler to 1x system clock (F_CPU)
  TCCR1A = 0;
  TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
  TCCR1C = 0;

  //catchFallingEdge(); // initialize to catch
  { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

  // Interrupt setup
  // ICIE1: Input capture
  // TOIE1: Timer1 overflow
  TIFR1 = (1<<ICF1) | (1<<TOV1);        // clear pending
  TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

  // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
  pinMode(8, INPUT);
  digitalWrite(8, 0);       // leave floating to count 60 Hz etc.
  //digitalWrite(8, 1);         // or enable the pullup
}

Then service it

ISR(TIMER1_CAPT_vect) {
  union twobyte {
    uint32_t word;
    uint8_t  byte[2];
  } timevalue;

  timevalue.byte[0] = ICR1L;        // grab captured timer value
  timevalue.byte[1] = ICR1H;        // grab captured timer value

  // watch for the other edge to catch the half-pulse width
  //rising ? catchFallingEdge() : catchRisingEdge();
  if (rising) {
    TCCR1B &= ~(1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 0;
  }
  else {
    TCCR1B |= (1<<ICES1);
    TIFR1 |= (1<<ICF1);
    rising = 1;
  }
}


Code to use an Arduino Mega 2560 to transfer UART  USB to debug an other Microcontroller

A very simple sketch to pass serial through looks like this:

void setup(){
  Serial1.begin(/*BAUD*/);
  Serial2.begin(/*BAUD*/);
}

void loop(){
  if(Serial1.available()){
    Serial2.print((char)Serial1.read());
  }
  if(Serial2.available()){
    Serial1.print((char)Serial2.read());
  }
}

I would advise both run at the same baud rate, otherwise you may need to do some extra buffering yourself if the arduino starts running out of buffer space. If you want to use the mega's USB connection instead of "Serial1" like your schematic, just switch "Serial1" to "Serial"


ESP-01 not waking correctly up after deep sleep

Pretty sure you will need gpio 16 connected to reset in order for this to ever work, it’s tricky but not impossible. Have a read here:

https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/


How time intensive or how long can an ISR be?

How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

  would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.

That includes things that rely on other interrupts to function, such as serial communications, millis() and delay(), etc. That means using such functions from within your interrupt handler is a big no-go.

It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.


Have you tried Atmel Studio? Right now, it only supports Windows but is a great alternative to Arduino IDE.

If you're not comfortable using Windows virtual machine, I suggest you have a look at this: http://playground.arduino.cc/code/eclipse


High frequency audio sampling and storage

After doing some reading here Serial.begin(): Why not always use 28800? and looking at the manual for the 168. You should be able to achieve the baud rate you want by directly programming the USAR.

According to the answer there you should be able to use miniterm to keep up with a high baud rate.

As stated there you might run into problems with computer power.

Read chapter 20 here http://www.atmel.com/images/doc2545.pdf.

Basically you can set up the USART speed (UDR0) and the control registers (UCSR0A,UCSR0B and UCSR0C) such that you can send data pretty fast.

Let me know if you can't access that link and if you need me to explain some more about these things.


The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?

When your Nano board is 5V, you need a SD module with a level shifter for the signals.

To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.


Sending GPS data to computer via USB and then to iPhone app through Wi-Fi on LAN

So the Arduino gets the data over serial from the GPS and passes it over serial or USB serial port to the PC.

PC is either configured to be a WiFi hub or is connected over Ethernet to a WiFi hotspot.

The PC runs a TCP server with software so that any data from the Arduino is passed to any connected clients.

The iPhone connects to the WiFi and opens a TCP socket to the server on the PC. The PC can then stream the data to the phone as it comes in (and you can pass data the other way if you need to). If the PC has a static IP address then it's a little simpler for to tell the phone where to connect to.

If you can find a TCP server program for the PC which sends data entered from the keyboard (there are plenty around) then you could cheat and configure the Arduino to pretend to be a USB keyboard rather than a serial port. That way the PC software is completely off the shelf.

At some point you'll need to parse the GPS output (NMEA at a guess) to extract the time, location, and anything else you want. This could be done at any point in the chain, wherever you feel most confident writing and debugging code is probably the best place to put it.


Timer 2 interrupt with ATmega328p and make measurement in ISR

Well let's start from the start ...

Analog readings

  to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

Serial.print(digitalRead(1));

That is not reading analog pin A1, it is reading digital pin 1. If you want to read A1 you need:

Serial.print(analogRead(1));

Check the time

By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.

Example:

void setup()
{
  Serial.begin(115200);
}  // end of setup

unsigned long lastReading;
const unsigned long INTERVAL = 100;  // ms

void loop()
{

  // is time up?
  if (millis () - lastReading >= INTERVAL)
    {
    lastReading = millis ();  // when we took this reading
    Serial.print(analogRead(1));
    Serial.print(" ");
    Serial.print(analogRead(2));
    Serial.print(" ");
    Serial.print(analogRead(3));
    Serial.print(" ");
    Serial.print(analogRead(4));
    Serial.print(" ");
    Serial.print(analogRead(5));
    Serial.println();
    }  // end of if time up

  // do other things here

}  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

Using timers

If you really want to use timers (and I don't see what they achieve here) I have a page about timers that describes using them, and interrupts, in some depth.

The very least you would need is a timer 2 "compare A" interrupt like this:

ISR (TIMER2_COMPA_vect)
  {
  // Timer 2 has reached its comparison value
  }


Flash firmware with hex file over serial with Python (no avrdude, Arduino IDE)

This isn't the exact answer but it helps.
Uploading without avrdude is complicated and generally slow. The best solution to not using the IDE is to open and close a port then use the avrdude command that the ide usually uses.
from serial import Serial
from time import sleep
from subprocess import run

while input('Press enter to upload ') == '':
    Serial('COM5',baudrate=1200).close()
    sleep(1)
    run(["C:\\Progra~2\\Arduino\\hardware\\tools\\avr/bin/avrdude", "-CC:\\Progra~2\\Arduino\\hardware\\tools\\avr/etc/avrdude.conf", "-v", "-patmega32u4", "-cavr109", "-PCOM6", "-b57600", "-D", "-Uflash:w:C:\\Users\\USER\\Desktop\\Python\\tclab_v2/tclab_v2.ino.hex:i"])


The big circular parts likely is ultrasonic transducer as used in instant camera.

http://www.uoxray.uoregon.edu/polamod/

https://www.google.com/?gws_rd=ssl#q=polaroid+ultrasonic+ranging+module&revid=399558007&safe=off

Working principle is same as modern unit, easily available at a few US dollars. The transducer does NOT work by itself, needs the associate PCB to work.


'Delay command' and bluetooth communication problem

I see 2 problems with your code:

You use the delay() function, which is not good coding style, since it is basically busy waiting. The Arduino will do nothing in this time, also not reacting to any input. Instead you should use a non-blocking coding style, which only does something, when it is time to do so, and will not block until something happens. You can see this style in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as a time measure. Think of how you would bake a pizza. You would not sit on front of the oven doing nothing, until the pizza is ready. You would do other things while looking at your watch regularily, checking, if it is time to take out the pizza.
In the Serial communication part you use parseInt(). That can be a problem, since it has a timeout of 1s (standard value). Until the timeout the function will block. This is mitigated, if you consecently send a non-digit character at the end of every value. But it is better to first read a full message (until the newline character \n) and then process the message as a whole.

Also the line if (bluetooth.available()) is not necessary here, since the while loop will do the same.


Once you have purchased a USB vendor ID you can edit the firmware within the Arduino installation at hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/ with your vendor ID, chosen product ID, and other USB parameters as you wish and then rebuild the firmware and upload it to the ATmega16U2 on the board via ISP.

If you do not wish to purchase a vendor ID for the time being then you can use 0x6666, the prototype vendor ID, in the meantime, but you are not allowed to make products using that vendor ID available to the public.


Arduino digital pin input used to power device?

Arduino get the power from the port of 6502 via the protecting diod in the Arduino port. This the normal behavior.
// Mikael


First upload the msg errors you've get .
Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding.
I recommend you to use millis  instead of delays and use  multitasking code like freertos .


Unable to read the Serial Port through Arduino the way Serial Port Monitor softwares read it

It's not a good idea to use pins 0 and 1 for SoftwareSerial they are usually connected to Serial


A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.

Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.

Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.

A 7805 has a high dropout voltage and is out of place in a battery powered system.


Transmitting sketches to Yun with Autobahn - a byte at a time?

Partial answer: to send more information than just a single byte, it is possible to run:

# python
payload = "Here is a longer string"

# arduino
String commands = port->readString();           // Reads the whole thing
String commands = port->readStringUntil('\n');  // Reads until the given separator


No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).

A voice recognition chip generally is pre-programmed to respond to specific words.


I have arrived at a solution that works for me. Instead of using Adafruit library I have adopted Sparkfuns library.

Some adjustments in the setup for the pins:

#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno
#define SD_CS           4   // Chip select for SD card

Then some adjustemnt in the block for the HTTP request:

client.print("GET /index.html HTTP/1.1\r\n");
client.print("Host: ");
client.print(server);
client.print("\r\n\r\n");
client.println();
Serial.println();

This is not a solution for the Adafruit libary. But it helped me to continue my project.


'dynamic_cast' not permitted with -fno-rtti

It seems avr-gcc version 4.9.2 that is used by the Arduino IDE has been compiled without RTTI support. It defaults to -fno-rtti, and if you try turning it on with -frtti you just get other horrible linker error messages instead.

So it looks like you can't use dynamic_cast on AVR boards.

Googling around it looks like numerous people have tried to enable FTTI on Arduino, but they have either failed and given up, or they have succeeded and never bothered to tell anyone else how they did it (numerous forum posts of "how do you do this?", a bit of discussion, and then they tail off...)

The solution? Either don't use RTTI, or use a more capable microcontroller whose compiler has RTTI enabled.

One way to not use RTTI is to fake it yourself:

#define CLASS_A 1
#define CLASS_B 2

class A {
    public:
        virtual int classType() { return CLASS_A; }
};

class B : public A {
    public:
        virtual int classType() { return CLASS_B; }
        void bar() {
            Serial.println("Baaaah!");
        }
};

void foo(A *foo) {
    if (foo->classType() == CLASS_B) {
        B *foob = (B *)foo;
        foob->bar();
    } else {
        Serial.println("Sorry, I can't bar.");
    }
}

void setup() {
    Serial.begin(115200);
    A a;
    B b;
    foo(&a);
    foo(&b);
}

void loop() {
}

Output:

Sorry, I can't bar.
Baaaah!


Help understanding circuit for button example

The connection in that picture is pointless.  They are just putting power and ground on the top set of rails, but they aren't using it.

Your breadboard has only one rail on either side.  So you'll have to designate one for power and one for ground and you'll need some slightly longer wires for some of the connections.


I don't know of any way to compile it on an iPad, but Textastic should do the trick for writing the code if you set the syntax highlighting to C++.


Getting Accurate Velocity Readings From IMU

The process of integrating acceleration to derive velocity and integrating velocity to derive position are commonly known as dead reckoning.  In this link it is stated:

Dead reckoning is subject to cumulative errors. Advances in
navigational aids that give accurate information on position, in
particular satellite navigation using the Global Positioning System,
have made simple dead reckoning by humans obsolete for most purposes.

It may help to calibrate each of the 3 accelerometers using Earth's gravity as a constant.  Test if each accelerometer is symmetrical providing the same absolute values when pointed toward the Earth as when pointed away from the Earth. If any are not symmetric calculate an appropriate offset.  Next compare the range of each of the 3 accelerometers.  If they are not the same calculate an appropriate magnitude correction factor for maximum and minimum accelerometer ranges.
To find the offset and range correction values look at page 26 of the BNO055 specification sheet.  There you will find a picture of the BNO055 chip which relates to the direction of the X, Y and Z accelerometers.  Position the chip such that the X accelerometer is pointed downwards toward the earth.  Record the raw value.  Now repeat the measurement with the X accelerometer pointing away from the earth.  The absolute value of these two measurements should be the same.  If not, determine the offset needed to correct X accelerometer measurements and incorporate that value into your program.  Repeat this for the Y and Z vectors.
Now compare the maximum - minimum values for the X, Y and Z accelerometers.  These 3 values should be the same.  If not, find a value to multiply the smallest of the three such that it matches the middle value and incorporate that value into your program. Repeat this for the largest of the three values.
It is desired all 3 accelerometers work the same.  If they do not, using the values derived above should adjust the raw values such as the result appears as 3 nearly identical accelerometers.
That said, most accelerometers are very usable with no correction factors.  And it is expected any correction factors to be small.  However, as experienced, when integrating, small errors can accumulate quickly.
Next consider the application in which dead reckoning is to be used.  There may be clues as to the velocity at a given moment which, if used, can reset the assumed velocity to a known value.  For example, if the accelerometer were attached to a runner's foot, it can be assumed the velocity is zero for each foot to ground impact detected.


Addressing contents of array using incrementing variable

Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.

However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.

BUT the array isn't in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong.  You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".

PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but they're not the same room.

So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:

     Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at v addresses on from the start of the COLSA array in PROGMEM.


Serial structure data transfer between an Arduino and a Linux PC

The following solution isn't strictly portable, but it should work as long as both ends are little-endian (most platforms).

You can use the GCC attribute packed to tell the compiler not to pad the fields like this:

struct __attribute__ ((packed)) my_struct {
  char c;
  int32_t n;
};

Then you can send your struct like this:

Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use Python over C/C++ you can use the struct module to unserialize the data.

I just googled your product and the MIPS processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if ints keep their value after transmit. Also remember to use explicit size types such as int16_t, uint64_t, etc.


Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be HUGE.  So, "No!" is the answer.

You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?


Why doesn't the LED turn on in this circuit?

Because you don't actually have a circuit?  One side of the LED doesn't connect to anything.


You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ).
To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik.
ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)


Uno with LCD acting strangely - power issue?

System resets can be caused by power droop and by noise at the Reset pin, among other reasons.  The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.

The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question.  With all four relays on, and coils drawing 50 mA each, that's 200 mA.  LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.

However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.

When relays switch, they typically produce an electrical noise pulse.  If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc.  Using a separate power supply for +5 V to the board also should help.

Wiring issues include ground bounce and ground loops.  If you are using a breadboard, there may be poor ground or power connections.  Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.


How does Arduino determine whether the given condition provided to it is true or false?

In general terms comparisons are usually performed, at the low level of assembly language, using subtraction.

In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag.

If you are comparing A to B then you subtract B from A and see what happened by examining the flags.

For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call.

If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call.

If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed (a > b is the same as !(a <= b) for instance).

Of course, some architectures have actual comparison instructions (often CMP) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions:

CPSE - Compare, Skip if Equal
CP - Compare
CPC - Compare with Carry
CPI - Compare Register with Immediate

CPI would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value):

CPI $r3, 50

According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match:

BRLT - Branch if the result of the previous comparison was A < B
BRLE - Branch if the result of the previous comparison was A <= B
BRGT - Branch if the result of the previous comparison was A > B
BRGE - Branch if the result of the previous comparison was A >= B
BREQ - Branch if the result of the previous comparison was A == B
BRNE - Branch if the result of the previous comparison was A != B

There are more as well for other special comparisons.  You can read up all about them in the AVR instruction set manual.


Depending of the type of fan you are using, two solutions exist.

First one, use a MOSFET to drive the FAN from you nodemcu
Second one, use a relay to drive the FAN from your nodemcu

Things to consider :

The mosfet allow you to drive the fan without mechanical part moving.
The relay require some transistor and feedback diode to be driven by your µc.


How to power up this LCD 7 segments display

that's a controller-less dynamic (mutiplexed) display, with 4 coms.

So you will to program the mcu to do a lot:

1) the com pins are driven with 1/4 dc signal sequentially;

2) the seg pins are driven with 1/3 bias voltage. out-of-phase to be dark and in-phase to be transparent (not lit).

the way to do it is to:

put segment info in a buffer;
write a display update routine that scans digits and updates the com/seg pins according to the current digit's segment information;
call that display update routine periodically, preferrably from a timer isr.

the display update routine would be similar to an led display routine - an example of that (for led) would be here (https://dannyelectronics.wordpress.com/2017/06/30/a-more-flexible-driver-for-7-segment-leds/), but more complex due to the 4 com pins and bias generation.

it is much easier to pick a mcu with built-in lcd driver and program that mcu as a display controller / slave taking in information from a master (in this case your arduino).


Seeeduino V3.0 (Atmega 328P) and Rotary Angle Sensor Mystery Message

One problem is that you try to generate serial output before you initiate Serial.  This could have odd results beyond just making that message fail.

Serial.println("Setup Start...");
Serial.begin(9600);

Should be

Serial.begin(9600);
Serial.println("Setup Start...");

And of course your posted code never reads the sensor...


What variables to declare for controlling a motor with high power motor controller

Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.

It's the numbers you assign to the variables and, more importantly, what you do with those variables that is important.

Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.


How to get separate BPM readings from two pulse sensors using one Arduino

Change "#define USE_ARDUINO_INTERRUPTS true" to "#define USE_ARDUINO_INTERRUPTS false".

If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
#define USE_ARDUINO_INTERRUPTS false
#include <PulseSensorPlayground.h>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h


How to build a high-frequency (>20kHz) driver for LEDs?

Just change the timer prescaler to a lower value.

E.g. timer2 (PWM pins 3 and 11) has the prescaler set to clock/64 and runs at around 500Hz. So changing it to clock/8 will result in 4kHz. (Sorry, no clock/16 available).

TCCR2 &= ~_BV(CS22);//clear CS22 bit
TCCR2 |= _BV(CS21);//set CS21 bit


How to change input pin of FreqCounter Arduino Uno/Dumilanove library?

The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.

It can't be changed.  You have no choice in that.

You will have to move the LCD to another pin instead.


Here's what I came up with:

You have a certain percent of the gain cycle equal one "step" (step may be a bad term in this situation, but I'm using it because of stepper motors).
You have a blocking function that will move the motors and control all the P(ID) logic

Before this function is called, the main code will use a variable to store the desired time to do the next "step."
It will have a loop with "substeps." So it would look kinda like this:

void function nextStep(int var1, int var2) {
    //Read sensors and put into variables
    until(condition == true) { //Condition to see if the motors are at the right degree
        //Adjust motors not in the right place
        delayAndCheckBT(10); //Look at the bottom for this function
    }
}

You could also have it accept a few percent of variance as tolerance so it's not shakey, but that's more of the PID control than anything. You'll have to make sure that many 'steps' doesn't make the PID controller unstable.

When that code is done, the main function will check to see if the desired time for the next step has passed (or if it's now). If it's passed/now, then it will execute. Otherwise, it will not execute the next step and continue executing the main loop.

Great? No. The problem is you need to check for bluetooth! To do this, I've made two functions:

void checkBT() {
    //Checks BT. Make sure this is non blocking: if you need to, set a few global variables
    //Note this code will get called a LOT, so don't implement any delays or loops: inside here: use millis().
}
void delayAndCheckBT(int timeToWait) {
    unsigned long finishTime = millis() + timeToWait;
    while (millis()<finishTime) {
        checkBT();
    }
}


Benchmarking String.toInt() vs Checking individual characters gives unexpected result

As pointed out by Majenko in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using toInt(), for example, try:

// time our conversion
unsigned long start = micros();
unsigned long rInt = r.toInt();
bool invalid = rInt == 0;
unsigned long end = micros();

// print the result
if (invalid) {
    Serial.print("in");
}
Serial.print("valid conversion took ");
Serial.print(end - start);
Serial.print(" microseconds.");

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; "003" and "-17" are both three-character inputs that should be correctly converted.

According to the toInt() documentation, 0 is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of "0" and unsuccessful conversion of "abc" or some other non-integer, you really should be sure before you call toInt() that you've got a valid integer int the string.


Interfacing Gammon's RS485 with computer

Open-source and Web-search is just great. This might be what you are looking for.

Cheers!


The OpenLogger was designed to be paired with and Arduino Pro or Arduino Pro Mini and just log the serial output from one of those. You could theoretically use the OpenLogger itself to do the sensor reading and writing, however, the I2C pins that your sensor needs haven't been broken out on the OpenLogger.

This means if you really wanted to make this happen, you would have to hand solder those pins and break them out yourself. After that the process is pretty straightforward. SparkFun provides both the source code and directions on programming it.

If trying to break those out is a little too tricky, you can either pair it with one of those Arduino models and use it to read the data, or find another similar logger device that has more pins broken out.

Two answer the second part of your question, reading multiple sensors isn't a problem. Usually the way these sensors work is you send a request for data to them and they return the reading, so you would just request from the first sensor, request from the second sensor, write out to the file.

You can write to two different files no problem eiteher. I would not however, recommend writing to two different files. Switching from one file to another, back and forth introduces a little extra overhead which will slow down your loop. In rocketry, things happen very fast, and you'll probably want keep your loop running as fast as possible. I would recommend just writing to a single file and include data from both sensors probably something along the lines of time,accelX,accelY,accelZ,bar.


Going from one shift register to two shift registers

It sounds like the primary issue is how you've connected the two shift registers.  You just need the bit shifting out of the first one to shift into the second one so they act, together, as one longer shift register.

The example pictured is described in full here, under the heading "Example 2":
http://arduino.cc/en/tutorial/ShiftOut

As Klaus mentioned, you want to first ShiftOut the byte you intend to wind up in the second resister, then ShiftOut the byte for the first register.  This will push your first byte through to the second register.


Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328

Thanks for your answers!
Jot gave the solution: wADC must be a uint16_t.

Here is the corrected code :

void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println(readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint16_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}


Detect if a 3 phase AC submersible pump is on

It's likely that the power to the motor is originating at a panel with breakers. You should be able to confirm that only one breaker set is being used to power the pump motor. At that location, all the wires are separated.

If you do not have the necessary skill to identify the correct wires, consider to consult an electrician. It is advisable to remove power to the panel before you begin to insert your fingers to wrap the sensor wire around the correct lead.


how to push data from an Arduino pin to Bluetooth module

The HC-05 looks like like any other terminal to the Arduino so any serial operations that you would use for a wired terminal can be used with the HC-05. See the HC-05's manual for how to set it up initially. Note that HC-05s don't forget their settings and they have no reset command to put them into a known state, so write down your settings for your future reference.

- Read the analog pin value;
- Convert the value into whatever physical units you require;
- Print the result with Serial.print() or Serial.println()

Edit:  You wrote that your HC-05 is connected to Digital 0 and 1, but you created your SoftwareSerial, mySerial, to transmit on Digital 11. In that case your HC-05's receive pin must be connected to Digital 11.


What you are talking about in this instance is "Open Drain".  Normally, as you rightly note, with outputs you have either HIGH or LOW, which effectively connects the output pin to +5V or GND respectively.

Instead you are asking for Open Drain.  In this arrangement a pin is either "active", in which case it connects it to GND, or "inactive", in which case it is disconnected from (almost) anything.

Most 8-bit Arduino boards don't have Open Drain capability on their IO pins (some more advanced 32-bit boards do, though), but it is easy enough to emulate it in software.

You can emulate it using "Tri-State" logic.  That is logic where, as well as HIGH and LOW you have "High Impedance", or "HI-Z".  HI-Z is pretty much the same as "inactive" Open Drain. On the Arduino HI-Z is the same as INPUT.

So you can emulate it by:

To activate a pin set it to OUTPUT and LOW
To deactivate a pin set it to INPUT

For example, to "press" one of your buttons for 100ms you could:

pinMode(4, OUTPUT);
digitalWrite(4, LOW);
delay(100);
pinMode(4, INPUT);


Replace all:

case '0xZZZZZZZZ':

with:

case 0xZZZZZZZZ:

That's because value in decode_results structure is declared as unsigned long, 0xZZZZZZZZ is an unsigned long, but '0xZZZZZZZZ' is not (actually, it should not even compile).


Cheap medium range wireless communication with a linux PC

Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.

You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.

Another wireless option that I have no personal experience with is NRF2401 modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.

Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi.  For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.


Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.

The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.

One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.

This is how I'd probably write it:

void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
{
    // Guard against division by zero
    if (numSteps == 0) numSteps = 1;

    // Calculate how how much each colour needs to change on each step
    const float
        stepR = (newR - oldR) / (float)numSteps,
        stepG = (newG - oldG) / (float)numSteps,
        stepB = (newB - oldB) / (float)numSteps;

    // These values will store our colours on the way along
    float r = oldR, g = oldG, b = oldB;
    uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

    // Go through each fade step
    const uint16_t numPixels = strip.numPixels();
    for (uint32_t step = 0; step < numSteps; ++step) {
        // Move one step towards the target colour
        r += stepR;
        g += stepG;
        b += stepB;

        // Round the colours to integers here so we don't have to do it repeatedly in the loop below
        byteR = (uint8_t)(r + 0.5f);
        byteG = (uint8_t)(g + 0.5f);
        byteB = (uint8_t)(b + 0.5f);

        // Apply the colour to each pixel
        for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
            strip.setPixelColor(pixel, byteR, byteG, byteB);
        }

        strip.show();
        delay(waitPerStep);
    }
}

As you can see, you pass it the old colour (which you're fading from) and the new colour (which you're fading to). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.

I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.

To use this, you'd do something like this:

// Fade from black to red and pause briefly
fade(0, 0, 0,  255, 0, 0,  100, 10);
delay(500);

// Fade from red to purple and pause briefly
fade(255, 0, 0,   255, 0, 255,  100, 10);
delay(500);

// Fade from purple to green and pause briefly
fade(255, 0, 255,  0, 255, 0,  100, 10);
delay(500);

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.

I've also modified the wait parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.

In my example above, you can see the 100, 10 parameters at the end of each call to fade(). That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).


Change Servo Speed With RedBearLabs BLE Shield

The bi-directional Parallax High Speed Continuous Rotation Servo responds to “simple pulse-width modulation”, according to its web page.  That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.

The code in the BLEControllerSketch uses the following bits of code, among others, to initialize servo-control data structures and to control them:

#include <Servo.h>
...
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
...
      case 'O': // set Servo
        {
          byte pin = ble_read();
          byte value = ble_read();

          if (IS_PIN_SERVO(pin))
            servos[PIN_TO_SERVO(pin)].write(value);
          pin_servo[pin] = value;
          reportPinServoData(pin);
        }
        break;

Thus, you will need to send an O message from your iOS app, together with servo pin number and control value, to set a servo's speed.

As noted on the ServoWrite page at arduino.cc, the parameter to Servo's .write() method is a number:

  On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's .write() method in Servo.cpp:

void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

SERVO_MIN() and SERVO_MAX() are macros that access min and max fields in a Servo object and convert them to microsecond values.  Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).

Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees.  The .write() method will interpret such numbers as microseconds instead of as degrees.  Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.

In short, it appears that you should do some experimenting with O messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.


The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.

The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.

Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.

Just connect OUT+ to 5V and you are done.


In file included from led.c:3:0:
  /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
  optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add -Os to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

  avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

  avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

-F tells avrdude to not verify the device signature. -V tells it
to not verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. -c arduino is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the -D option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:

avrdude: erasing chip
avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:

avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf


The problem with your code is your using delay(). This is a function
that should most of the time be avoided for one simple reason: when the
Arduino is executing the delay() instruction, it does nothing but
wait. This means, among other things, that it cannot be reactive to user
input. As outlined by ARK in his answer, interrupts could be used to
overcome this problem. But you actually do not need them: the standard
way to avoid delays is to use instead the millis() function to control
timings. This approach is well described in the Blink without
delay Arduino
tutorial.

Here is how you can apply this technique to your alarm() function: In
a nutshell, you can think of delay() to be roughly equivalent to this:

void naiveDelay(uint32_t ms)
{
    uint32_t start = millis();
    while (millis() - start < ms) {
        // do nothing
    }
}

The problem here is the “do nothing” part. You do not want your program
to do nothing, you want it to monitor the “alarm stop” button. So the
simple solution to your problem is to replace delay() by the code
above, and then change it so that it monitors the button instead of
doing nothing. Then you get something like this:

void alarm()
{
    for (int count = 0; count < 5; count++) {

        // start the buzzer
        digitalWrite(buzz, HIGH);

        // first delay
        uint32_t start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                digitalWrite(buzz, LOW);  // stop the buzzer
                return;
            }
        }

        // stop the buzzer
        digitalWrite(buzz, LOW);

        // second delay
        start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                return;  // buzzer already off
            }
        }
    }
}


Command through Serial monitor does not properly work in Arduino

The root of your problem seems to be not knowing what Serial.flush() does.

It pre-Arduino 1.0.0 times Serial.flush() used to clear any data in the serial's RX buffer. It would throw it away.  In your code that would throw away the line ending \r\n that is sent along with the command.

However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer.  This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.

This change was not widely documented, but it is mentioned in the manual:

  Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with Serial.flush() acting like it does in current versions, you would get a different string the second time around.  You would see:

SHOW$
\r\nSHOW$
\r\nSHOW$

and so on.

You have come up with a "fix", which uses String::trim() to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings.  However it would be far better to ignore them in the first place and not need to do the trimming.

The simplest way would be to only add characters to your string if they are printable:

if (inChar == '$') {
 Serial.println(" Received String :");
 Serial.print(strReq);
 if (strReq.equalsIgnoreCase("SHOW"))
   showData();
 Serial.flush();
 strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
  strReq = strReq + inChar;
}

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.


Strange behavior on 74HC595 Shift Register IC when its GND pin is used

Disconnecting the ground pin was not a solution.

It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands.  They are 100?

Look closely at the driver data sheet.  It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.

For example, a red LED has a of around 1.6 V.  You are using Vcc=3.3, so a 100 ohm resistor limits the current to <17 mA ((3.3-1.6)/100).  The actual current will be a somewhat smaller as the Vf increases with current..

But you also stay within the maximum Icc and Ignd on the data sheet.  These limits are not necessarily 8 x 35 mA.  For example an NXP max Icc is 70 mA.  That means you cannot drive all the outputs at maximum current, just 2.  This is a logic chip, not a driver.

There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described.  The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.

A common LED current is 5 mA, so this chip could drive 8 simultaneously.  If you want high brightness, you need to add a driver such as ULN2003.

Note that the schematic shows red LED's.  The color is important.  Different LED's have different forward voltage.  The blue LED have the highest in the range of 3.3 V and higher.  So with a Vcc=3.3 there is barely enough voltage to light the blue LED.  The red and yellow have much lower forward voltage.  When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.

From the video, it looks that you have the same resistor on all the LED's.  On different color LED's this will not achieve the same brightness on all LED's.  You need different resistors for each color if you want them the same brightness.

The solution is

Up the Vcc to 5V so that you can reliably light the blue LED's.
Increase the resistor values start with 510 for red and 220 for blue.  This should be about 6 mA for both.


3,6V DC motor spinning with L298N and Arduino

The L239 is a terrible motor driver. It's the kind of motor driver Noah used to control The Ark.

It requires a power supply that is at least 2.5V more than the "logic input high" voltage, which is rated at 2.3V. That means an absolute minimum of 4.8V, which is borderline for the Arduino's 5V pin, especially if you are running off USB (which can drop as low as 4.75V and still be within specification) and way out when powered from the battery.  It's really designed for driving motors in the 12V+ range.

To drive a low voltage motor like yours you need to pick a more modern MOSFET based motor driver.


How do I change pin assignments for the LUFA AVRISPMkII?

I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX_LINE_MASK to change the pin. Thanks to everyone who helped!


The WiFi libraries (such as Wifi.h, WifiClient.h, and WiFiServer.h) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. Serial.write(), etc.)


Serial communIcation from OS X app to Arduino Mega

One problem is here:

  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    }

Your Serial.available() call guarantees that you have one byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.

How to process incoming serial data without blocking


SMlib State Machine Library not working as expected

Maybe you need some sort of debouncing? There's a tutorial on the Arduino site that I think will sort your problem out.


Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.

Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

(search for "5 pin DIN female jack")

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.


How to prevent shoot-through when swiching a motor with a bridge?

You only get this kind of problem when you are manually controlling the high- and low-side switches manually.  Bridge chips seldom make you do that and include the logic and drive circuitry within them so that you just control a HIGH or LOW to a "leg" and it switches the two transistors properly for you.

You normally get an "enable" and a "direction" input.

For instance, take the L298 internal circuit:

If we look at the left-most transistor pair you can see they are driven by a pair of gates. One has an inversion on the input.  The gates are mainly there to AND the enable signal in, but the inversion on the upper input of the lower gate is the vital thing. That makes sure that one transistor is on when another is off. You can't turn both on, or both off - you only have a single signal that indicates which should be on.

Of course, that circuit is very simplified, and there is additional circuitry that ensures that during the switching period one transistor switches off before the other switches on.  Matched transistors with known switching characteristics, adding offsets to the base voltages with diodes, etc are all methods that are used internally.

With MOSFET based bridges it's less of an issue since gate threshold (VGS) come into play and choosing and matching the transistors correctly automatically creates a "dead zone" in the switching input voltage range.


Millisecond timestamp (13 digits) in Arduino

18446744073709551615
That 20 digits. It is the maximum value of a uint64_t. Even the Arduino Uno can use the uint64_t. Perhaps the Serial.print does not support it, but the compiler supports it.

Which processor does your RFduino have ?

Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a xy-problem.


Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?

NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.


Waking an ESP8266 from Light-Sleep using a signal from MQTT?

I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.

The best you can hope for is a periodic wakeup to connect to the server and check for any new data.  But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.


You must have your microcontroller in place if you are uploading code to it.

You can talk to ESP8266 via serial monitor because you are connected directly to the pins of your USB-UART bridge.

Place your uC back, change this line of code:

SoftwareSerial ESP8266(0, 1);

to this one:

SoftwareSerial ESP8266(8, 9);

and change your wires accordingly(what was on pin 0, now connect to pin 8, pin 1 to pin 9).
Now your Atmega can talk to ESP8266 after you upload the code.

btw. "Serial2" is Serial port for more advance Arduino boards, it won't work on Atmega328 based board.


Arduino digitalWrite 1 or 0 instead of HIGH or LOW

Yes, that is fine.  LOW is 0 and HIGH is 1.  digitalWrite() sets the output to off if it receives a 0 and on if it receives anything of 1 or more.

That means that these are all equivalent:

digitalWrite(pin, HIGH);
digitalWrite(pin, 1);
digitalWrite(pin, 69);

It's especially useful when you are examining a variable for, say, a certain bit being set:

digitalWrite(pin, bytevar & 0x80);

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.


Combined code and nothing works. Head scratcher for sure

DateTime now = rtc.now();
Does not belong above void setup()
4hours to troubleshoot this little mistake.


How to calculating requirements of power supply for a project

A power supply a 9V battery is not. Since you are using batteries the L293D is a very poor choice for a driver, it uses silicon transistors which I believe are in a darlington configuration which will cause a voltage drop of from 1.4 to 2.8 volt on the motor.  The 4 (or more) AA batteries will work but use a MOSFET bridge. You can always use a small SEPIC (Buck/Boost) converter to power it, that will keep the voltage constant until the batteries are exhausted. Set it to about 9V and power the arduino via the VIN input for more filtering. You will need a way of measuring voltage. You will lose less power with the converter then you are losing in your current driver.


convert 32 bit long to 4 bytes and back again - CAN Bus

The union type is similar to a struct except that each of the members of the element occupy the same memory. If you define a struct so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.

union packed_long {
  long l;
  byte b[4];
};

This is the type, so you have to declare the variable to be of that type:

packed_long mydata;

Now, you have two sub-elements of mydata: l and b[].

To save your long value, write to the l part:

mydata.l = myaccel.getY();

To access each of the 4 bytes:

byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];

On the receiving end, you take each of the 4 bytes:

mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();

As long as you receive the bytes in the same order in which you sent them, you can now access your long value in mydata.l.

The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: int32_t (signed 32-bit integer) or uint32_t (unsigned 32-bit integer).


not getting proper bitstream output in serial monitor using digitalRead

Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the level of the wave, not the transitions from one level to another.

For instance:

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.

Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input changes should you look to see what the new level is and print that.

As you can see the 1 and 0 are just after the change in level, since it's impossible to do anything during a change, only once the change has happened.

You might code that as something like:

void setup() {
    Serial.begin(115200);
    pinMode(3, INPUT);
}

void loop() {
    static byte oldValue = LOW;     // Place to store the previous level
    byte newValue = digitalRead(3); // Read the current level
    if (newValue != oldValue) {     // The input has changed
        oldValue = newValue;        // Save the current level
        Serial.print(newValue);     // Print it.
    }
}


How to program a Arduino Nano(Bricked) with a working arduino nano

I have a page about programming a bootloader using another Arduino.

Basically you grab the code from here and then make up wiring from the good device (which you put the sketch onto) to the device to be programmed, like this:

Arduino Nano        Target Nano

D10 (SS)            Reset
D11 (MOSI)          D11
D12 (MISO)          D12
D13 (SCK)           D13

Gnd                 Gnd
+5V                 +5V


Why do I get negative voltages for a PWM waveform?

At first you had the scope AC (Alternating Current) coupled.  Then you switched it to DC (Direct Current) coupled.

AC coupling is used to remove the DC component of a signal.  It places a large capacitor between the probe and the internal amplifier.  This is used, for instance, if you want to see a small signal with a large DC offset.  But it can also attenuate and / or alter signals that are low in frequency.

When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs.  As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes.  Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.

DC coupling is where there is no coupling capacitor between the probe and the internal amplifier.  Everything comes through.  For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.


You can't just "print" a key like that. You use print for sending text.

When you use println it sends an enter key along with your text, so you can do :

Keyboard.println("ls -al");

and it will send the text ls -al and press enter for you.

If you want to do it in the 'raw' way you will need to press and then release the key:

Keyboard.press(KEY_ENTER);
Keyboard.release(KEY_ENTER);


Difference between WiFiClient and HttpClient

WiFiClient provides a raw connection to the internet through a WiFi access point (such as your home router).

HttpClient provides a connection to a web server via an existing Client connection, such as a WiFiClient connection.

So the simplest answer to your question

  to send HTTP commands to a server (XML/JSON), which one to go for?

is "Use both".

You use WiFiClient to connect to the internet, then you use HttpClient on your WiFiClient connection to communicate with a website.  As it states in the readme on HttpClient's github repository:

  Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with EthernetClient, WiFiClient and GSMClient.

To understand the concept more fully you will first need to understand the OSI 7-Layer Model which is essential reading for anyone doing anything with networking software.


ISP Programmer with Serial and 5v/3.3v power

How about, connecting a tiny battery across the 3.3v output of the Pololu.  Lets assume a 3.7v LiPo, charged to 3.3v.
When the battery is connected at 3.3v, no current will flow.
When my device to be programmed is connected it will draw a spike of current, which will start to take the Pololu below 3.3v, but then the LiPo will start supplying current and stop the Pololu voltage getting dragged down and browning out.
The LiPo will then be slightly below 3.3v, so will get a Constant Voltage charge back to 3.3v.
Two potential issues I can see:

When the Pololu is disconnected from the USB will it be being 'back powered' by the LiPo?

When in CV charge mode, the only current limiting will be internal resistance of the Pololu output / LiPo cell, probably not an issue in practice due to the voltage drop being very small.

I know it is a hack, but thoughts welcomed.
Cheers
Kev


Send data before raising edge of a Clock

It sounds like you have some misconceptions.

In order to work with clocked signals like in SPI, you set your data line(s) to the desired value, and then raise the clock signal from low to high. The receiving device detects the low to high transition and reads the state of the data lines.

If you did it in the other order (switch the clock signal from low to high, then set the data pin(s).) then the receiver would detect the clock rising edge and try to read the data value before it was set correctly.

With a clock line like in your setup, the communication doesn't rely on fixed timing. The clock line tells the receiver when the data is available, and you can use whatever clock timing you want (up to the max speed supported by the hardware.)


find out the pin numbers for the Arduino IDE for a certain board - the esp 32

An Arduino boards package with configuration for your board has constants for pins which correspond to labels on the PCB. The constants are defined in pins_arduino.h file, which is applied only if you choose the corresponding board in Tools menu. In code you should use this constants as values for your constants, like for example const uint8_t LED1_PIN = D2;.

If the boards package doesn't have the board and you use generic settings, the you can study the schematics of the board to see which PCB pin goes to which MCU pin. Usually the logical pin numbers are labeled in schematics additionally to physical pin numbers of the chip.

Note: The linked pins_arduino.h is for FireBeetle ESP32. The Beetle ESP32 is not defined in ESP32 boards package yet.

The schematics is on the Wiki page.


Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.

Look at the LCD rear, you should see your I2C chip, search google typing
["chip's code"  20x4 arduino]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...

Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.

Another way to find the address is to upload this code, it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.

If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.


How to connect new OV7670 FIFO to Arduino?

I recently brought this book off Amazon "Beginning Arduino ov7670 Camera Development".  I'm loathed to recommend it, because it has a nice 80 page introduction to the Arduino and OV7670 and the rest of the 250 pages are just double space annotated code.  That said, it does appear to be a very good introduction, with example code, for a OV7670-FIFO (the title of the book is incorrect).

It might be possible to find the code on the net and then you can decide if you want to buy the book or not.  Oh and I am not Robert Chin, I do not know him and I have nothing to do with the book, other than owning a rather new and once read copy of it.


Trigger countdown with 433MHz transmission

You say The full code includes some differentiation mechanism for all sensors so I'll assume there's some function GetSensorId() that returns 0 to NUM_SENSORS - 1.

So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:

// Assume you never receive 0 from sensor.
const int NO_DATA = 0;
const int NUM_SENSORS = 4;
int sensor_data[NUM_SENSORS];

void setup() {
    // Initialize array
    for (int i = 0; i < NUM_SENSORS; i++) {
        sensor_data[i] = NO_DATA;
    }
}

Also, a variable to keep track of time of last message:

uint32_t last_message_time = 0;

So, in loop():

void loop() {
    // Check for data
    if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        if (value == 0) {
            lcd.clear();
            Serial.print("Unknown encoding");
        }
        else {
           // Determine which sensor sent the data
           int sensor_id = GetSensorId();
           Serial.print(value);
           Serial.print("%");
           // Save the data and the time of the message
           sensor_data[id] = value;
           last_message_time = millis();
       }
    }
    // See if all sensors reported
    byte sensors_reported = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        if (NO_DATA != sensor_data[i]) {
            sensors_reported += 1;
        }
    }

    // When 0 sensors have reported in, do nothing
    if (0 != sensors_reported) {
        // Otherwise, at least one sensor
        // check the time
        uint32_t elapsed = millis() - last_message_time;

        // If have all data or time's up, do something
        if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
            // Do something

            // Reset state
            for (int i = 0; i < NUM_SENSORS; i++) {
                sensor_data[i] = NO_DATA;
            }
        }
    }
}


How can I make FastLED set every 2 LEDs to the same color?

The FastLED community appears to live at this reddit.com site. Consider asking your question there.
It is unknown if the following will exceed the current limitations of the Arduino platform you are using.  But, consider sending the same data to two different strings of LEDs simultaneously.  Briefly, each LED strips off the 1st packet of data and sends the balance of data through to the next LED.  Two different strips should behave the same if given the same data.  Thereby creating the effect you described (pairs of LEDs behaving the same).


Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

Yes. Assuming the "block" can provide enough current.

  Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)

No.

  Is a Power Converter like this for the ESP8266 necessary?

Yes if you are powering it from more than 3.3V.

  Should I use another external Power source for the ESP8266?

Not necessary if the 9V one can provide enough current as I mentioned above.


Photoresistor value drops when board stacked on Arduino Uno

It should not happen.

I have changed this answer, because at first I read that the resulting value was changed by -40, but I think it drops from 900 to 40.

The shield is doing something, so it is not empty. Perhaps it shortcuts the AREF to GND. Perhaps you are reading an open input, and the sensor is at another analog pin. Perhaps the shield does something to the voltage pins.

A breadboard can have bad contacts. The shield can have bad contacts.

Be sure that the sensor is connected to the channel that you are reading. Measure the voltage at that analog input with a multimeter with and without the shield. Check the 5V, 3.3V and AREF pins with and without the shield.


Why Commenting Serial.print() gives me a different value?

Majenko has correctly diagnosed your problem, and the blog post he
linked to is definitely a must-read. The suggested solution, namely
buffering the input until you can read a complete message, is presumably
the most standard way of dealing with an input stream.

It is, however, not the only option. Your idea of building the number
digit by digit can work, if implemented properly, and it can save you
the memory cost of the buffer. The key is to only read bytes when they
are available.

Below is a non-blocking implementation of a number reader that works
along the lines of your own code. This function only reads positive
numbers. It returns the number it just parsed upon reading a non-digit
character. In every other case it returns -1 to tell you there is no
input number available:

// Read an positive integer from a stream.
// Returns -1 if a complete integer is not available.
int readInt(Stream &link)
{
    static bool got_a_digit = false;  // did we get a digit so far?
    static int i = 0;                 // the integer we are building
    if (link.available()) {
        char c = link.read();
        if (isdigit(c)) {
            i = 10 * i + (c - '0');
            got_a_digit = true;
        } else if (got_a_digit) {  // non-digit: return the number
            int i_copy = i;
            got_a_digit = false;   // reset for next reading
            i = 0;                 // ditto
            return i_copy;
        }
    }
    return -1;
}

And here is how you would use it:

void loop() {
    int i = readInt(mySerial);
    if (i != -1)
        Serial.println(i);
}


Adafruit Huzzah ESP8266 Battery Power issue

After tinkering more, I figured out that the Huzzah module is happy to take in up 4.5V via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was over 5V.

That's a little weird considering that in Adafruit's page, it says

  ..to make it easier to power, we put a high-current-capable 3.3V
  voltage regulator on the board. It can take 3.4-6V in but you should
  stick to 4-6V since the ESP8288 has high current usage when WiFi is
  on.

Hope this may help someone else.


The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).

You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.


Arduino Hardware serial library with rts/cts flow control support

I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)

If you take this route, you will have to copy the file
HardwareSerial.cpp from the Arduino core, make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

Wire the 'ready' signal from the device to an interrupt-capable pin of
the Arduino.
Inside the interrupt handler:

when 'ready' is deasserted, disable the UDRE interrupt by issuing
cbi(*_ucsrb, UDRIE0)
when ready is asserted, enable it again, but only if the output
buffer is not empty:
if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);

Patch HardwareSerial::write() to enable the interrupt only if
'ready' is asserted.
Note that the UDRE IRQ can be explicitly called
by HardwareSerial::flush()
and by HardwareSerial::write() if interrupts are globally
disabled. You will have to condition this on the 'ready' signal.
Note also that HardwareSerial::write() can write directly to the
UART if the buffer is empty. This also has to be
conditioned on the 'ready' signal.


How to find out if HX711(amplifier and 24-bit ADC) is damaged or not?

Looking closely at the photo of your setup I can see that you haven't soldered the header to the breakout board. Whilst there are headers available that don't require soldering, and ways of making header connections that don't require soldering, this isn't either of those.
Without solder the connection to the board will be intermittent at best and non-existent in general.


How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval

void loop() {

   ultraSonic();

   if ((distance > 0) && (distance =< 10)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW); // turning LED on
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH); // turning LED off
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}


1)Will adding voltage divider help?

You will need n voltage dividers, one for each solar panel.

  2) What is the limit of Arduino of Voltage Divider?

There is a limit on the equivalent Thévenin resistance of the voltage
source connected to the Arduino analog inputs. It should be no larger
that 10 kΩ, otherwise you risk cross-talk between the channels.

If the solar panels have a low output resistance, then the equivalent
Thévenin resistance is the resistance resulting from setting the two
resistors of the divider in parallel. Setting the smallest resistance
to 10 kΩ will ensure you meet the condition while at the same time
keeping the consumed current quite low.

There is also a limit on the number of solar panels that you can
independently monitor: 16, which is the number of analog inputs on the
Mega.

  [...] each solar panel generate[s] around 300-400 W

The power generated is irrelevant: only the voltage is a concern. Your
dividers must output no more than 5 V.


Arduino sizeof Servo array objects is.. wrong?

What you describe seems to be a common issue that many C or C++ developers can get (or have got) with sizeof.
Take a look at the following code:
char a[3];

int size(char b[]) {
    return sizeof b;
}

void setup() {
    int size1 = sizeof a;
    int size2 = size(a);
}

In that code, size1 will be evaluated, by the compiler, to 3 which is the real size of a variable, whereas size2 will be 2.
Why so?
This is just because sizeof a is evaluated by the compiler, and the compiler knows that a is an array of 3 char; but when a is passed as an argument to function size(), it is converted to a pointer (to the first element of the array), hence its size is the size of a pointer, which is 2 bytes on AVR ATmega MCU.
This subtlety of sizeof may explain strange values as you describe.
How to fix the issue?
Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.
Here is a sample code:
Servo allServos[] = {...};
#define NUM_SERVOS (sizeof(allServos) / sizeof(Servo))
...
void handleServos(Servo *servos, int numServos) {
    for (int i = 0; i < numServos; i++) {
        servos[i].write(...);
        ...
    }
}

void loop() {
    handleServos(allServos, NUM_SERVOS);
}

It is common practice in C to declare an array and immediately after, define its size as above.


There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.


How come people connect their arduinos to buzzers without any coil protection?

That kind of "buzzer" doesn't have a coil.  It is a "Piezo Transducer" and uses a crystal to produce the sound.

When you're using a real speaker and producing sound you are doing it very differently to switching a motor or a relay on and off.  You're generating a much smoother waveform and you don't have the sharp "ON-OFF" that causes a collapse of the magnetic field.  You're actually gradually reducing the power and then reversing it to remove the magnetic field then apply a new one in the opposite direction (if you have wired it right of course).

Also the currents involved in driving a speaker like that are minuscule compared to switching a relay, especially when driven direct from the Arduino.  For louder volumes you will use an amplifier, and that deals with the whole protection within itself since it is designed to drive a speaker.


Arduino Pro Micro TX and RX leds flash quikly while power drawn from VCC pin

Aah, I figured it out! @JeffWahaus was correct, the RC RX was placing too great a strain on the Arduino Pro Micro. My latest working theory is that when the RC RX is in communication with the RC TX, it has current spikes that allow the system current draw to exceed that required to drop the voltage coming out of the 5V regulator below that required to shut off the ATmega32U4 MCU.

The solution I found, upon recommendation, was to move the RC RX voltage source from the VCC pin to the RAW pin which taps power from ahead of the 5V regulator and add a 10uf capacitor in parallel with the RC RX to smooth out any current spikes.

simulate this circuit – Schematic created using CircuitLab