You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.

Radio: Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.

You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.

IMU: Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.

You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.


If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.


Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.

Instead, you can use the C style strcmp function, which is also part of the C++ library:

    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    }


WiFiManager - Combine NonBlocking portal AND addParameter

The WiFiManger's autoConnect function starts the configuration web server (and AP) only if connection to configured WiFi network is not established.
If you want to run the WiFiManger's web server to reconfigure WiFi or to set other parameters, you can start the WM web server with the startConfigPortal function.
autoConnect and startConfigPortal are blocking by default. The library has a loop inside this functions which runs until the web server is stopped calling [Exit] action on the configuration web page or the timeout set with setConfigPortalTimeout is reached after last contact from browser.
To run the WM web server 'parallel' to your sketch you can configure it as not blocking with setConfigPortalBlocking(false). Then to allow WM handling of the web server the sketch must periodically call wm.process().
In not blocking mode the [Exit] action on the configuration wen page doesn't stop the web server. The server must be stopped in code.
The parameter definitions must by global in sketch, if you want to run WiFiManager with parameters outside of setup(). Parameters local in setup() don't exist after setup() finishes. WiFiManager detects this and doesn't use the parameters.
The OnDemandWebPortal example and OnDemandNonBlocking example demonstrate startConfigPortal in blocking and not blocking use.


Can I make existing libraries use external SRAM for the Arduino

Making a library use external SRAM is not an easy task. It can be cone, but it takes quite a bit of work.

The best start would be to abstract the SRAM into a library that provides simple access to it. Then you would need to use that new library to read and write data in the SRAM instead of accessing variables in the other libraries.

There is no way of simply mapping a variable into external SRAM - for that you need a microcontroller with an MMU  and/or an EIB.


Arduino not recognizing when a timer reaches 0

As per comment and Majenko's answer you are current creating local variables called secLeft and secLeft2 inside the 'if block.  These take precedence over the ones you have defined globally.  Removing the in declarations from inside the if block will stop doing that and point you at the globally defined variables.

As to the rest of the code. If you have

secLeft=(secLeft2--);
secLeft2=(secLeft);

Then that translates to this sequence of instructions

Assign secLeft with the value of secLeft2
Decrement secLeft2
Assign secLeft2 with the value of secLeft

And in the end you do not change anything.

This is because you are using post-decrement on secLeft2  EG secLeft2--.  This is a feature of C style languages.

I am not sure what you are even trying to do at this point.


Button press with Arduino repeated many times

I can't comment that's why I'm writing this as an answer but,

Are you doing exactly this this to wire the button?

I'd like to see your schematic but from what you describe there's a pull-down connection missing


The error you posted has nothing to do with an Arduino core. This is just plain avr-libc stuff. In order to use this kind of functionality, you need to

#include <avr/io.h>

In the Arduino core, it is common to have this done by default. But if this is not the case with your chosen core, just add the #include yourself in the program.


Using SD shield for extra external memory?

There are different options:

SD shield: much memory (GB's), however keep in mind that it will take time to retrieve the data from the SD card. Also you can retrieve 512 bytes every time (which also means it costs 512 precious bytes of arduino SRAM).
External SRAM: There are external SRAM ICs, like 23LC1024 or 24K256. These are much faster and offer 128 or 32 KB. There are many others too, these are most 'common'. These are much faster than SD cards, you can get 1, 2 or more bytes per time. But it's not the same as Arduino SRAM, e.g. you cannot really store variables, so you have to copy data to internal SRAM to be used.

So first, check how much you need, and more important: what is the latency you can live with.


The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.

As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.

Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the millis() timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives before the ISR is ready to service it there will be a delay - and any delay is bad.

Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).

SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.


where to syphon off voltage from a 25 pin serial?

You should be able to use pin 7 for negative, 9 as positive, this gives you 12 volts.

YOU MUST NOT HOOK THIS UP DIRECTLY to the arduino, connect it to a plug for the power jack (right of the USB connection).

If you are using a USB -> serial adapter, then the voltage may be 5v, but don't count on it.

Of course, USB is always going to be better!

PS - if you draw more power than the serial port is rated for, you will probably destroy the card. In most cases, this will be the motherboard. You are unlikely to be able to find out what it is rated for (look for Amps or A, or milliAmps  mA, or microAmps uA). The Arduino (with NO inputs or outputs, and idle) running from a 9v battery will draw about 50 milliAmps.


FYI, this issue was brought up nearly 3 years ago, with no response from the author:  https://github.com/rocketscream/Low-Power/issues/36


I would do it this way:

void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

eventually

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}


As far as I understand the DAT (Green wire) is a digital data wire. Try the following:
1. VCC to +5V pin
2. GND to GND pin
3. DAT to 2 Digital pin.

Then try to change the state of the 2 digital pin from high to low and see if anything happens... That's what I would start out with.


Arduino Vin pin does not work, but Arduino 5v pin power works

The Vin pin on the Arduino Uno board is connected to the input of the 5V onboard voltage regulator of the Arduino board.
This voltage regulator needs an input voltage that’s about 1.5V above its (regulated) 5V output that will feed the Arduino.
Arduino - note the recommended values of the Input Voltage (7-12V)
If you feed 5V into Vin, the voltage drop on the internal regulator will cause the Arduino board to be supplied with only about 3.5V, which is probably enough to make it function, but not enough to control the servos.
The solution, as you already found out, is to feed the 5V from the L298N board directly into the 5V pin of the Arduino. Please take care to measure the actual voltage from the L298N before you do this (it should be 5 Volts). Alternatively you could connect 12V to the Vin pin of the Arduino, but again, make sure you know what you’re doing.


DHT11 data in Arduino UNO to Firebase through ESP8266

First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO.
The code you have written will not work as you are giving instructions like Firebase.setFloat("temp",t); to UNO. It will not compile.
What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial.
ESP8266-01 will capture that data and transmit it over the Internet.
YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266.
All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!

If you want I can share all video list that I found useful!


How to Store 2 analogRead values and read using EEPROM for Arduino Uno?

See Reading and Writing Data Structures to EEPROM.

EEPROM.write(addr,a);

You can't directly write arrays. See the link for how to do it.

Example code:

#include <EEPROM.h>
#include <EEPROMAnything.h>

int array[2];
int addr=0;

void setup()
{
}

void loop()
{
  array[0] = analogRead(0)/4;
  array[1] = analogRead(1)/4;
  EEPROM_writeAnything(addr, array);
  addr += sizeof (array);

  if(addr >= 512)
    exit (1);

  delay(100);
}

Your posted code is a bit flawed anyway. You know EEPROM has a limited life? If you have a sketch that writes to EEPROM indefinitely you will wear it out.

My code above stops once it reaches address 512.


Programing a Mini 05 without a USB-to-serial converter

You can use the Mega. The only reason for "removing the chip from the board" is to disable it so it doesn't respond to the serial data - you can also disable it by just connecting the RESET pin to GND.


Reading 4 to 20ma pressure sensor using uno

To read a current with the Arduino you first have to convert that current to a voltage - and you do that by passing it through a resistance. The voltage dropped across that resistance as the current changes is what interests you.

simulate this circuit – Schematic created using CircuitLab

For a 4-20mA current you need to choose a resistance that gives voltages that are within the 5V range that an Arduino can read.

