How can I make a power button for my project powered by a USB powerbank?

You could put the microcontroller into sleep-mode. Then use a button (connected to one of the interrupt pins) to wake it up.

But depending on what Arduino board you are using, and what other sensors etc you've connected to the board, this might not save that much current. For example on the UNO board the usb-to-serial converter is always on, so while your MCU is sleeping and trying to save power, the usb-to-serial continues to draw current.

But adding a switch to a usb-cable would be a lot simpler.

PS doesn't the powerbank have an on-off switch?


Turns out that, in the Cortex Mx processors, interrupts don't work the same way as older 8- and 16-bit Arduino-style chips work.
As far as I can tell, there's only one ISR that's connected to the pins. In that routine, you've gotta check the status of the pins you are monitoring and set a global variable accordingly.
I'm not sure this is the only way to do it (seems kludgy), but it does work and it looks like it can scale to any number of pins. I'm using only two.
Here's my demonstration code if anyone is having the same problem. I put the debouncing code in the ISR. I know that's probably not best practice, but it doesn't take a lot of cycles and it's a lot easier than putting it in the loop.
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile bool frontDoor = LOW;
volatile bool backDoor = LOW;

void isr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 50)
    {
        int fds = digitalRead(FRONT_DOOR_SWITCH);
        int bds = digitalRead(BACK_DOOR_SWITCH);
        if (fds == HIGH) frontDoor = HIGH;
        if (fds == LOW) frontDoor = LOW;
        if (bds == HIGH) backDoor = HIGH;
        if (bds == LOW) backDoor = LOW;
        last_interrupt_time = interrupt_time;
    }
}

void setup()
{
    Serial.begin(115200);
    while (!Serial);
    Serial.println("in setup...");
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), isr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), isr, CHANGE);
}

bool lastFrontDoor = LOW;
bool lastBackDoor = LOW;

void loop()
{
    if ((frontDoor == HIGH) && (lastFrontDoor == LOW))
    {
        Serial.print("fd+");
        lastFrontDoor = HIGH;
    }
    if ((frontDoor == LOW) && (lastFrontDoor == HIGH))
    {
        Serial.println("fd-");
        lastFrontDoor = LOW;
    }
    if ((backDoor == HIGH) && (lastBackDoor == LOW))
    {
        Serial.print("bd+");
        lastBackDoor = HIGH;
    }
    if ((backDoor == LOW) && (lastBackDoor == HIGH))
    {
        Serial.println("bd-");
        lastBackDoor = LOW;
    }
}


It's a bit hard to see, but

DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like

DHT11 dht;

where dht is an instance and you can use that.

Than in

DHT11.read(DHT11pin);

you should replace it by

dht.read(DHT11pin);


Best practices for really long distance sensor deployments

There's as many ways of solving your problem as there are of skinning a cat (those poor poor cats - always getting skinned... ;) )

As you have already noted there are two basic solutions: wired or wireless.

Wired does have one major advantage that you haven't really touched on (only mentioned in passing) and that is power. With a wired solution you can provide power over those same wires so you don't need to worry about solar panels, batteries, whatever. But wires can break, yes. So they're not ideal. But then what is?

With wireless you then introduce the major problem of power. Solar panels are one possible way of getting power, though they are expensive, and you need to "over spec" them to charge batteries so you continue to have enough power for the times when is little or no sun.  Complementing them with wind power is also an option to boost the battery charge when its windy. It all adds up to very expensive sensors though.

A compromise might be to consider both options together.  Turn the sensors into small clusters of sensors that are near by with a base station for those sensors that both gathers and stores the power needed for them, and performs the wireless communication. The sensors would then be wired to the base station.  Your wires are then shorter, and your power is more centralised.

But what to then use for the wireless itself? Well, there it's really all down to frequency.  There's two basic gropings here:

High frequency - 2.4GHz - is great at unobstructed communication. That's the frequency your WiFi works on, and as you probably know it's great if there's no walls in the way. Add walls and the signal drops off considerably.
Low frequency - 433MHz - Far far better at penetrating walls and things but much less bandwidth.

I have had distances of hundreds of meters using a 2.4GHz nRF24L01+ module with power amplifier and antenna. That's in open air with (pretty much) line of sight. Indoors the range is much much shorter. Put buildings in the way and your hundreds of meters drop down to tens of meters.

So if there are obstructions you're pretty much going to want to use the 433MHz range (there is another frequency, which is different depending on where in the world you are - 868MHz or 915MHz, so we'll ignore that for now).

There's plenty of modules around that run at 433MHz, some better than others. There is, however, a new standard emerging now that is designed specifically for this kind of thing - long range, low bandwidth, just for sensors (as part of the IoT bandwagon) called LoRa (short for Long Range) which aims at distances of 15km using very small amounts of power (tens of mA) which is ideal for solar powered operation. It also can use the 868/915MHz region as well.

The final option that you touched on without knowing it is that of a mesh. This is where all the nodes form a network and each node is capable of relaying data from other nodes to get to their destination. Kind of like how the internet works. There are some mesh libraries available for some radio modules on the Arduino, but I have no idea how good or reliable they are. The best ones would be completely self-healing with auto-discovery - add a node and the whole mesh works out how to route messages to the destination node; remove a node and the mesh works out new routes to pass the data around the hole it's created.

Creating a good mesh stack is not child's play, so you would want to research it properly and find the best modules with the best library support if you wanted to take this route. That's why LoRa is taking off - it's so much simpler to get wide coverage without the need of complex mesh systems.


I have the code printing the data I need but don't know how to connect the data on ESP8266 IP web server

The esp-01 is in AP mode. To access the web page on the IP address 192.168.4.1 show in Serial Monitor you must connect to the WiFi network created by the esp-01.

If you click the WiFi icon in the bottom right corner of Windows, you will see a list of WiFi networks.


Is supplying 5V from both external 5V and USB harmful?

No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

Update, my previous answer contained the following paragraph, which is not related to your problem

  But you should take care of some things.

  Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
  source.
  Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
  switching PSUs. Those provide a AC voltage of half your line voltage
  to DC ground (only with 0.3 to 0.7 mA, but enough to cause
  disturbances on your signals at 55 volts in the US or 115 V in the EU)
  If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
  VGA-port-screw) to your arduino's PSU's ground directly, to prevent
  leakage currents from the Y-capacitors wandering around in your
  circuitry.

Update according to your enhanced question

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.


How to code 4 relays to go off in intervals and not in sequence?

Here is some code that might help you; leaving out the temperature and humidity stuff:

// constants
// number or relays
const int relays = 4;

// pins for the relays
const int relayPins[] = {2, 3, 4, 5};

// relay cycle times
const unsigned long relayTimes[] = {
     5*60*1000, // 5 min
     60*60*1000, // 1 Hour
     2*60*60*1000, // 2 hours
     12*60*60*1000 // 12 hours
  };

// relay on durations
const unsigned long relayOntimes[] = {
    1000, // 1 second
    10*1000, // 10 seconds
    60*1000, // 1 minute
    60*60*1000 // 1 hour
  };

// timing for the relays
// storing the last time
unsigned long relayElapsed[] = {0, 0, 0, 0};

// state of each relay
int relaystate[] = {0, 0, 0, 0};

// helper function to process each relay
void relay_helper(unsigned long t, unsigned long &elapsed, int pin, int &state, unsigned long delta, unsigned long ontime)
{
  // depending on the state we do different things
  switch (state)
  {
  case 0: // state 0 is off, wait until time has passed
    if ((t-elapsed) > delta)
    {  // then
       state = 1; // set the state to on
       elapsed = t; // reset the time
       digitalWrite(pin, HIGH); // turn on
    }
    break;
  case 1: // state 1 is on, wait until time has passed
    if ((t-elapsed) > ontime)
    {  // then
       state = 0; // set the state to off
       elapsed = t; // reset the time
       digitalWrite(pin, LOW); // turn off
    }
    break;
  }
}

void setup()
{
  unsigned long start = millis();
  for(int i = 0; i < relays; i++) // for each pin
  {
    pinMode(relayPins[i], OUTPUT); // set it to output
    digitalWrite(relayPins[i], LOW); // and turn it off
    relayElapsed[i] = start;
  }
}

void loop()
{
  unsigned long tm = millis();
  for(int i = 0; i < relays; i++)
  {
    relay_helper(tm, relayElapsed[i], relayPins[i], relaystate[i], relayTimes[i], relayOnTimes[i]);
  }
  // do other loop stuff
}

The basic idea is that the only way to do thing simultaneously is to do things in sequence really fast, we can't use delay() because it is a busy loop, nothing else can happen during delay(), so we keep track of the time and when it is time to turn on the relay we turn it on, and when it is time to turn it off we turn if off.

Another option would be to write a class per relay:

class Relay
{
public:
  Relay(int pin, unsigned long delta, unsigned long ontime);
  ~Relay();

  process(unsigned long t);

private:
  unsigned long delta;
  unsigned long ontime;
  unsigned long last; // elapsed
  int pin;
};

Then one can create an array of these:

Relay[] relays = {
    Relay(2, 5*60000, 1000),
    Relay(3, 60*60000, 10000),
    Relay(4, 2*60*60000, 60000),
    Relay(5, 12*60*60000, 60*60000)
  };

put the code from setup into the constuctor, and the code from the helper into process, and finally call it in a loop in loop.

The first way shown is how one would do it without C++ classes, and the second way is with them!


Master Reader/Slave Sender with Distance Sensor

Your code has some flaws, that I will address here:

The main problem, that you see here, is that you only let the slave write data into the buffer, when it is receiving data. But you never send data to it. So there is never anything in the buffer.

In the slave code you have

void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {

  Wire.write(Distanceincm);
  Wire.write(count);
  Wire.write(contor);
}