The biggest voltage drop across the resistor will occur when the current is at maximum (20mA) so you can use that to calculate a good resistor value to use:

R = V/I = 5 / 0.02 = 250

And for the same resistance at minimum current:

V=IR = 0.004 × 250 = 1

So across the resistor you would get between 1V (4mA) and 5V (20mA).

250Ω resistors aren't that common, so a more common value would be used instead - such as the commonly available 220Ω.  Substituting the 250Ω for a 220Ω would give voltages:

@20mA: V=IR = 0.02 × 220 = 4.4V
@4mA:  V=IR = 0.004 × 220 = 0.88V

Both comfortably within the Arduino's range and also gives a bit of wriggle room in case of any small over-current conditions.

It can also be good to protect the analog input of the Arduino with a resistor + zener diode to prevent damage in the case that the resistor fails / becomes disconnected and you get the full output voltage applied direct to the Arduino:

simulate this circuit


Using a MOSFET module to control DC LED PWM

it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --> ask the manufactuer to be sure.

whether it works for you will depend on the load, driving signal and the mosfet used -> you should ask the seller for a schematic, or buy one and reverse engineer it.


How to check if two device has the same address on I2C?

It's my understanding that duplicate I2C addresses prevent the master from communicating from the slaved devices, so the answer is no.

Instead, connect the devices one at a time, run the I2C scanner, note the address for each, and take note of any duplicate addresses.


How to read a Text file from server and store to a separate variable?

Here is what I found:

You need to have a special character like  "*" (a delimiter), from which important data will flow through.

char z = '*';
int s=0;

void setup()
{
  // usual initialization
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    // Serial.print(c);
    if (z == c)
    {
      s=1;
    }

  if(s == 1)
  {
    int i=0;
    k[i] = c;
    i=i+1;
    // Serial.print(k);
  }

  place +=k;

  Serial.print(place);

  }

.......
}


Both the Arduino and the Raspberry PI have interfaces like SPI, I2C and UART. These interfaces will make it easy for you to communicate between the two. I suggest you search for UART unless you need a very high data throughput, then you need to go for SPI. But unless you want to send over a thousand messages per second UART will work just fine.


If there is no code that enables the WiFi, it won't be enabled.

Here's the link:
https://www.arduino.cc/en/Guide/ArduinoYun#toc14


Do I need to solder wires to my tilt sensor?

I don't have the starter kit but I have a tilt ball sensor:

My guess is that there is a ball inside it, and it connects the wires, like this:

This is confirmed by measurement.

I suggest you either solder wires to it, or push the wires into your breadboard. As you can imagine from the diagram, the contacts will be closed if the ball (or mercury or whatever it is) is downwards. In other words, if the leads are facing down. As you tilt it, the ball will move away from the two wires, breaking the connection. You may have to tilt it quite a lot for this to happen.

(Edited to add)

I see from the Arduino Starter Kit page that the tilt sensor works like this:

This shows that my guess was pretty accurate. :)

There are four pins, so I imagine that the ball would connect four of them if held upright, and various combinations if tilted forwards or sideways.

  If you insert the pins into the board the sensor will always be standing and there will be no way to turn it.

Well, you could tilt the breadboard, yes?

However I agree that if you want to tilt just the sensor, then soldering wires to it would seem quite sensible.

I think the starter kit is there to show you the concepts. There is nothing stopping you tilting the entire breadboard to see how it works. In practice you would mount the sensor in such a way that it activated when moved from position A to position B, whatever that is.


Why is Arduino Pro Mini not powering this LED?

This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.

Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.


producing sine wave variable in amplitude and frequency

You can use a digital potentiometer as a programmable attenuator or as a feedback element in a programmable gain amplifier circuit.

See references  at arduino.cc regarding interfacing an AD5171 or AD5206 to Arduinos.


How to prevent Arduino compiler from merging changing of port pin outputs into a single operation

I certainly can't duplicate what you are saying.  The small code snippet:

void setup() {
    PORTD |= _BV(0);
    PORTD |= _BV(1);
    PORTD &= ~(_BV(1));
}

void loop() {
}

compiles into:

000000a6 <setup>:
  a6:   58 9a           sbi 0x0b, 0 ; 11
  a8:   59 9a           sbi 0x0b, 1 ; 11
  aa:   59 98           cbi 0x0b, 1 ; 11
  ac:   08 95           ret

000000ae <loop>:
  ae:   08 95           ret

That is clearly two separate bit sets followed by a bit clear.

I am using UECIDE that is set to use GCC 4.3.2

If I switch to GCC 4.8.1 instead, the code generated is identical.

Even turning on full -O3 optimization I still get the same results.

So how are you determining that it's happening at the same time?


Reading data from airspeed v3 eagle tree

I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.

the following code adapted from first sample above works on my Nano:

/*
 * note that timming is critical - see delay (5)
 * and bps set to 115200
 * works ok, but clean up 5-19-2019 jaf
 */

#include <Wire.h>

#define AIRSPEED_ADDRESS  0x75
#define WRITE_BIT         0x00
#define READ_BIT          0x01

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Serial.println("Program started");
}