Besides the unbalanced parentheses (which let's me think, that this might not be the actual code, that you are running currently), you are writing to the buffer only inside the receiveEvent(). That only get's called, when the master does a Master-Write transmission (via Wire.beginTransmission() and Wire.endTransmission()). In the master code you are only using Wire.requestFrom(). If you want to send back data on a request, you need to use the onRequest callback of the Wire library. You need to set the appropriate callback function:

Wire.onRequest(onRequestEvent);

And then write data inside that callback function:

void onRequestEvent(){
    Wire.write(...)
}

I will explain how to write the values correctly in a different point below.
In the receiveEvent() function you want to loop through all received bytes but the last. But you are not doing anything with the data. You aren't even reading it. As your code currently stands, this line does not make any sense.
In your master code you are requesting data from the slave with the address 2. Your slave code initiates the Wire library with the address 4. From that point there should never be a successful I2C transmission, unless you have another slave on the bus with the address 2 (another point, where I suspect, that these codes are not exactly the ones used for the test).
In the master code you are using

while(Wire.available())

because the slave might have send less data, than requested. You are testing, that the number of available bytes is not zero. But then you are reading 3 bytes without checking again, which means, when you received 2 byte, you still would try to read 3 bytes, which cannot give good results.

The condition should be Wire.available() >= 3, to check, if at least 3 bytes are in the buffer, because you are reading 3 bytes from it. But also the loop does not make much sense to me. As you have a binary protocol here, how would you treat additional data (meaning excess data, send after the first valid data frame)? You want to receive 3 values per transmission and you are reading 3 values in one iteration of the loop. If there where more data in the buffer, you would be reading the next 3 bytes, throwing away the first 3 bytes. I don't think, that is what you want.

Instead use the return value of Wire.requestFrom(), which is the number of received bytes. Use it to distinguish valid transmissions, from those, which are too short:

uint8_t n = Wire.requestFrom(4, 3);
if(n >= 3){ // at least 3 bytes where received
    uint8_t value1 = Wire.read();
    uint8_t value2 = Wire.read();
    uint8_t value3 = Wire.read();
}

Any transmission, that is too small, will get ignored. Excess data in too long messages will also be ignored. Note, that I used uint8_t, which is an unsigned integer with 8 bits (1 byte) here for simplicity of that points logic. More about your data types and their implications on your code below.
For the to send datatypes on the slave you have int and long. int is a signed integer with 16 bits, long is a signed long integer with 32 bits. (I suspect you don't need a long for the distance, as ultrasonic sensors mostly reach only 3m, but that is up to you). In contrast the argument of Wire.write() is an uint8_t, which has only 8 bits. That call is used to put exactly 1 byte into the buffer, not more. When you are using

Wire.write(Distanceincm);

you are putting the least significant byte of Distanceincm into the buffer. The rest will just be thrown away (this happens at the cast from long to uint8_t). This works as long, as the value is between 0 and 127 (which is the upper part of the int8_t value range). With higher (or lower) values your received data will be garbage. Instead you need to write every byte of your data into the buffer:

Wire.write(Distanceincm  & 0x000000FF);
Wire.write((Distanceincm & 0x0000FF00) >> 8);
Wire.write((Distanceincm & 0x00FF0000) >> 16);
Wire.write((Distanceincm & 0xFF000000) >> 24);

With bitwise ANDing (&) of the hexadecimal value 0x000000FF, we are deleting all bits, beside the least significant byte (analog with 0x0000FF00 for the second least significant byte, and so on). Then we are shifting the corresponding byte to the position of the least significant byte (8 bits for the seconds least significant byte, 16 bits for the third least significant byte, and so on), which then gets used by Wire.write(). To better understand this, read about bitwise operators on the web.

You have to send both integer values in a similar fashion (though they both have only 2 bytes instead of 4).
Now that we are sending more bytes, we also need to receive and read all these bytes correctly. First we need to request the correct number of bytes. 4 bytes for the long value and 2 bytes for both int values --> 8 bytes. So you need to request 8 bytes:

Wire.requestFrom(4, 8);

Then you need to read these bytes into the corresponding variables:

long distance = Wire.read()
                | (Wire.read() << 8)
                | (Wire.read() << 16)
                | (Wire.read() << 24);

We are using the bitwise OR (|) to put the bytes together, shifting every byte to its correct position in the long value. In a similar way you are putting together the 2 int values.


In a word, no.

The Arduino uses a rather crude 10-bit ADC. If you feed it a small voltage reference, you can divide that small voltage into 1024 steps. (as you say, about 1.1mV/step)

If you feed the same small 1.2V reference voltage into a 12-bit ADC, you'll get 4 times as many steps for the same range. (about 293μV/step)

And, as mentioned before, the ADC's in Arduinos are not very good. They're slow, and not very accurate.

(To be technical, precision is how exactly you DESCRIBE your answer. A decimal reading using more decimal places is more precise than a reading with less decimal places. Accuracy is how close the measured value is to the actual value. If you're sloppy with your measurements but use lots of decimal places to write it down, and the answer is very far off, you have a precise but inaccurate answer. (e.g you measure something as 1.0000001 millimeters, but it's really 2.5 mm.

A 12-bit ADC is more precise than a 10-bit ADC, but it may or may not be more accurate. Given the crude nature of the ADCs in Arduinos, a dedicated 12-bit ADC is likely to be more accurate than built-in one.)


It can be done. Your Digispark has SPI pins, which are ISP pins. For the esp8266 there is an ESP8266AVRISP library for OTA upload to AVR. You can use the example of the library.

You must wire the SPI pins and ground together. Wire reset pin of Digispark to io 5 (D1) of NodeMcu. You should use level conversion, but esp8266 tolerates 5 V TTL (not recommended for long term). Do not wire the SS pin.


Arduino master/slave communication using RS485

First of all, your connection is just wrong, you should make the RS-485 bus as a straight line, with a 120 ohm resistor at the beginning and another one at the end. Each slave should tap into that line as close as possible to that line, look for datasheets and you will understand what I am talking about.

Second, you can use Modbus as a pretty good and easy to use communication protocol.


What's wrong? FastLED and WS2812B simulation works, physical build doesn't

Consider what would happen if your power supply is not powerful enough.  Depending on the number of WS2812B you are lighting at the same time you may be exceeding the current rating of your power source.  Using the following quote from this source:

... consider how much current your LED strip is going to pull. With every
single LED on at full brightness, each breakout board can pull about
60mA (20mA per color channel).

We can calculate for a string of 15 WS2812 set to full brightness it would take 15 x 60mA or almost 1 Amp of power.  People commonly source power supply which can handle twice the expected high current load.  So, in this case you would need a supply which can source at least 2 Amps
Also consider not using the Arduino's linear voltage regulator for large current loads.  Not only does it have current limitations but it is also not as effective as a switching power supply. Instead use a power supply of the correct voltage and capable current rating for large current loads.
Try lighting only 1 LED at a time in the strip and stick to one color at a time.  If this works it is likely your power supply is not capable of supplying the necessary current to operate your project as expected.


What will happen if I supply greater than 1.1V to analogue inputs if analogReference set to INTERNAL?

You will read 1023.

The limit of the voltage is not the reference voltage but the chip supply voltage - so 5v on a 5v board.


How do i run multiple functions simultaneously on a LCD screen?

Use the state machine model shown in BlinkWithoutDelay

unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

With this example, Second() is called only when the difference between "now" and the last time it was called is greater than secInterval. Likewise for Minute().

[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]

EDIT BASED ON UPDATED CODE SAMPLE

Issue 1:

In both your Minute() and Second() functions you have a sequence like:

lcd.setCursor(0, 0);
lcd.print(First_Digit);
lcd.setCursor(1, 0);
lcd.print(Second_Digit);
lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.

Issue 2:

At the start of the Minute() function, you have the following:

int First_Digit = 0;
  int Second_Digit = 0;

This means the variables First_Digit and Second_Digit are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as static so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:

static int First_Digit;
static int Second_Digit;

and similarly in the Second() function.

You're correct that digitalWrite() is not needed in your function as it is described. digitalWrite() is for changing a physical pin on the Arduino to a LOW or HIGH value (that is, a 0V or 5V voltage.) In the Blink without Delay example, ledPin and ledState are just variables to hold the pin identifier for the blinking LED, and the current state (LOW or HIGH) of that pin. Again, not necessary for your code, as you have described it.

SECOND UPDATE

Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the for loop in the Minute() and Second() functions, but it's unnecessary.

You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:

void Second() {
  static int second;

  second++;
  if (second>59) {
    second = 0;
  }
  lcd.setCursor(0, 0);
  lcd.print(second/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(second % 10); // Prints the remainder after dividing by 10
}

void Minute() {
  static int minute;

  minute++;
  if (minute>59) {
    minute = 0;
    // Probably want to increment an Hour counter here?
  }
  lcd.setCursor(3, 0);
  lcd.print(minute/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(minute % 10); // Prints the remainder after dividing by 10
}


MQTT - Can lastwill be sent to multiple topics?

The "Last Will & Testament" facility of MQTT is controlled by the server, not the client.

The topic and payload are specified when the client connects as part of the connection handshaking. When the client disconnects this stored information is published automatically by the server.

The specification only allows for one topic and payload to be set.

Of course, you can specify the same topic for many clients and give each one its own distinct payload, but you can't also have a unique topic for each client at the same time.

This is according to the specification - however that doesn't stop a broker implementing its own extensions to the specification to allow such things - but I know of no such extensions being implemented. But, given the open-source nature of many MQTT implementations (PubSubClient.h and Mosquitto, for example), there is no reason you couldn't extend the protocol to implement your own requirements (at the cost of compatibility with other systems of course).


How do i generate exact number of PWM pulses in arduino?

One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle, whichever is appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:

volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n (or to n if counting cycles instead of toggles).  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.


How do I connect an Adafruit headphone jack to an Arduino 101?

First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.

Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

simulate this circuit – Schematic created using CircuitLab

Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.


Arduino Compatible can mean many things, but most of the time it means that some company has made something they sell to a customer that supports development with the Arduino IDE.

The thing is that most Arduino Compatible units use the Atmel processors, but some use others too. Third party developers then make "board"-projects that you can add into the Arduino IDE.

Be aware though that you in some cases can run into issues if you dont do your homework, here are some of the issues you can run into:

Some "compatible" boards use different architectures, so even if you can do many things with the Arduino IDE, maybe some sensor libraries are not supported. (Might have to be hacked or updated)
Some "compatible" boards have different USB-circuits (if they have them at all)
Most of the boards you buy off aliexpress, banggood etc. do not come with instructions at all and some times they differ from the "original" design (might be better, might be "the same" or might be worse.).

I'm not trying to scare you off, but just my experiences. You can find a lot of fun things on those sites like clones of lilitiny with the AtTiny 85. One example is in my blog heer: http://mjelde.blogspot.no/2015/12/lilytiny-lilypad-attiny85-wearable-iot.html

The main issue with the clones I've had is that some times they differ in some ways that the first times will make you scratch your head. Like: ESP8266 is Arduino Compatible with the boards manager added ( https://github.com/esp8266/Arduino ), BUT: The input pins are not "correct" marked. So you should then add constants to "remap" them in your code.

Also the ESP8266 does only support 1V analog read, while many Arduinos support 5V. But you can "fix" this with an 16bit ADC (analog to digital converter). The ESP8266 only has 3.3V also, so you cant run sensors that "must" have 5V, without then giving them a different power circuit :)

The AtTiny 85 LilyTiny clone i bought in a pair of 2 from AliExpress works fine and works different than the rest of the Arduinos. Uploading to those for instance means you leave them disconnected and then you hit upload in the IDE. Then it says in the status window to connect it, which you then do.

Then it uploads. It has very few inputs, but it's very cute id say. Primarily it's made for wearable and of course it has a lot of short comings compared to a large arduino board. But you can of course use it to control RGB leds, etc.

Remember to always check specifications (3V vs 5V, how much analog read resolution can it handle, etc). There is the sensor vs board (some sensors work on both 3.3V and 5V, some work only on 5V, some only on 3.3V).

For going to 5V to 3.3V you usually use a voltage divider. Either you can buy pre made ones or you can make it based off three resistors and some math :-)


What's wrong with infinite loops inside loop()?

First, I will give you some unsolicited advise about your coding style.
Instead of writing:

PORTB &= B11111110;
...
PORTB |= B00000001;

you could write:

PORTB &= ~_BV(PB0);
...
PORTB |= _BV(PB0);

These are standard AVR idioms, and they make it clearer that you are
toggling the pin PB0.

Then, to answer your actual question, your delay loop does not work
because it got optimized-out by the compiler. This has already been said
in Michel Keijzers' answer, but let me elaborate.

All modern compilers are optimizing compilers. This means they can
change your code in whatever way they see fit, as long as the visible
effects remain the same. The effects considered visible are usually
I/O and access to variables declared volatile. Quite importantly, the
slowness of the program is not considered a visible effect for the
purpose of optimization. And if you think about it, it makes good sense:
if the slowness of the program were to be preserved, then any form of
optimization would be impossible. Thus, a loop that has no effect other
than slowing your program down can legitimately be optimized-out.

The solution to your problem is quite simple: if you want a delay, then
call delayMicroseconds(). Or maybe even delay() if you are OK with
its low resolution. On the other hand, if you need sub-microsecond
resolution, you can call _delay_us(), from the avr-libc. This function
(or rather, macro) provides single-cycle resolution. If you write

#include <util/delay.h>

...
_delay_us(1.375);

you get exactly what you ask for, i.e. a delay of 22 CPU cycles
(on an Arduino Uno clocked at 16 MHz). The issues with this
function are that it is AVR-specific, and its argument must be a
compile-time constant.

It has been suggested to you to write your delay loop using a volatile
loop counter. I strongly advise you against doing that, for three
reasons:

Doing so will force the counter to be allocated to RAM, thus
consuming a scarce and valuable resource for no good reason.
Incrementing a RAM-based 32-bit counter takes 20 CPU cycles. Add
to this the time required to test the end-of-loop condition and you
will realize that your delay resolution is way worse than that of
delayMicroseconds().
Your actual delay will depend on the clock frequency, and probably
also on the compiler's version, making your code pretty fragile.


Chances are the offset headers won't allow the shield to directly plug into a breadboard.

As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.


The simplest solution to that problem is to download the Time library and use the weekday() function:

int weekday(time_t t); // the weekday for the given time

Cheers!


İs there any way different way than GND's Arduino

Dario,

There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close.

Strip board and pin headers will help you here, try this: http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/


How to make 2 LEDs flash in a 5/4 Polyrhythm?

I generally calculate whether the led must be on or off, based on the current time.

//Making a 5/4 Polyrythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {
    // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
    // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
    bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
    bool led7on  = (millis()/750)%2!=0;
    digitalWrite (LED13, led13on);
    digitalWrite (LED7, led7on);
    delay(10);
}


Using Arduino as ISP and SoftwareSerial at the same time

I'm not really sure, but in the Arduino ISP example there is an if that looks if the ISP is in program-mode. You could try adding in the else statement of that if the Software Serial part.


Arduino compiler uploading last saved version of sketch, not current

I haven't tried it but it would be an easy experiment to make on some throw-away code.

However, do note that saving before compiling or uploading is optional in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited preferences.txt file. That might be the key to what you observed.

Update:
In that case, including the pre-defined macros __DATE__ and __TIME__ (of the pre-processor run) and __TIMESTAMP__ (of the file's last modification) in a "Hello" string can help debug this.

These pages list the standard, and common predefined macros implemented in gcc's pre-processor.
Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.


MKR 1010 disconnects COM-port on each upload

This was due to using a virtual machine (VMware) which apparently doesn't handle the MKR board COM-port so well. Moving the development environment to the host solved the problem. It still disconnects the COM-port after upload but then consistently reconnects to the same COM-port and that's good enough.


What Minimum Value Can I Measure With ACS712 30A Current Sensor?

That model has a sensitivity of 66mV/A which means for every 1A of current passing through it outputs 66mV.
The Arduino's ADC when running at 5V has a resolution of (5/1024) 4.88mV per LSB.
That means that 4.88/66 gives you 0.074 - or 74mA per LSB.
Since 1LSB is considered to be in the noise area of the signal you can expect the minimum usable value to be double that - 148mA
Which is pretty useless for measuring currents in the mA range.
You would get better results with the 5A variant, but still not great.


add ID number to the feather m0 bootloader (flash)

This is quite an easy fix, actually.

The problem here is the compiler doesn't think the const is used for anything - so it (quite rightly) throws it away.

All you need to do is tell the compiler that it's used and all should be good:

__attribute__((section(".myid"),used)) const unsigned long ID = 0xdead1234;

And when you compile:

build/.elf  :
section             size         addr
.vectors            0x40          0x0
.text             0x18d4         0x40
.data               0x5c   0x20000000
.bss               0x34c   0x2000005c
.id_sec              0x4       0x1ff8
.ARM.attributes     0x28          0x0
.comment            0x80          0x0
.debug_frame        0x68          0x0
Total             0x1dd0

Properly, though, you should make some more changes to the linker script to properly isolate those 8 bytes of flash (though you don't have to).

You should reduce FLASH by 8 bytes.
You should include the FLASHID length in the __sketch_vectors_ptr calculation.

That's:

MEMORY
{
  FLASH   (rx) : ORIGIN = 0x00000000, LENGTH = 0x1FF8 /* First 8KB used by bootloader */
  FLASHID (rx) : ORIGIN = 0x00001FF8, LENGTH = 8
  RAM    (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */
}

And:

PROVIDE(__sketch_vectors_ptr = ORIGIN(FLASH) + LENGTH(FLASH) + LENGTH(FLASHID));

That way the compiled bootloader code can never be placed in the FLASHID area (not that it would at the moment, but if a new version of the bootloader were released that used 100% of the lower block of flash it would conflict).

Of course, if all you need is something unique to identify the board with, all AVR and SAMD devices that have built-in USB support have a unique ID number. This is intended to be used as the Serial Number for the USB, but could also be used for a MAC address for Ethernet (or for portions of it anyway) or other unique "node" addresses.


Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).

There are two ways of entering the bootloader:

Wipe the flash with the ERASE button (or trigger from 16U2).
Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.

You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.


Reset Arduino by connecting vcc and gnd?

That is wrong. That is very, very wrong. That is one of the worst things you can do to a USB connection short of plugging it into the mains.

Do not even consider doing this.  Short circuits are never a good idea.


Power LED Matrix With LiPo Battery & ESP32

The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.
Check your dev board specifications on how much power you actually need to supply to the Vin pin. The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended). Your dev board regulates the 5v to provide that amount to the chip.
Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.
Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.
If you are using the FastLED Animation Library, I would recommend setting a power limit using set_max_power_in_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.


WCH is the manufacturing company that first produced the CH340. They are Chinese.


Problem with connecting ESP8266 to arduino

I had the same problem. I used SoftwareSerial library, so you should set baud rate as 115200 for communication with esp8266. It might look like this:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

It helped in my case.


Stacking adc's when making an midi controller ( lots of potmeters)

These ADC's use the SPI protocol. Luckily the Arduino has one onboard.

With each ADC you get 8 channels (thus inputs). Since you need more than one SPI device (ADC in your case).

With SPI you can chain multiple SPI devices to your SPI port of the Arduino. To select which is active you use the Chip/Slave select signal. This is a separate GPIO you can define yourself. Read more about SPI to read details.

For 50 inputs you need 50 / 8, rounded up is 7 ADCs. This means also 7 CS pins. Thus in total you need 3 (for SPI) + 7 = 10 pins. I hope you have that many left.

About 'stacking', just put the ADC's on a breadboard and wire them according to the SPI protocol.

See also Arduino Reference SPI


Selling a product using Arduino microcontroller or bootloader

The Arduino hardware is released under the creative commons license.

https://www.arduino.cc/en/Main/FAQ#toc3

"which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license"

It's possible for someone to retrieve the instructions from the MCU but they would be looking at assembly rather than the c code you wrote your sketch in.

This is a similar question and answer:
https://electronics.stackexchange.com/questions/67030/can-arduino-be-used-in-commercial-products


Change Digispark clock speed, run at low voltage?

You can set the clock prescaler at run time. For example:

#include <avr/power.h>

void setup()
{
    clock_prescale_set(clock_div_8);
    // etc...
}

More details in the documentation from
avr-libc.

Note that with this method your Digispark will still be overclocked when
booting, so it might not be 100% reliable. But it will be overclocked
only for a very short time.


How can i interpret this macro for a given x value ?

As normal. First expand the macro, and then worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.


you might want to consider timed routines or interrupts.

For timers https://playground.arduino.cc/Code/Timer1 or similar can help.

When using interrupts be sure to be minimalistic because atmegas do not behave well when interrupts take too long to process.

About menus there are several, most of them dynamic and some requiring user display + nav code.

This open-source menu lib (https://github.com/neu-rah/ArduinoMenu) is static, that is good for bigger projects because it stores a lot on flash.

(-) you can not change menu at runtime (however it support value fields)
(+) requires no user code base
(-) setup involves several parts (inputs/output)
(+) non blocking polled mode. Just call the poll function on your code loop, the menu will just return if it has no input or output
(+) supports a lot of display devices, including i2c lcd
(+) supports encoder (interrupts (PCINT) or timed driver)
(-) atmega2560 interrupts (PCINT) only on 3 ports, PCINT might require pin mappings (not sure), but if needed the PCINT library examples can print one for you.


Serial broken into two shorter shorter strings

I guess you are sending 5 and have the line ending set to newline only. Then everything is correct and as expected. You see 2 bytes, that are transmitted. Serial.print() will cut out the leading zeros of the byte, so all other digits before that are just zero.
The first byte is the character 5 encoded in ASCII (53 is the decimal representation of the ASCII value here). The second byte is the newline character \n, which marks the end of a line or the end of the data message (depending on the interpretation of the data). If you don't want to send the newline character, select Nothing for the line ending (My Arduino IDE is in German, so I don't know, what exactly is the term in the english version here, but you need to set it for not using any line ending).
As it seems, that you don't know that currently: When you write a number into the serial monitor, you are not sending the direct binary value of that number. You are sending the ASCII representation of the individual digits. ASCII is a system, where the values of a byte represent a character. That includes decimal digits, the alphabet and some special characters. So when you type "255", you are not sending 0b11111111 (1 byte with all bits set --> decimal 255), you are sending 3 bytes with the ASCII byte value for the characters 2, 5 and 5. You can read the byte values for all the characters in tables, just by googling for "ASCII" and looking at the images found.


Physical dimensions(size) of the new MKR1000 board?

If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.


What is the best way to configure a bidirectional, open collector data pin?

If the other end of the link has the same signal voltage as your
Arduino, you can simulate an open collector with a single pin:

digitalWrite(pin, LOW); pinMode(pin, OUTPUT); sets the pin to output
an active low signal.
pinMode(pin, INPUT_PULLUP) sets the pin to input mode, or output
passive high which, in open-collector mode, is the same thing.

Note that in the first case the order of the commands is important: on
AVR microcontrollers, if you set the mode to OUTPUT before writing
LOW, the pin will for a short time output an active high, which is
forbidden in open-collector mode. I don't know how other MCUs would
behave in the same situation though.

Edit to address Ignacio Vazquez-Abrams’ comment: An open-collector
bus needs a pullup resistor on each data line to function properly. If
that pullup is already provided by your keyboard, or your cable, then
you should use pinMode(pin, INPUT) to accurately emulate an
open-collector output on the Arduino side. Otherwise you have to provide
that pullup, either as an external component or by using the internal
pullup of the MCU. Beware that the latter may be a little bit weak,
depending on your data rate.


Why does the Leonardo take 8 seconds to restart?

That's the firmware waiting for a programming connection. If you want alternate behavior them burn SparkFun's ATmega32U4 firmware to it. One press of Reset will reset the device, and two presses will put it into programming mode.


You could try using analogReference(INTERNAL);, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.


Unexplained behavior of char array after using `deserializeJson`

When you pass a char* input to deserializeJson(), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.
In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

'\0' are inserted at the end of each string
Escaped special characters (like \n) are unescaped

Example:
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);

After executing the line above, the input variable probably contains something like: "hello\0world\0".
You can find more details in the documentation


What is the name of this chip on Arduino Mega ? I am not finding its datasheet 56 TI MSP?

There is only one 8-pin SMD IC on the top side of the Arduino Mega 2560.

From the schematic
it appears to be the "LMV358IDGKR" a TI dual op-amp used for two separate functions on the Mega.

Selecting power source - VIN vs USB.
Illuminating the built-in "L" LED (on D13) without loading PB7


Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read its datasheet and so you can get a guess on how it should work:

attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
attach the LED to the terminals LED+ and LED- (remember the polarity!)
attach a transistor to pull down the pin DIM
send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)

EDIT:

How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done


If the pavement is black, you could detect snow by infrared reflectivity. You might detect wet by resistivity. That leaves ice. Reflectivity might work there, too, at a different threshold. You'd need to experiment.

Another possibility might be a short-range sonar. If the measured distance changes, something is there. Ice would probably read as nearer. You'd probably need to average a number of measurements to increase the measurement resolution; you care about very thin ice coatings. Snow might well read as no return - but again, experiment.

A combination of the reflectivity and sonar might be the most reliable.


LM335Z temperature sensor gives very varying values

According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.

You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).

In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.

Update:
I based my connections description on this diagram

, from this datasheet. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.

I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.


RadioHead library nrf24 sending and receiving struct data problem

Your problem is that you are working with pointers.  You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that.  Which of course won't work.

Instead you need to send the content of the memory the pointer points to:

nrf24.send((uint8_t *)strm, strlen(strm));

strm is already a pointer, you don't need to convert it to a pointer with & - that just confuses things and gives you a pointer to a pointer, which in this context is garbage.

A struct made up of String objects will not do what you think it does.  A String object does not contain the string itself. Instead it just allocates an external block of RAM (from the heap) using malloc() and holds a pointer to that memory. If you try transferring a struct which contains String objects all you will be sending is the data associated directly with those String objects, including the pointer to the string content, which is completely meaningless to the remote end.

Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.