void loop() {
  byte data[2] = {0};
  int i = 0;

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(WRITE_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(0x07);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(READ_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.requestFrom(AIRSPEED_ADDRESS, 2);
  data[0] = Wire.read();
  Wire.endTransmission();

  Serial.println(data[0]);
  delay(5);
}


The command line interface of the Arduino IDE is described in this document

https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

For example, this command will compile and upload the Blink example to my Arduino Leonardo

./arduino --upload --board arduino:avr:leonardo --port /dev/ttyACM0 --verbose examples/01.Basics/Blink/Blink.ino

Foot note: with IDE 1.6.0, there is an experimental version of the IDE for recent MacOSXs. It doesn't yet support the command line. If you need the command line on Mac, use the recommended version. This will be fixed with 1.6.1


for (int j = 0; j < 256; j++) {

  ...

  //blink off
  for (int j = 64; j > 0; j--) {
    ...

Notice that you are re-declaring the variable j.


Help with wiring? Fritzing example inside

Those are, in fact, the same board. When you look at this image (from Amazon)...

...you can see that there are really six pins, just two of them aren't soldered.

Your circuit:

On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. This module (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power and the TX/RX.

I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

tl;dr: it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about that specific part but there was another one that a reviewer specified that this was okay.

Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.


Arduino Mega2560 clone responding slowly

Either your fuses are wrong (set to 50% the real speed of your crystal / ceramic resonator), you're using the internal oscillator instead of the expected external one, or you have the wrong board with the wrong F_CPU value selected in the IDE.

Check all of those carefully.


Compatibility between Arduino and Arduino clones

Over the years I have used original Arduino boards as well as a multitude of clones of varying provenance, from the excellent InduinoX that is listed on the Arduino site as an official compatible board, to the very well-made Chinese Meduino Nano Enhancement (3.3 / 5 Volt switchable), to dirt-cheap clones from eBay that are sometimes better constructed than the official boards.

There is nothing unique or sophisticated about the Arduino board: It's basically just the microcontroller (atMEGA328, atMEGA1280, SAM3X8E or others) and its minimal support hardware. Not much that can go wrong with that little, really.

The two common elements that ensure compatibility across these boards are:

The Arduino bootloader
Support for the board within the official Arduino software distribution

The bootloader can be replaced with a better or more up-to-date version if one is available for the microcontroller on your board.

The support files can either be found online, or minor edits to the nearest similar board's files can provide the requisite support for the Arduino environment.

In short: Yes, clones typically work just as well as the original Arduino, and clones with enhanced features often work far better while retaining compatibility (e.g. InduinoX)


You aren't sending the Host: header with your request.  Without that the web server has no idea which website you want to get the /index.php page from.

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n"
                  "Host: 39c309ae.ngrok.io\r\n"
                  "\r\n";


Problems with passing objects in tree structure

TreeNode *children[];

That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.

If you only expect a small amount of children then you can use that upper bound as a static allocation:

#define MAX_CHILDREN 10

//...
TreeNode *children[MAX_CHILDREN];

Otherwise use a vector instead:

std::vector<TreeNode *> children;


In order to be sure that your classA object doesn't use the Serial.println() function before the baudrate is defined, it is necessary to add functions in your class ClassA and to inform from setup() your classA object.

The simplest way is to add:

a boolean bool bSerialReadyto keep the status of the Serial object,
in all ClassA constructors, initialize that bSerialReady = false;,
add a function void SetSerialReady() to switch the status bSerialReady = true;. The function should be called in the setup()function just after Serial.begin(9600);,
and in all functions of ClassA, add a if-condition if (bSerialReady) before calling the Serial.println().

Your class ClassA will become:

class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

Your setup() function becomes:

void setup() {
    Serial.begin(9600);
    classA.SetSerialReady();
    ...
}

And in functions of ClassA, it looks like:

if (bSerialReady) {
    Serial.println("Bar");
}


The following recommandations, as you are providing not enough relevant info

Install ESP-exeption decoder and analyse your backtrace - post it here so we see what indetail caused the wdt
Async webserver tends to cause this behavior if a response tends to take to long a well placed yield() sometimes helps to prevent that behavior - to anaylse you need ESP-exeption decoder
as loop() is running on core1 some/no process (idle) on core0 caused the behavior. You cann look up task assignment to cores be done manually to distribute the tasks (or send a yield() timed to core0 to reset the wdt
placing timeouts in combination with sleep/deep sleep (although you dont seem to use them) are also causes for wdt resets
a hackey trick is to set CONFIG_ASYNC_TCP_USE_WDT 0 but is ok for testing

If you look into async_tcp the possible culprit you see one line
xTaskCreateUniversal(_async_service_task, "async_tcp", 8192 * 2, NULL, 3, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE);
   Here an example how I use it to prevent wdt resetsPlace in setup()

disableCore0WDT();
disableCore1WDT();
disableLoopWDT(); // You forgot this one !

and because of this routine in the async_tcp lib

static void _async_service_task(void *pvParameters){
    lwip_event_packet_t * packet = NULL;
   for (;;) {
    if(_get_async_event(&packet)){
#if CONFIG_ASYNC_TCP_USE_WDT
        if(esp_task_wdt_add(NULL) != ESP_OK){
            log_e("Failed to add async task to WDT");
        }
 #endif
        _handle_async_event(packet);
 #if CONFIG_ASYNC_TCP_USE_WDT
        if(esp_task_wdt_delete(NULL) != ESP_OK){
            log_e("Failed to remove loop task from WDT");
        }
#endif
    }
 }
  vTaskDelete(NULL);
   _async_service_task_handle = NULL;
}

I set the CONFIG_ASYNC_TCP_USE_WDT 0 and it works so far.


Can I force a function to live in the boot sector without overwriting the bootloader?

The Optiboot version 8 has a do_spm function which can be called from application. The Optiboot repository contains an example for the use of this function.
SPM is the AVR CPU instruction to write to flash memory. The Optiboot wraps this in a function. A pointer to this function is put in a 'vector table' at the beginning of the bootloader. The first pointer jumps to main, the second pointer jumps to do_spm. The optiboot.h then has the function as (version for small Optiboot)
typedef void (*do_spm_t)(uint16_t address, uint8_t command, uint16_t data);
const do_spm_t do_spm = (do_spm_t)((FLASHEND-511+2)>>1)

I made an enhancement of this, a copy_flash_pages function with reset option to bootload an AVR from its own flash. It is added as third entry in the 'vectors table' of Optiboot. It is used in my ArduinoOTA library for AVR MCUs.
typedef void (*copy_flash_pages_t)(uint32_t dest, uint32_t src, uint16_t page_count, uint8_t reset);
const copy_flash_pages_t copy_flash_pages = (copy_flash_pages_t)((FLASHEND-1023+4)>>1);


How to send multi variable information over serial?

You have three options for what you want to achieve (if I understand it right):

Have a fixed length for each variable: If I know each number is going to be two digits, I can send "1234" and the other side can figure out the numbers are "12" and "34".
Have a delimiter character: Have a character that signals a new variable. For example: "213|1234" would translate into "213" and "1234". You could even use the newline character to signal a new line (with Serial.println();).
Do some sort of validation to separate the data: If sending a favorite number and favorite color, I can send "12RED345BLUE" and the other side it can find that it's "12" (both numbers), then "RED" (all letters), then "345" (three numbers), and finally "BLUE" (again, all letters).


Arduino Nano clone doesn't fit into breadboard. How can I work around this?

You might be able to use these female to female jumper wires and these headers and hook up the board and breadboard like this:

Note, the square female cable ends may not fit closer than 0.1 inches on center.

A more compact and (possibly) mechanically difficult solution may be implemented using wire-wrap sockets.  You may be able to leave the sockets intact and deform the pins to match the breadboard.  Or you may need to remove the pins from the plastic in order to accommodate your (different) Nano:


Is there any problem about calling if (Serial) many times?

There is no problem, no, but yes it will slow you down.

This is the source code to the boolean operator for the Serial constructor for CDC:

Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

As you can see from that all it does is check the value of a variable.  However it also imposes a 10ms delay¹.  Personally I'd have written it as:

Serial_::operator bool() {
    return (_usbLineInfo.lineState > 0);
}

And on top of that I'd have made it inline.

You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².

Edit: I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the delay(10) when it is actually needed rather than at every call to the bool operator regardless of need.

https://github.com/arduino/Arduino/pull/3624

¹ This is done to allow the port to complete opening at the PC end before data is allowed to be sent.  A better system would only perform the delay() at the moment of port opening rather than every call to the operator.

² Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message.  A better system is in the pull request mentioned in the edit to this answer.


You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.

That's not how you sample signals.

Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously.  Then when (and only when) a sample set has been captured do you send that data through serial.

If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending.  Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.


ESP8266 not working with MPU 6050 over wire library and I2C

I've been struggling with getting anything with the MPU6050's to work with either a D1 Mini or an older NodeMCU v1. I'm using D1/D2.
I've used the i2cdevlib MPU6050 library as well as the Electronic Cats' version.
I've used an assortment of sketches and even tried code which uses just Wire (no MPU6050 specific libs).

The best I've been able to get is the Electronic Cats MPU6050 library, without DMP, where at least it thinks the MPU6050 has been connected to, but it just puts out 0's as raw values.
The second "best", maybe, was some code that just used plain Wire, but except for Wire.endTransmission() returning success (and I had to slow loop() down for that), its numbers are gibberish (either 0's, or Z will just increment.  Nothing is affected by the movement of the board itself).

The DMP versions always fail to initialize the DMP.
I've tried 8.2k and 4.1k pullups on D1 and D2.
It works fine on an atmega32u4-based Pro Micro 16.


printing data from gps on Serial1 and sensors into Serial

This looks like another case of serial spam.  I recommend changing to a frame-based approach and controlling that rate with checks to millis.
That limits the spam.  Alternative is to limit it outright to 1:
//a static global:
static int isaidHELLO = 0;

//later in the loop
if (Serial1.available() > 0) {
    gps.encode(Serial1.read());
    if (gps.location.isUpdated()){
      Serial.println("Satellite Count:");
      Serial.println(gps.satellites.value());
      Serial.println("Latitude:");
      Serial.println(gps.location.lat(), 6);
      Serial.println("Longitude:");
      Serial.println(gps.location.lng(), 6);
      Serial.println("Speed KT:");
      Serial.println(gps.speed.knots());
      Serial.println("Altitude Feet:");
      Serial.println(gps.altitude.feet());
      Serial.println("");
      isaidHELLO = 0;
    }
  }
  if(isaidHELLO == 0)
  {
      Serial.println("Hello there");
      isaidHELLO = 1;
  }


If you are ready to wait a month for delivery and also giving up flexibility by restricting yourself to just sending and receiving SMS, then you can go as low as €2 for a DIY kit on AliExpress.

By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".


You did not specify what Arduino board you are talking about. It would
have been useful to tag the question with the appropriate board name. In
the following, I assume you want something similar to an Arduino Uno,
i.e. an ATmega328P at 5 V and 16 MHz.

  I realize I can go look up the actual design itself [...]

You should. There really isn't that much to it.

Let us take a look at the Uno rev. 3 schematic, and see what may be
useful to you:

ATmega16U2 and associated circuitry: This is for USB communication.
You have no use of it if you are not doing USB.
3.3 V regulator: This is for providing the Arduino 3.3V output.
Only a convenience feature, not used by the Arduino itself. You should
leave this out unless you need a 3.3 V supply.
5 V regulator. Only you know how you want to power your board.
This regulator is needed unless you have some reasonably stable
5 V supply like, e.g., a USB bus.
ISCP header: This is rarely used on an Arduino, but you are very
likely to use it in your custom board, as ICSP is the easiest way to
program an ATmega with no bootloader.
Reset button: Not always needed, as you can just power-cycle your
board.
10 kΩ pullup on RESET: Your board is very likely to work just
fine without this, but there is a little risk that you suffer from
random resets. You want this resistor on anything that is
“production”-like, for reliability concerns.
Decoupling capacitors: Just like the RESET pullup, the board may work
without them, but they provide reliability.
The MOSFET and OP-amp right before the 3.3 V regulator: This is
for automatically switching between the Vin and USB power supplies.
Unlikely to be useful on a custom board.
Ceramic resonator: For running the ATmega at 16 MHz, you need
either this or, for better timing characteristics, a quartz with
suitable capacitors.
LEDs: You know if you want them.
AREF capacitor: Only useful if you do analog readings, as it reduces
noise.


The 12MHz crystal is for the USB interface.

The main MCU uses a very small 16MHz resonator, which you can see between C5 and C6.


You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.

Some places you should, therefore, probe for voltages, and what voltages you should expect.  With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

At the rear of the socket: 12V
At the socket side of the M7 diode: 12V
At the header side of the M7 diode: 11.4V
At the right-hand (VIN) pin of the regulator: 11.4V
On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.


Digital pins on Arduino function as both positive and negative terminals?

The answer to your question is basically yes, you can use ATmega I/O pins as +/- power supply terminals for other circuits. But there's a limit to what you can power that way (20mA per pin and 100mA total per ATmega). In practice this means you can only power the simplest circuits (single LEDs per pin, and not many LEDs in total, for example). As a general rule, you should really look for other ways to power anything else.

Also, there's a problem with the citation you gave. That 40mA figure is the absolute maximum current per pin, but that should be avoided. Safest is to use about 20mA of maximum current per pin. Also, the ATmega pins should not have more than 200mA flowing through Vcc and GND (also an absolute maximum that should also be avoided).

Usually, you should either power other stuff off of the regulated +5V that also feeds the ATmega (up to the regulator capacity that depends on the Arduino board - 500mA for the Arduino Uno - 1A for LM7805 regulators - and so on). You could also use the unregulated power in some cases. Then you should use digital pins on the ATmega to switch transistors on and off which in turn will switch your load. Sometimes you can use transistors to switch relays, that in turn will switch even larger loads.


As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.

It is likely you are receiving everything in ASCII code.  That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.

This is fine when you are working with character strings.  But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal.  That is, subtract 0x30.

It should now be obvious that you can only enter 1 digit at a time when using a terminal.  That you will have to reconstruct the number as the user types each digit.  For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.

Since this is such a common conversion, there are Arduino libraries that do this for you.  Consider using ParseInt for this purpose.

Added later...

In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed.  And that the code is only waiting for the CR.

The delays are necessary as UART communication, as most communications, takes a finite amount of time.  And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.

Consider "looking" for the LF character after finding for the CR character and removing the added delays.


2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High

You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.

That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.

Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.

You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.

You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.


Can I control a 28BYJ-48 5V stepper with a DVR8825 driver?

Stepper motors are rated in two different ways. Some provide a "rated voltage" in combination with a "DC resistance", others provide a "phase current" and a "phase resistance". The way they operate is identical.

Stepper motors such as your 28BYJ-48 are usually intended to be driven with a fixed voltage, their rated voltage. At this voltage, the maximum permittable current flows in the steppers windings - determined mostly by cooling and wire thickness. If you exceed that voltage, more current will flow and will damage / destroy the stepper motor.

The DRV8825 is a current controlled stepper motor driver - it always uses the full available supply voltage - 8.2V+ - but uses PWM to limit the current actually flowing in the stepper. This is possible because the stepper motor coils are inductors, which inhibit the flow of current.

To use your stepper motor with a DRV8825 driver, you'll have to calculate the steppers equivalent "maximum phase current". According to this datasheet, it's rated 5 V at 50 Ohms, giving us a current of 0.1 A. You can then set this current via the potentiometer on the driver chip. The Vref voltage should be set so that Vref = Imax / 2.
Start at a Vref of 50 mV, and see how warm the motor gets and whether it's as strong as you would expect it to be.


Venus GPS + Arduino. Kill 3.3V TX during sketch upload

If you have a logic-converter between the Arduino and the GPS then you won't have any problems.

The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.

However you could just as easily upload a "do nothing" sketch like this:

int main () { }

That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.


Arduino Due 16U2 Programming Port Documentation

The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.

Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).


Calculate the Li-Po Battery Level in ESP-Wroom-02

Another problem you can run into is that a lot of the A/D converters use the VCC as a voltage reference. Which means that as your input voltage drops (what you are trying to measure) the reference voltage also drops which means the values you are recording will not appear to change or at least will not give an accurate reference.


As Majenko said you can use the millis() keyword.

Unless millis is not accurate enough. In that case you can use micros(), but this overflows every 70s if I'm correct, but you can offset it against millis().

If you need to compare two values, what you can do is:

get millis()
get micros()
read sensor data (optimize if needed)
get micros()

Average the difference of the micros, and add it to millis, and you have the average time for the sensor data readings.

Of course if it doesn't matter that all sensor data is read at approximately the same time, you can use millis() for each sensor data reading and work with those values.


I found this code for the SRF05 and it works for the SRO4M-2 as well.
Good Luck!
const unsigned int TRIG_PIN=13; //RX
const unsigned int ECHO_PIN=12;  TX
const unsigned int BAUD_RATE=9600;

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(BAUD_RATE);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
  int distance= duration/29/2;
  if(duration==0){
    Serial.println("Warning: no pulse from sensor");
  } else {
    Serial.print("distance to nearest object:");
    Serial.println(distance);
    Serial.println(" cm");
  }
  delay(100);
}


problem using one function to blink different leds

You want to let the LEDs blink concurrently.
Your static variables oldTime, and ledState are shared between the three LEDs.
So there is ony ONE ledState in your program but you need that state for each one.
Same applies for oldTime.

Resolve the this issue and your LEDs will blink as expected.

btw. you don't need the ledState as you can read its current state.


How to control a DSP-G1 programmatically/electronically?

The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.

If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)

MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:

Serial.begin(31250);


How do I set a constant in setup() that I can use in loop()?

You can't, and there's other things wrong with your code.

int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);

Calling functions from the global scope is an incredibly bad idea.  Those are run before the board has been properly initialized, and the results you may get from it are not guaranteed in any way, shape, or form.  Instead you must call functions like analogRead() from within another function, like setup(), or loop().

As for const - a const is just that - a constant value that can never change.  You can only assign a value to it at the moment of creation.

And that means that you can only use it within the scope it was defined within.  As you can't do that in the global scope (see above) then you cannot use a constant.

So just use a normal global variable.  It will only change when you tell it to change.  Using a const only makes sense when you have a numeric literal that you want to refer to by name. Using const doesn't protect the variable from being changed at run-time by memory leaks, etc, it just protects it from attempts to modify it at compile time - and if possible replace it with the numeric literal that it refers to.

So in summary just use:

int sensorValue1;
int sensorValue2;
int p1;
int t1;

void setup() {
    sensorValue1 = analogRead(A0);
    sensorValue2 = analogRead(A1);
    p1 = (1.09512*sensorValue2-22.105)*133.3225;
    t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}
... etc ...

HOWEVER: Your program methodology is also completely flawed.  You read the analog values once, and do calculations with them once, then repeatedly display the same values over and over again.

You must perform a new analogRead() of your sensors every iteration of loop() in order to update the values in your variables.


Digital pin output voltage fall down when driving a relay

If the coil is 70 ohms and it's driven by 5V, it should draw about 5/70 = 71 mA.  That's pushing the 2n3904 a bit hard, and doesn't even account for inductive effects. (It's a small-signal transistor.)  Do you have an NPN power transistor to try, just as a test?  If its current gain (beta) is too low, use a Darlington configuration by combining it with your 2n3904.  (2n3904 base from digital out resistor, emitter drives power NPN base directly, both collectors are connected together to the bottom of the coil, and the power NPN emitter is the effective emitter of the just-created "super transistor" with high beta and power handling.)  Be sure to use an anti-kickback rectifier (1n4001)across the relay coil.


How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message?

Apparently there is no ATMega32U4 on that board but ATmega328P according to the signature 0x1e950f.

Anyway, you may have to change or add new board with correct MCU setting.

Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.

I've found board definition for Arduino UNO:

unoyun.name=Arduino Uno -- Dragino Yún
unoyun.upload.via_ssh=true

unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true

unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F

unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

More info about it here: https://www.arduino.cc/en/Guide/ArduinoYunShield or similar product http://wiki.dragino.com/index.php?title=Yun_Shield


Can a stepper motor be controlled directly from an Arduino?

Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.

Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.

A solution is to use a motor driver chip or shield. This one is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.


According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.


How to program micro chips directly with USB

Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.

Some chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.

However chips that don't have USB will never have a USB DFU bootloader in them. In such cases is is your responsibility to create (or otherwise obtain) a suitable bootloader that you will install into the chip.

Digispark and Adafruit both do that.  They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.

For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.

If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have proper USB communication instead of slow HID and custom (non-standard) protocols only3.

Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE.  The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

Personally I think that's a horrible idea and should NEVER be done. I'm a purist though.
Such as the ATMega32U4 used on the Leonardo and Micro boards.
VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.


The difference between "time_t" and "DateTime"

A DateTime is a full class with lots of methods to it - a time_t is just an unsigned long.

time_t is used to store the number of seconds since the epoch (normally 01/01/1970)

The Arduino Time library returns a time_t to the now() function - but RTCLib return s a DateTime object.

The DateTime object, though, has a unixtime() method which will return a time_t representation of the time stored in the DateTime object.

So you can do:

DateTime dt = RTC.now();
time_t time = dt.unixtime();


Exit status 1 expected primary-expression before ']' Arduino

I wouldn't use strncmp because the UID might have zeroes in it. This looks safer:

   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (success &&
      uidLength == sizeof (wantedUid) &&
      memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
      ...

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.

memcmp compares a block of memory for the number of bytes you specify. It returns zero on a match.


Using an Arduino for learning embedded C programming

The Arduino is a great place to start embedded C programming. You can use both C and CPP. There are tons of tutorials online and there are a bunch of books available. In addition there are lots of libraries available on GIT HUB for interfacing with all types of hardware like RF24 Wireless Transceivers.

If you want to go into more low level programming, you can. For example, you can set all Port B pins to Output:

// the setup routine runs once when you press reset:
void setup() {

  // initialize the digital pins as an output.
  DDRB = 0xff;
}


I am making heated socks with adjustments by Nano and want to extend batterty life?

With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.
Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.
Current • duty cycle • on-time = total power consumed AND total heat generated.
If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.
Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to right and left) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.
All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.
Edit:
If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.
If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.
Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using delay().


Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags.  If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error.  Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.

If this type of response time is not needed, interrupts may be more trouble than they are worth.

This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program.  This can be very confusing to new programmers.  At any moment an interrupt may stop their program and possibly erase or change what that program was working on.  Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.

It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt".  Using the Arduino paradigm, the purposes of the loop() entry point is to do just this.  A function which will be called over and over again.  Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.


Can you save data to EEPROM using firmata?

You have to edit the Firmata source code and add a few lines of code:

add the EEPROM library
include the library into the Firmata code
in the setup() function use the EEPROM library to read the id from the EEPROM

How do you plan to write that data into your Arduino EEPROM?
If you want to do that via serial connection than you also need to add that code.
I have done something similar in an example for my VoltageReference library, specifically in EEPROMCalibration.ino

UPDATE

After a little investigation I understand there is the possibility to exchange generic messages and handle generic commands via Firmata: commands 0x00-0x0F are reserved for customization. On the Arduino side you can use:

void storeToEEPROM(int id) {
  ...
}

void readFromEEPROM() {
  char buf[12];
  Firmata.sendString(itoa(the_id, buf, 10));
}

void setup() {
  ...
  Firmata.attach(0x00, storeToEEPROM);
  Firmata.attach(0x01, readFromEEPROM);
  ...
}

That will allow you to write and read the id using those two custom commands.


There are quite a few points that could be improved in this code. The
main ones have already been shown in the comments:

the data buffer was not large enough to hold the whole string,
which leads to a buffer overflow, memory corruption and, ultimately,
the crash you are experiencing.

The second parameter to snprintf() should be the size of the
provided buffer.

Here I will add a few points that, although not really defects of this
program, could help improved it and save memory.
Here:
char current[4];
// ...
if (val)
    snprintf(current, "YES");
else
    snprintf(current, "NO");

you are not using the current buffer to build a string, but only to
store one of two pre-existing strings (the literals "YES" and "NO")
that are already stored in memory. Rather than making a copy, you could
instead reuse those pre-existing strings, and have current be a
pointer to the relevant one:
const char *current;
// ...
if (val)
    current = "YES";
else
    current = "NO";

This only saves two bytes (size of the buffer minus size of the
pointer), but this pattern happens multiple times in the program, and
the savings add up.
Now, another small optimization. Here:
char strt[6];
sprintf(strt, "te=%d", temp);
strcpy(data, strt);

you do not need the extra strt buffer, as you can write directly into
the data buffer. Better yet, you can write everything into the
buffer in a single call to snprintf():
snprintf(data, sizeof data,
        "te=%d&ti=%02d:%02d&mot=%s,%s,%s&mo=%s&hum=%d",
        temp, t.hour, t.min, ventionoroff, Foggeronoroff, current,
        Exhuastonoroff, hum);

If you don't like this approach, and would prefer writing the data in
separate calls to snprintf(), you can do so without using auxiliary
buffers. You have to remember (with a pointer) where within the buffer
you finished your previous write, and pass this address to the next
snprintf() call. Note that you also have to keep track of the room
that is still available, which is easy to do with a second pointer that
points to the end of the buffer:
char *p = data;                  // current writing position
char *end = data + sizeof data;  // end of the buffer
p += snprintf(p, end - p, "te=%d", temp);
p += snprintf(p, end - p, "&ti=%s", today);
// ...


UNO SPI slave read from UNO SPI Master beginTransaction

Okay so I have got this working now. It seems that it was the Slave not understanding the data mode. I found the SPI.setDataMode() it is listed as Do not use in the reference guide on Arduino.com but its worked spot on for me.


Arduino: put string through variable in array

A String isn't a char array. You can't assign one to the other.

You shouldn't be using String, it's too heavyweight, and how you are passing your String object is wrong, it wastes huge amounts of memory making clones.

You should read this.

The only time you should ever consider using a String object is if you are using a third party library that requires a String object - and even then you should consider other methods.

Regardless of that, you need to copy the content of your string, not the string itself.  This code should work, but it doesn't address the underlying String issues:

String splitStringIntoCoordinates(String &input){
  char arr[input.length() + 1]; // Create a char array big enough including the terminating NULL
  strcpy(arr, input.c_str()); // Place incoming route in char array
  // ... etc ...
  // return a string
}

If you just want to reference the String as a C string you can just use the function input.c_str() to get the internal char * array pointer.


Using I2C to keep track of position of slaves

This is indeed not possible.  I2C was meant for short on-the-same-board communications and though it's sometimes also extended to near-board communications, it still has no facility for position sensing.  Each slave  simply listens for an address and then responds to commands sent for that address.

Slaves can "stretch the clock" to slow down things, but cannot otherwise make themselves known so long as they are not mastering the bus.  In any case, even if bus mastering is assigned round-robin, only presence can be determined, not the position in any chain.


NRF24L01+ (TMRH20 library): Receiver gets blank data

A couple of clarifications first

At the time instant 22:38, the receiver isn't detecting any available radio devices but at the transmitter side, an acknowledge is received. How is that possible? How is your tx getting an ack without the rx getting connected.
I have not seen slave adresses being set as - const byte slaveAddress[5] = {'R','x','A','A','A'}; For the record, NRF24L01 adresses are 5 bytes long by default and not 1 byte long as you have defined. While defining the pipe addresses, the first 4 bytes of the adresses should be same among all the pipe addresses. Only the last byte should be unique. Pipe addresses can be 0xF0F0F0F0A1, 0XF0F0F0F0B1, 0XF0F0F0F0C1, 0XF0F0F0F0D1, 0XF0F0F0F0E1 Try setting the pipe addresses as uint_64t address[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};Do the same declaration at the receiver end too. And btw, you can specify any byte you want in the last byte of the address. Here I have defined the last bytes as A1, B1, C1, D1, E1.
To make sure that communication is successful, set some custom ack byte and compare it with the received ack. If both match, you can be sure that the rx did get the data. Sometimes, the NRF24L01 can pickup garbage values from stray signals present around and it can consider it as data sent by the receiver. So to avoid false triggering, its better to make a fool-proof ACK mechanism.


Simple Arduino Bluetooth Shield Android Display

You need to terminate the string sent by adding blueToothSerial.println(""); after blueToothSerial.print(temp1);. As it is the code doesn't terminate the temperature string with an LF char, and the Android app thinks it hasn't received the full string yet.

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  blueToothSerial.println("");
  delay(1000);
}


An NPN bipolar transistor requires a current to flow from base to the emitter which is then multiplied by the beta of the transistor controlling the maximum current which flows from the collector to the emitter.  A 2n2222 beta is about 100.  Let us calculate the amount of current which will be allowed to flow from the collector to the emitter of the 2n2222 transistor.  First calculate the current from the base to the emitter:
I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
I(be) = .0043 Amps

Use this current to find the maximum current flowing from the emitter to the collector:
I(ce) = 100 x I(be) = 0.430 Amp or 430mA

We see that the transistor does not provide enough current to drive a 600mA motor.
We need to reduce the value of R1 such that I(ce) is at least 600mA which means that I(be) needs to be at least 6mA.  Rearranging the earlier equation to find R1:
I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
I(be) = (5.0 volts- 0.7 volts) / R1
R1 = (5.0 volts- 0.7 volts) / I(be)
R1 = (5.0 volts- 0.7 volts) / 0.006 Amps
R1 = 716.67 ohms

However, because of the large amount of I(ce) current necessary to drive the load, we find the transistor reaching it's limits and the beta of the transistors drop apprecably:

This diagram is a little hard to understand.  And there is no curve for 600mA.  But we can get an idea of what to expect if we look at the 500mA curve.  We see that in order to get less than a volt drop across the transistor (V(ce)) we need to pump in more than 10mA (I(be)).  To get similar results for 600mA we would likely approach 20mA and now we are dangerously close to the processor pin current driving capabilities.
A common alternative is to use a Darlington Transistor configuration:

The resulting beta is essentially the product of the individual transistor's betas.
Let's do some rough calculations.  If the 2n2222 that switches the load current has a lower beta of about 10, we would need about 60mA to switch a 600mA current.  To generate 60mA through the transistor connected to the processor, we would need about 0.6mA from the processor.  That's really small and we can afford to triple it to ensure reliable operation.  So let's pick 3mA:
R1 = (5.0 volts- (2 * 0.7 volts)) / 0.003
R1 = 1200 ohm

So a 1K ohm resistor should likely work.


Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually?

The LEDs are "addressed" in series; if you address the first LED then you address all connected first LEDs. So yes, you must connect the Data Out of the previous LED/strip to the Data In of the next in order to address all of them individually.


Looks like you're using https://github.com/esp8266/Arduino, in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.
I am not entirely sure why the NodeMCU guys had to do this "pin remapping", but the end result is inconvenience when using the module with anything but their Lua.


Interrupt routine for button somehow respondng to room lamp turning off and on

Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

Conducted EMI through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).
Radiated EMI (most likely). There are some things you can do to mitigate its effects:

Use wires as short as possible.
Twist wire pairs whenever possible.
Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this this. You'll have a better grasp about the art of debouncing inputs.

SPOILER: One thing you can do to make your debouncing routine far more robust is to wait for N consecutive readings with the same value (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.


There is this thing called "operator precedence" that defines the hierarchy of operators.
The ?: will be calculated after the +. That's why
s = s + digitalRead(2) ? "1" : "0";

actually means
s = (s + digitalRead(2)) ? "1" : "0";

But you want
s = s + (digitalRead(2) ? "1" : "0");


You can trigger on CHANGE, and check in your handler which case it is:

   attachInterrupt(digitalPinToInterrupt(my_pin), my_handler, CHANGE);
    (...)
    void my_handler(void) {
      if(LOW==digitalRead(my_pin)) {
        //do_falling();
      }
      else {
        //do_rising();
      }
    }

Another option would be to use a timer to poll your input, and implement a logic on top of this.


How is it possible to access the CPU registers using memory addresses?

Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.

As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

  Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM


Welcome to the Stack Exchange and on the Arduino World.

Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).

When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.

To program it, you need to know which COM port is created for your Arduino module:

Press WIN-'R' (execute application)
Write devmgmt.msc

Check the COM port to see wich COM port was used for your Arduino.

This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.


Standalone ATmega clock continuous lifetime