Personally I would use a fixed size buffer. In this method you change your struct so it contains two character arrays with a fixed size. For instance:

struct DataHolder {
    char name[10]; // Room for 9 characters + NULL
    char skill[10]; // Room for 9 characters + NULL
};

Then copy your string data into it:

struct DataHolder data;

strncpy(data.name, "Fred", 10); // Maximum 10 bytes
strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

Now you can send the struct in its entirety:

nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

The data sent (and indeed the data held in the Arduino's RAM) will be:

Fred\0\?\?\?\?\?ClassA\0\?\?\?

Where \? represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and \0 is the standard C end of string NULL character (ASCII 0).

For receiving it's exactly the same. Use the same struct, and go:

struct DataHolder data;

int len;
if (nrf24.recv((uint8_t *)&data, &len)) {
    // Do something with data.name and data.skill
}

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:

struct DataHolder *data;
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

if (nrf24.recv(buf, &len)) {
    data = (struct DataHolder *)buf;
    // Do something with data->name and data->skill
}

Note the change from . to -> for the struct access since it's now a pointer.

Also note that you don't want your struct to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.


Can't send DHT11 temperature data to Xively from Yun

As long as I checked, this way of uploading data to Xively only works for up to tree pairs of name,data.

If you try with more pairs at the same time the response is "Done", but nothing happens. I finally divide the upload in groups of 3 parameters, and everything is Ok.

I saw your question yesterday when I was looking for a way to upload data to Xively from Yun. It was really helpful for me. Thank you.


Fluctuating readings of LM35 temperature sensor (+- 5°C) with Arduino UNO

The cause is the low sinking capabilities of LM35 output. This makes the output sensitive to EMI. Yes, the output output impedance is stated as 0.5 ohms but only for sourcing current. The sinking current is limited to 1uA which is easily achieved by the environment noise.

You need to add a low impedance load between LM35 output and ground, can be 200 ohm as the data sheet recommends for heavy capacitive loads but I wouldn't go that far, might be 1k or 2k to avoid self heating errors.

No software only solution can solve this error.


Why doesn't this work on a Mega2560 although it works on an Arduino Uno

You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.

An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:

void setup_rcTiming() {
rcOld = 0;
pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

PCMSK2 |= 0x0F;       // Four-bit mask for four channels
PCIFR  |= 0x04;       // clear pin-change interrupts if any
PCICR  |= 0x04;       // enable pin-change interrupts
}

and

ISR(PCINT2_vect) {
byte rcNew = PINK & 15;
...
}


If I understand your question, the main issues are that the axis don't match up, and z from the accel is not accurate?

with respect to the axis: just swap the values. Rotation math is self-consistent and "correct" in many different permutations. What makes it correct is the set of equations, not any single equation; So, copying equations from one reference frame to another will yield incorrect results even if they were correct originally.

your link addresses this difference:

  "Interpreting the diagram at left is a little tricky, since the tilt
  of the X-axis actually shows rotation around the Y-axis, and the
  angling of the Y-axis shows (negative) rotation around the X-axis."

  ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));

should work better for you

On the second point: accelerometers can't measure yaw, the "z" equation can safely be ignored. that isn't yaw it calculates. Calculating z from the gyro alone should fix your second issue.

Other considerations:

The gyroscope tracking can be made more accurate by using the midpoint rule in your integration
Your code is not integrating the gyroscope's signal with the best estimate of its last position (rx, ry, rz), instead it integrates the gyro with separate numbers (grx, gry, grz). In effect information from the accelerometer is discarded each loop and gyro drift is not corrected for.
Thanks for including those graphs with your code samples =] rotation math is extremely tricky, and graphs help a lot


OSEPP 16x2 LCD Display Turns On But Does not Display any White Boxes

It is normal that these displays start up with some lines displaying as all white (and others all dark). That's just how they look before they were initialized.
However, as mentioned above, you forgot to wire the data lines. Pins 7-14 from the display need to be wired to the Arduino, typically pins 4-11. But that depends on the configuration in your sketch. It may also work with only 4 lines, then you would connect pins 11-14 from the display to the Arduino pins 4-7 and configure the display to use 4-bit mode in your sketch.
That said, there are more wiring errors in your picture. The lower pin of your potentiometer is unused, and so like this it has no use (and you cannot control the contrast of the display, also making the text, if there is any, hard to read). The bottom pin of the potentiometer must go to pin 3 of the display (remove the line that is already there).