So how long will my clock run if is it supposed to be online 24/7

Until you turn it off or a stray neutrino corrupts the flash memory, or the flash memory degrades (20-100 years or so depending on temperature).

Should I reset it sometimes? If yes , when, after how many days should I reset it?

No.

And do I need a coolant system for it? (I guess not)

No. Not unless it's in a sealed container with no ventilation and a hot environment.
However
Your RTC-less "clock" will probably not be particularly accurate, unless you have some external source of time (NTP, GPS, etc) as the Arduino's internal timing is not very accurate, and built on a breadboard it's even less so due to excess stray capacitance.


Look at line 55, where you are doing this

temperature = newSetpoint;

There is no reason to give temperature the same value as the set point. It does not make sense. And the temperature variable is the same, that you are using to display.

So, while you are changing the setpoint, the temperatur variable gets overwritten with the setpoint. When you are not changing it anymore, the measured temperature is still in this variable, when you are displaying it.

Just remove the mentioned line.


Stack arduino, motor shield and lcd shield

Stack one shield on top of the Arduino itself and connect the other shield using wires. This way you can pick your own pin assignment for the 'external' shield.

Be careful when using a specific library though, sometimes the used pins are hard-coded in the library itself. Modifying the .h and .cpp files for the library is possible, so you could (hard code) assign your own used pins.