Is the Uno Vin pin protected by the voltage regulator?

If you look at the schematic you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).

So the same input-voltage of    7-12V applies to Vin.


Attiny85 microcontroller programming without arduino

Programming a bare ATtiny85 IC needs either another Arduino or an AVR programmer

Programmer $4-$7
Something like the Pololu AVR Programmer v2.1 can be bought for $7 and used with the free Arduino development software (IDE). I have used this to program an ATtiny85. This is what I would suggest, because a programmer is the most versatile solution.
 Even cheaper, a $4 USBASP

Arduino as ISP $4.50
I have used an old Arduino Duemilanove using the Arduino as ISP sketch as a programmer for an ATtiny85 but any Arduino with inbuilt USB and enough GPIO could be used. There are some low cost ATmega328P or ATmega32u4 based Arduino clones that would be suitable. A Nano v3 clone costs $4.50.

Development Board with USB $3
As others have commented, you can buy a "digispark" (just Google and click "shopping") for three or four dollars. This is essentially a breakout board with an ATtiny85, a USB connector and a soft-USB-capable bootloader pre-loaded onto the ATtiny85. You can program it with the Arduino IDE after using the IDE's board-manager to install Digistump's "core" definitions for the Digispark. It doesn't need another Arduino nor an AVR Programmer. I bought three on Amazon for $9 a month ago.

Since it is an Arduino-compatible development board, it doesn't really meet your requirement of "without Arduino" - but it might be the closest solution to what you have in mind.

Useful resources and inspiration:

ATtiny-Based Beginner's Kit
Twelve PWM outputs from an ATtiny85.

Yes, 12 LEDs individually controlled with just four resistors and four pins of an eight-pin ATtiny85 and and no other components!
I have no affiliation with the above site, I just think it is one anyone new to electronics with an ATtiny85  would find interesting.


What you try here:

rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};

is only valid in C++11. (Before that you can initialize an array like this only upon initialization.)

Besides, as pointed out by Pete Becker, you need to declare rp as an array rather than a single int.


nRF24L01 module using Mirf library was working and then stopped

Using the MIRF Library that I got from here, and then using this code to send

 Mirf.send((byte *)&command);
    while(Mirf.isSending()){
        }

and this code to receive

 if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();
else(){
}

I was able to get it to work


Building an adjustable low frequency PWM controller with Arduino

The ATmega328 in the Arduino Uno has a 16-bit timer (Timer/Counter 1) which can do PWM. It has a prescaler that can divide by 1024.  The lowest frequency that it can generate is about 0.12 Hz:

16MHz / 1024 / 65535 / 2 = 0.1192 Hz

We change the PWM frequency by changing the "top" value. For higher frequencies, lower the top value, and/or pick a smaller prescaler.

(And, really, what does 0 Hz PWM even mean?!? :-)

The duty cycle can vary from 0-100%, with the resolution changing with the specific frequency you generate.

As for the high-voltage... use a motor driver, or darlington, or hexfet, or whatever...

I'm confused as to why you're reading the frequency. With the 16MHz crystal, you set it and you get what you asked for (within the crystal tolerances, temperature, etc.)

At least, that's how I think it works.
Good luck!


Code flow execution between loop() and timer interrupts

The timers starts when it is enabled. Either explicitly or via one of The calls to timer functionality.

Once the interrupt fires, current execution is preserved and the isr execution starts. Once you exit the isr, the loop execution resumes from where it pauses

Yes, if your use fires too frequently or takes too long to execute your loop may never gets executed.


Is it possible to use FrSky D8R-II Plus 8ch 2.4Ghz ACCST Receiver with an arduino Uno?

I've used plenty of receivers like this with arduino.

The operating current is not really an issue; It is drawing power off of the 5v line, not the digital pins, which is capable of 100mA. In any case they usually have an extra "bat" line that you could plug in to a BEC from one of your speed controllers, and then just connect signal and ground lines to the arduino.

pulseIn works, but not ideally (especially for quadcopters). reading with pulseIn tends to have quite a bit of noise, and runs slow. Those receivers pulse around 50-60Hz, so reading those signals with pulseIn (which has to wait for the signal to finish) will take too long. I say "too long" because in all the open source quad copter programs I've looked at the sensor-read/stabilize update loop needs to run at 100 Hz or more.

What you need to use is the interrupt functionality of the AVR. That way you can detect the time between changes in state of the input pulse without causing the rest of the program to stop. This can get somewhat complicated so I'm not going to write a tutorial here. I recommend you research it yourself and ask new, specific questions here if you have any.

It doesn't magically fix everything for you though; the Uno only has 2 external interrupts. I think most arduino based quads use arduino megas or Leonardos, which have more. I know the APM 2 board has a separate chip converting those 8 single channel PPM signals into a single 8 channel PPM signal that goes into the main controller, despite the fact that it is a mega.

You can look into Aeroquad and Multiwii for inspiration. ArduPilot is open source as well but their code is messier, which makes reading it much more difficult. I don't think it is impossible to use an Uno, but it will be difficult.


Voltage issue on an esp32 wvroom 32D development board

Try measuring the voltage against a different ground pin? I had a similar problem and discovered the pin next to the 5v input pin wasn't actually ground. Not sure why this would affect sketch uploading though..


Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.

struct row_t {
  ... column fields ...
};

uint32_t row_addr = TABLE_START_ADDR;
row_t data;
data.column = value;
...

eeprom.write(row_addr, &data, sizeof(data));
row_addr += sizeof(row_t);
...

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).

Cheers!


the newline characters from println (\r\n) stay in the serial input buffer and you read them with Serial.readStringUntil(':');. then the string is not "servo" but "\r\nservo"

if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them


From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'.  The loop section should look more like:

if(Serial.available()){
    state = Serial.read();
    if(state == '1'){
           Make motor move;
    }else if(state == '0'){
           Make motor stop;
    }//end of elseif
}//end of if


The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.

Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the carrier frequency of the PWM).

Can you do it from LabVIEW? Who knows? I have never used it.


Best way to assign value to lot of variables

The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:

192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:

brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.

String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:

String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

Cheers!


Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

  Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

  Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation.
The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.


You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.

If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.

What can you do? Well, two things:

Use an adaptor that requests enough current for your needs (may be hard to find)
Power your circuit separately using another power source.

Of the two I would suggest external power.


If you're just running lines to the buttons, you won't need to power the remote from the arduino.  You could just let it keep the internal batteries.  But it would be possible to wire it up for power as well.

As a learning project, you could just take it apart and see if you can access the button contacts.  See if the contacts are split.  If so, shorting one side to the other should count as a button press.  But the details have nothing to do with an arduino.  They would depend on your specific remote and how it's constructed.

If your purpose is really to control the TV (rather than learning about the remote and fiddling with it), it will be much easier (and probably cheaper) to blast the IR without involving the remote at all.  A single IR transmitter and a library would work in most cases.  As an example: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html

P.S.  By coincidence, Adafruit just posted an updated guide to IR library use on Arduino.  https://learn.adafruit.com/using-an-infrared-library/overview


Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.

The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).

Try comparing checksum to data_sum % 256.  If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.


I have this error too when I typed a wrong password to connect to the green 'osjs' interface.
have you changed the password of your board ?
have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ?
hacve you cleared your browser cache / test with another browser ?


xbee communication not established between arduino

Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.

Not sure if this will help ...

  Arduino is connected to PC USB... RX>TX TX>RX

1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.

  however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino

2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU

You could try this for better diagnostics

    void loop() {
while(Serial.available() > 0) {
           msg=(char) Serial.read();

      Serial.print("data arrived from xctu: ");
      Serial.print(msg);
      Serial.println();

           if(msg=='H') {
               digitalWrite(led,HIGH);
           }
           if(msg=='L') {
                digitalWrite(led,LOW);
           }
delay(1000);
}
}


Arduino - My problem is when the condition is greater than 900.00 it will continue the loop and do the code below once