How do I get the size of my program at runtime?

Just to warn you, I minimally tested this, but it seems to work.
In the Due's linker script there are these relevant lines, containing the named rom section.
MEMORY
{
    rom (rx)    : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K */

Below you'll see:
SECTIONS
{
    .text :
    {
        . = ALIGN(4);
        _sfixed = .;

_sfixed is a symbol they've created to mark the current location, which happens to be the start of the rom section in this case, 0x00080000.  At the bettom of the brace matching the one following .text, you'll see:
} > rom

showing that section goes into ROM, which is why . at the beginning of the .text section refers to the rom section start address.
If you look near the last thing placed in rom, you'll see:
    . = ALIGN(4);
    _etext = .;

So, they've set another symbol there, the one of interest, _etext, the address of which should be the byte of ROM not used, or so I thought the first time through this; turns out it isn't.  I gather you have no use for start of ROM symbol, since it's a static value and at the beginning, so I'll ignore that, but if you cared to make use of it it could be done the same way as follows for _etext.
These symbols don't have any type, but you can make them whatever you want.  If you want to perform arithmetic on a pointer that results, it makes sense to use a char type, so:
extern "C" unsigned char _etext;

I thought this was the end of the story, could just take the address of this symbol, but there is more to it.  Following the regular code is this section:
    .relocate : AT (_etext)
    {
        . = ALIGN(4);
        _srelocate = .;
        *(.ramfunc .ramfunc.*);
        *(.data .data.*);
        . = ALIGN(4);
        _erelocate = .;
    } > ram

They're placing code for the banzai (reset) function (and perhaps other things), which goes into ram ultimately, at this location in ROM.  So, presumably in the start code this is copied from the end of the normal program code into some place in ram.
So, there are two more symbols of interest here, _srelocate and _erelocate.  Declarations for them:
extern "C" unsigned char _srelocate;
extern "C" unsigned char _erelocate;

These symbols resolve to addresses in RAM, so they can't be used directly, but can have their addresses subtracted to get the size of the image in ROM that gets relocated to RAM, leading to:
const unsigned char *rom_end = &_etext + (&_erelocate - &_srelocate);
Serial.print("The end of used ROM is : 0x");
Serial.println((uintptr_t)rom_end, HEX);

When I compile and run a simple test like this and check the serial monitor connection, I see output like:
The end of used ROM is : 0x82FF8

If look at the .bin file produced by the compiler:
$ wc --bytes  build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin
12280 build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin

And 0x82FF8 - 0x80000 == 12280.
When I hex dump flash around this address I can see what looks like it padding out the flash sector with 0x00 bytes before the next unprogrammed flash sector shows as 0xFF.  So you would need to round this up yourself, and if you want be somewhat safer, maybe add some margin.
I don't know how common that configuration in the linker script is.  It's likely that most linker scripts place a symbol there, if they've had some forethought.  But I wouldn't necessarily expect it have the same name.  It's possible they modify it to add more stuff after that symbol.  But for now, for the Due, that would seem to work fine.  It is a bit messy though.


Running Pro Mini Continuous on 12v w/o Damaging Regulator

Summary:

Simple, effective, low cost solution - choose any 3:
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.

Detail:

Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)* 0.040 ~= 350 mW

"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.

Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.

Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W  x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external  will make an immense difference.

An easy and effective solution:

The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

Vsupply_minimum - the absolute lowest value supply will assume.
Vreg_in_minimum  I'll use 6V to start.
I_load_maximum - you said 40 ma. This must be abs_max or if of very short duration must be able to be supported by capacitors.

Then

Rmax = V/I = (V_supply_min-Vregin_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially.
A  W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.

Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.

Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.

._______________________________________

Temperature rise inside box due to heat dissipation.

Summary: Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.

Notes:

Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area.  Obviously:
 - Thicker plastic leads to higher temperature rise.

More surface area leads to lower temperature rise.
Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

Delta T = Watts x thickness / (Ktc x area)

So Ktc = Watts x thickness /(Delta_Tx area)
So units of Ktc must be Watts/metre/degree_C
Which is indeed how Ktc is usually expressed.

This table of Thermal properties of plastic materials lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.

Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here  = L D W = 100mm x  50mm  25 mm or 0.1 x 0.05 x 0.025m
Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts

Using the formula - Delta T = Watts x thickness / (Ktc x area)  from above

Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.


How to add data without pre-defining variables?

Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.

As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

For those who don't know

In C, data relevant to an object can be stored in a structure, or struct. You can put all sorts of different types of data in a struct, like so:

struct personalProfile {
    char    firstName[8];
    char    lastName[8];
    uint    cardID;           // 'uint' is an unsigned int...
    bool    accessAllowed;
};

You can then use that structure to create a 'personal profile' for however many people you want:

// within your main program:

struct personalProfile Person1;
struct personalProfile Person2;

// Now you can directly access individual aspects as so:

Person1.firstName = "John";
Person1.lastName = "Brown";
Person1.accessAllowed = TRUE;

Person2.firstName = "Dodgy";
Person2.lastName = "Dave";
Person2.accessAllowed = NOT_A_HOPE_IN_HELL;

You can use the members of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.

The best way to store multiple instances of a particular variable type is in an array:

struct personalProfile listOfPeople[5];

You now have an array of five (blank) structs, which can be accessed by listOfPeople[n].firstName = Potato;, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.

An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five structs in it you can't add or remove any. One solution is to create a massive array, and set all the values in each struct to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.

Next comes containers. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

EEPROM basics

The EEPROM library that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.

Using the function EEPROM.put(address, data) you can put ANY data type - an int, char or - you guessed it - a struct into the EEPROM, starting at the byte specified by address. Of course there has to be enough space so you can't put an int, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)

So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.

// within main program

struct personalProfile Person1;
struct personalProfile Person2;

// fill in the details for Person 1...
// fill in the details for Person 2...

// ...then put Person1 in the EEPROM at address 0.
EEPROM.put(0, Person1);

// Done. Now put in Person2. But where?
// You need to make sure you put them AFTER Person1.

int AddressJump = sizeof(personalProfile);

// AddressJump now equals how many bytes are need to store one person.

EEPROM.put(AddressJump, Person2);

Simple as that.

If you create a Person3, you're going to need to put them sizeof(personalProfile) bytes AFTER Person2, i.e. EEPROM.put(AddressJump*2, Person3);. So, you add PersonN to address AddressJump * (N-1).

Retrieving data is the same principle, except you use EEPROM.get():

// provided you've used the above snippet somewhere to actually
// populate the EEPROM with something!

struct personalProfile personA;

EEPROM.get(0, personA);

Serial.print("Person A is called:");
Serial.println(personA.firstName);

Again, you're going to need sizeof(personalProfile) to read the second, third, or Nth person. If you 'send EEPROM.get() to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't put one person on top of another (you could get in trouble for that) and you don't want to get someone that isn't there.

List management

This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.

Your first task is to determine what sort of array you want. Inevitably it's going to be a Linked List. This is an array of structs, where each struct element in the list contains the memory address of the following element, thus the list is linked. You need to consider:

How the array will be linked (if at all);
Whether or not the array is space-critical (does it have to be as small as possible);
Where the array is going to start;
How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!


#define I2 13  // Control pin 2 for motor 1

Pin 13 is the LED and is blinked by the bootloader. You will have to use a different pin for your motor.


Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:

do {
    add_logs_in_suspicious_places();
    wait_until_it_crashes();
    analyze_logs();
} while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)


How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller?

The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is Torricelli's Law.

My suggestion for you is design a system which use a feedback concept instead


I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

1. When INPUT is LOW:

Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.

2. When INPUT is HIGH:

Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.

3. When INPUT is floating (microcontroller is turned off):

Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)