setup(){ ....
......
}
float old_reading=0;
loop() {
float reading = analogRead(LIGHTSENSORPIN); //Read light level
// ... do this always (maybe empty)
// in your code it is LED shining and printing
if ((old_reading<=900) && (reading>900)) {
   // ... do this just just once when reading goes over 900 up
   // in your code it is manipulating motor
   }
old_reading=reading;
// ... do this always , but after special part (maybe empty)
// in your code it is just delay
}

So on begining old_reading is just zero, but being declared outside loop, it keeps its value between different runs of loop.
the if (condition) does not hit, as reading is less than 900 (if it starts with more then 900, see next part)
the end with old_reading=reading; makes old_reading to be the last known value of reading
when reading goes Greater than 900 for first time, the old_reading is Less or Equal 900 (as it was the last value of reading before it crossed 900 up.

so the if (condiotion) is true and you start moving motor

then (on the end) you set old_reading=reading; and old_reading is also larger then 900

while reading stays over 900 in next loops, the old_reading does so, and therefore the if (condition) does not hit - (old_reading<=900) is not true

when reading falls down 900 or lower, the if(condition) also does not hit, but after that the old_reading=reading; makes old_reading less or equal 900

and so we are at the start again, skipping the part after if(condition) until reading gets Greater than 900 (then we run motor, set old_reading to something greater than 900 and we already was here and know, how it works :)


Formula / calculation of the function random() / randomSeed()

The underlying random() function isn't part of the Arduino code. It's actually part of avr-libc. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).

It's open source though. You can get information about it here:

http://www.nongnu.org/avr-libc

If you look down the page a short way, you'll find the "Source code and documentation" link.

The random() function is under libc/stdlib/random.c. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.


Multiple sensors connected to Arduino MEGA 2560 Serial ports

Your serial buffers and moving in and out of phase, which is distorting your display.

Try something like:

void setup() {
  String sensor1;
  String sensor2;
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    sensor1 = Serial1.readStringUntil('\n'));
  }

  if (Serial2.available()) {
    sensor2 = Serial2.readStringUntil('\n'));
  }

  Serial.print(sensor1);
  Serial.print(sensor2);
  Serial.println();
  delay(1000);
}

I would also recommend the method suggested by @Majenko in his comment below your question.


I would suggest using a 12V controller, and then adding a 3.3V switching regulator using the 12V supply. That would be 2 off-the shelf components and you're done.


The product page you linked to has modules of different types.
Make sure you have uncommented the matching type in the this section of the example:
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

Also makers of these boards sometimes label them incorrectly or describe them incorrectly when selling them.  If you're unsure what you have, try them all.


As Matej already mentioned, use:

strcmp(a, b) != 0

If you compare a and b, what you are actually doing is comparing two pointers (to the text characters). These pointers a and b are stored at different locations in memory, although the content itself can be the same.

See it as this:

a   memory location 0x12345: "Bang"
b   memory location 0x1234A: "Bang"    (5 memory locations further)


Why do I keep blowing up Nanos when I solder them?

My advice would be not to solder directly to the Nano pins.  Instead, use the appropriately sized DIL socket, and solder to the pins of that instead.   Then plug in the Nano once the soldering is complete.


One approach that I have used for similar purposes is to generate the appropriate header files (or module or whatever) from a simple text file for all the required uses.
Since you already know python this should be pretty easy. Quick "proof of concept" follows. (Warning: I barely know any python.)
One downside to this is that you have to remember to regenerate the header/module each time you update the enum (keys or values) - don't forget to recompile for the C++ part. If you have a build system, it is best to integrate that code generation step into it.
A variation of this is to parse one of the language's source code to extract the definition and output it in a format suitable for the other. That is generally much harder to do though if you want to make it robust.

robot.enum
UP    1
DOWN  2
LEFT  3
RIGHT 4
JUMP  5

enum_generator.py
def python_enum(filename):
    with open(filename, 'w') as w:
        w.write('class Robot(Enum):\n')
        with open('robot.enum') as r:
            for line in r:
                parts = line.split()
                w.write(f'    {parts[0]} = {parts[1]}\n')

def cplusplus_enum(filename):
    with open(filename, 'w') as w:
        w.write('#pragma once\n')
        w.write('enum Robot: int {\n')
        with open('robot.enum') as f:
            for line in f:
                parts = line.split()
                w.write(f'  {parts[0]} = {parts[1]},\n')
        w.write('};');

python_enum('robot_enum.py')
cplusplus_enum('robot_enum.h')


I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write

You are running at 400000 bits per second, or 200000 per half second you say it takes.
You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
200000/1000 = 200 bits per transaction.
Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.

That makes 50 bits per transaction.

So yes, half a second to write then read it all is perfectly possible.

The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.

A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.

So for a read and write it's 38+48 = 86 bits.

Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.

At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.

If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

So not a bad guestimate of 25% transmission in my original surmising.


Whats the function of the resistor between MCU and its Resonator in Arduino Mega?

That resistor limits the drive through the crystal.  If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).

See good instruction PDF here, section 2.1.


How to connect a card reader (extracted from printer) to arduino uno

I can pretty much categorically say you won't get it working.

I have a similar board here with the same SMSC (now owned by Microchip) chip on it.

The interface is USB plus some other signals.  I have managed to identify the USB portion of the interface on mine, but not the other signals.

The SMSC chip has the option of using an external ROM chip to store its program, and Dell love to do that.  So, it has a custom firmware which means it doesn't get recognized by my computer without Dell's specific drivers installed.  So it's useless.

There's a very very slim chance you may get it working with a USB Host Shield, but unlikely - and at the end of the day, what's the point?  It's just an SD card reader.  Wire an SD card socket direct to the Arduino and save yourself both the headaches of trying to work it out and also the massive pointless expense in buying the hardware you'll need to do the interfacing.


Floating power supply for Arduino - Is it still connected to the USB ground?

Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

Yes.

  Would it be ok to remove the jumper connection between UGND and GND?

No. I don't know quite why they provided that jumper. I can see no scenario in the datasheet where it suggests the two can be separate.

  Or should I try something like a linear USB isolator like this?

If you want it to float then you need galvanic isolation on all USB pins. The device you link to will do that for you. There are others as well.

Personally in these situations I prefer to use a wireless communication system so there is no worry about grounds and isolation - it's naturally isolated.


Arduino app hangs on upload for all boards

I tried that once. A very common reason for this problem is a different cable. Some USB cables are not suited for uploading the data to the Uno board.

Have you brought a new cable? If so, switch back to the old one. It may not look like it makes a difference, but it requires attention.


You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.

But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.


Mobile phones use the mechanism of assisted GPS.

In contrast to your Arduino U-Blox module it uses the cell tower data your phone can provide to determine your location. This is especially helpful to get a quicker first fix and to get a fix even when you have poor satellite signal conditions.

That said, this will not be possible using only your GPS module connected to your Arduino.


Allocate it in the heap. Don't forget to free it after.

#include <stdlib.h>
#include <string.h>

 ...

char *c = getFloat(val, valid);
use(c);
free(c);

 ...

char *getFloat(float val, bool valid){
  if(valid){
    char stringFloat[16], *ret;
    dtostrf(val, 10, 8, stringFloat);
    ret = strdup(stringFloat);
    return ret;
  } else {
    Serial.print("No Float");
    return NULL;
  }
}


Arduino Nano (3.0) Use an USB Bluetooth stick

Interfacing an Arduino with USB is already VERY hard. USB does not use the same Serial as protocol so don't connect it to Tx and Rx. The only way to interface an Arduino and an USB device is trough a USB shield, which is quite complex already.

Just for you information. USB uses 5V so no voltage divider is needed to reduce it to 3.3V. A voltage divider is pretty much 2 resistors in series where the original voltage goes in one end, the output voltages is between the 2 resistors and the other end is connected to ground. Read more about them here.

Now, communicating with Bluetooth is also complicated, but mix USB + Bluetooth and you get something ALMOST impossible (I hope the ALMOST is clear enough for any hatters). It is possible, but seeing you level of knowlage, simply don't risk having a severe depression trying to fingure it out!

In the end of the day, your plan of using that Bluetooth USB module is just going to be crazy complicated and big.

A more effective solution would be to use a module such as the HC-05 Bluetooth module. It is quite cheap if you get it from sites such as Amazon. Link here for this product on Amazon.com. It is designed with the Arduino in mind thus making programming easier. You project could also be a little smaller, because this module pretty much has the size of your Arduino Nano.

Hope it was helpful!


Posting data to ASP web service from GSM using AT commands - where am I going wrong

+CREG: 1,"002A","0F48"

That's the registration status. "1" is "Registered on your 'home' network", "002A" is your LAC (Location Area Code) and "0F48" is the Cell ID (CI).


Arduino Adafruit playground: Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory

Sorry completely forgot about this post. Apparently I had a folder in my project with the playground library that wasn't updated. When I removed this folder everything worked fine.


Optimizing Arduino File Selection from SD card

You have several possibilities:

Do not store the names of all files, but use the index and iterate through all files again. Disadvantage: this takes a lot of time (every time you need the file name)
Add SRAM to the Arduino (e.g. 23LC1024, 23K256), depending on your memory needs. Disadvantage: you have to 'manage' this memory yourself.
If you know something about the file names, you might generate the name. Probably it's not the case, but just to add another option. E.g. if you know that file nr 10 will always be called 'File10.txt', you can 'generate' the name.
I don't know exactly how you want to use the file names, but you might store only the latest x files used, to prevent having to iterate again reading the SD card. Of course, this only helps if there is a high chance the last x files are used more than the non recent files.

Update:
If you need to read the files while leaving the Arduino unblocked, you have to incorporate it in your loop, but don't read all the files in a loop. Something in pseudo code like:

bool readingSd = false; // True between reading first and last file
uint16_t lastTimeRead = 0; // Last time read

void loop()
{
   // Check if file read needed (initial or one hour past, I don't take
   // overflow into account
   if (lastTimeRead == 0 || (lastTimeRead + 1000 * 60 < millis())
   {
      checkReadFile();
   }

   // Perform your normal code... this will run between processing/reading
   // one file/dir.
   ...
}

void ProcessSingleFile()
{
   readingSd = true; // Within reading first/last file
   "read/process ONE file or dir (without containing files)";
   if ("last file read")
   {
       readingSd = false;
       lastTimeRead = millis(); // Move to top to prevent reading time
         // between first/last to take into account
   }
}


Arduino loses its program under unusual conditions

I would suggest that you reproduce the issue and then use a device capable of reading the flash, to confirm that it's still identical to the .hex file that was used to program the board.

I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.

But it seems that you are not alone.

Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.

Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.

Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.


const byte MY_ADDRESS = x;  // where x is whatever unique address you like

byte RxByte[32]  //32 byte buffer

void setup() {
  //insert unique ddress
  Wire.begin(MY_ADDRESS);

// this line allows the arduino to listen for i2c broadcast at address 0

TWAR = (MY_ADDRESS << 1) | 1;
//set up a receive handler
 Wire.onReceive(receive_data);

then call
Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

Wire.write( address of destination) // make the first byte the destination

Wire.endTransmission ();

then you need a receive handler

void receive_data() {
//use a buffer to temporarily store the data

for ( int d = 0; Wire.available() > 0 ;d++){

RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
datareceived = 1;

//then test if it was for this device
if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
else {}

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send

destination, myaddress, a command, and how many data bytes to follow

Addendum to Original answer. below is a complete working example.

//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient)
    //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do)
    //and 4= the number of data bytes which follow in the packet
    //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes
    //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work.
its a n example of how data can be moved around in a multi master situation
that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application

to send data just attach a button or wire to pin 2 directly to ground

watch the 2 serial windows

#include <Wire.h>
//device address  MAKE DIFFERENT FOR EACH

const byte MY_ADDRESS = 20;
const byte PARTNER_DEVICE = 25;

// transmission table stuff
byte RxByte[32]; //setup a receive buffer to hold data
byte TxByte[32]; //setup a transmit buffer to hold data
byte datareceived;

// stuff to generate some data
const int Sensor1 = A0;
byte SensorVal1 = 0;

//stuff to debounce pin 2
const byte digitalpin = 2;
byte pinstate = 0;
byte lastpinstate = 0;
unsigned long checktime = 0;
const byte debouncetime = 50;

// timer
unsigned long timing_loop = 5000;

void setup() {
  Wire.begin (MY_ADDRESS);
  TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
  Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
  Serial.begin(9600);
  pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
  Serial.println( "READY" );
}

void loop() {
  // generate some random data

  GenRandData();
  //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
  // debounces pin 2 so we can trigger a data broadcast
  pinstate = digitalRead (digitalpin);
  if ( pinstate != lastpinstate && millis() >= checktime) {
    if ( pinstate == 0 && lastpinstate == 1 ) {
      checktime = millis() + debouncetime;
      Serial.println( " button working" );
      REQUEST();
    }
    lastpinstate = pinstate ;
  }

  // this triggers the process data method after receive of data
  if (datareceived == 1  ) {
    datareceived = 0 ;
    ProcessData();
  }

  // 10 second timer triggers transmission of some data
  if ( millis() >= timing_loop ) {
    BROADCAST();
  }
}
void GenRandData() {
  // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
  SensorVal1 = random(255);
  TxByte[7] = TxByte[6];
  TxByte[6] = TxByte[5];
  TxByte[5] = TxByte[4];
  TxByte[4] = SensorVal1;
}

void ReceiveData() {
  // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
  for ( byte d = 0; Wire.available() > 0 ; d++) {
    RxByte[d] = Wire.read();
  }
  //set a trigger event
  datareceived = 1;
  Serial.println( "receive" );
}

void ProcessData() {
  Serial.println( "process" );
  // check what the data is an who its for then do something with it (RECEIVE TABLE)
  if (RxByte[0] == MY_ADDRESS) { // for this device
    switch (RxByte[2]) {
      case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
      case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
      default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
    }
  }

  else if (RxByte[0] == 0) {       //handle broardcast
    Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
    Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
    Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
    Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
    Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
    Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
    Serial.println( "DONE" );
  }
  Serial.println(  );
}

void BROADCAST() {
  // this is transmission table to send data to everyone
  Serial.println("Sending broadcast");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (0);                       // broadcast
  Wire.write(0);                                    // ADDRESS =0 BROARDCAST
  Wire.write(MY_ADDRESS);                           // SEND my address
  Wire.write(0);                                    // DATA TYPE CODE
  Wire.write(4);                                    //number of bytes being sent
  Wire.write(TxByte[4]);                            //data
  Wire.write(TxByte[5]);                            //data
  Wire.write(TxByte[6]);                            //data
  Wire.write(TxByte[7]);                            //data
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;
    Serial.println( "fail" );
    goto Tx;
  }
  //reset timer to run this again
  timing_loop = millis() + 10000 ;
  Serial.println(  );
}

void ActAsMaster() {
  //this is transmission table to send data to specific device OR return a result of a task
  Serial.println("Sending data");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (RxByte[1]);               //the return address
  Wire.write(RxByte[1]);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(1);                                  // DATA TYPE CODE
  Wire.write(1);
  Wire.write(SensorVal1);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );

}
void REQUEST() {
  //this is transmission table to send data request of partner device
  Serial.println("Sending request");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (PARTNER_DEVICE);               //the return address
  Wire.write(PARTNER_DEVICE);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
  Wire.write(0);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );
}


Use file.write(payload, length); for byte array. length should be the count of payload bytes, not the size of the payload array.

print and write return the count of bytes written. It is not meaningful to use the return value as boolean.


I think you need to look at using interrupts.

The printDate function is quite processor intensive with all the Wire and Serial.print calls, it will be taking the majority of the time in each loop().
Whilst in printDate it won't be looking at the state of the button, so you have to press at just the right time.

If you place an interrupt on the button's pin I think you will get a more responsive system.  Another thing that you could look at it only reading the clock once a second, this could be done with a timer interrupt.


Can I use my Arduino nano to upload sketch in Uno's ATmega328p chip?

Yes. You can. Either as a USB to UART adaptor and use the Uno's bootloader as you would with any bootloader-enabled breadboard Arduino, or as an Arduino ISP to program the chip directly through the ICSP pins as you would when putting the bootloader onto a blank chip.