1A coming in thru the barrel jack connecor, then you risk blowing the 1A rated reverse polarity protection diode. The 5V regulator will overheat at high currents above 7.5V. The chip itself can have 800mA put thru if if properly cooled and the IO limits of current per port are respected.

So 1.6A, no way.


What is "tws_delay" and how can I use it? (with an ATTiny85)

tws_delay() is a function provided by the TinyWireS library here. As you can see from the declaration - void tws_delay(unsigned long); - it accepts a parameter of unsigned long, just like delay() does.
In fact, the comment on the line above that declaration says...
// Implement a delay loop that checks for the stop bit (basically direct copy of the stock arduino implementation from wiring.c)
... so, it's safe to say that wherever you would have used delay(), you can use tws_delay().
So there should be no need to declare or define it. But to simply use it. If using tws_delay() in code that includes TinyWireS.h doesn't work, I would be checking that you have a version of the library that declares/defines it. Which you should, given the example you linked, as that repo has had the function since 2012!


I think, the problem in that line B test. You are define a variable, but you forget to define default constructor ( B() ). You try to setup an A class with unknown pin! To avoid this you may define test variable in that way B test(2); or in that way const int test_pin = 2; B test(test_pin);. Also to avoid this problem you may to set default value to the constructor sucha as  B(int attach=2) : myA(attach) {} and define test variable, as you do in your code B test;.


Is there a variable type of half byte? Is there a workaround?

If the point is to save program storage space, you're probably going to have to live with some unreadable bit mush or do bit-swapping in your head. Here's a code example that encodes your same array as a 32-byte array, but you have to combine pairs of your original numbers into bytes. It's not especially difficult because each hex digit represents one of your original numbers.
I.e., 8,9 becomes 0x89. Likewise, A is 10, B is 11, etc. Then you can iterate 1 thru 64 and do some division and bit-shifting to pull out the original value you wanted. This will iterate through your 32-byte array and pull out 64 half-byte values.
    const byte wave[32] = {0x89,0x9A,0xBB,0xCC,0xDD,0xEE,0xEF,0xFF,0xFF,0xFF,0xEE,0xED,0xDC,0xCB,0xBA,0x99,0x87,0x76,0x55,0x44,0x33,0x22,0x21,0x11,0x11,0x11,0x22,0x23,0x34,0x45,0x56,0x77};
    for(int i=0; i<64; i++) {
        byte val;
        if (i % 2) {
            // the little byte is first (LITTLE ENDIAN)
            val = wave[i/2] & 0x0F;
        } else {
            // the BIG byte is second
            val = (wave[i/2] >> 4) & 0x0F;
        }
        Serial.printf("%i=%i\n", i, val);
    }

NOTE: that the Endianness if your system may be different than mine. Most systems are little-endian these days, but you never know.


How is a 41KB char array filling up 256KB of program memory?

The limitation here is the data type of the index of the array. That is int, and on an 8-bit system an int can hold a value in the range -32768 to 32767.

That means the biggest index number an array can have is 32767.

That limit cannot be changed. You're stuck with it.

However, there are some tricks you can use to expand it.  One is to use a larger data type than char and pack your data into it.  For instance, using unsigned int as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.

Using unsigned long (32 bits) would double that again.

It is then up to you to work out how to get to the individual bytes. Using the pgm_read_byte_*() function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...


What's the difference between #define and const int when declaring a pin?

"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.

"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.

Example:

#define A 5
int dummy_integer = A

... will be preprocessed as...

int dummy_integer = 5

... and the compiler will read this statement.

However, if I remember good, you can always overwrite a preprocessor directive as follows:

#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").


HC-05 can not use lower pins only 8 and higher

From the official SoftwareSerial Site: https://www.arduino.cc/en/Reference/softwareSerial (Section Limitations)

  Not all pins on the Leonardo and Micro support change interrupts, so
  only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15
  (SCK), 16 (MOSI).


Yes, you will need to physically cut the trace to use the on/off feature. This is common on development boards. It could be done with a jumper but that would add cost and/or require a larger board.

You will see on the back of the board there are 2 large pads connected by a thin trace. You can use an exacto knife to cut the trace. To repair the cut you use a blob of solder to bridge the gap between the pads.