I've copied and slightly modified your diagram, as below.  Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

simulate this circuit – Schematic created using CircuitLab

I'm supposing that unlike the original diagram, this one represents what you actually wired up.

A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur.  To see this, do some timing analysis on the code.

The code repeatedly executes sections of code like the following:

    led(0,i,0);
    __asm__("nop\n\t");     //one clock cycle delay
    PORTD = B01000000;      //select LED-2

The call to led() results in three calls to analogWrite().  As seen by perusing at garretlab the source code for analogWrite(), digitalWrite(), and pinMode(), each of those analogWrite() calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute.  Thus each of the two for loops takes less than 10 milliseconds to complete, causing the loop() routine to run more than 50 times per second.  Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.

To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the for loops.  For example, suppose you want to go up in one second and down in two.  As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add delayMicroseconds(3906-36) at the end of the first for loop, and delayMicroseconds(2*3906-36) at the end of the other, to achieve the specified rates.  (The -36 term accounts for time used by other code in each loop.  It's probably an overestimate and perhaps should be left out.)

However, the previous paragraph doesn't take multiplexing effects into account.  You may, of course, want a different PWM level for each of the nine different LED chips.  It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.

For more information about software PWM, see some articles that google turns up, including:
• Arduino PWM pin vs digital pin PWM simulation on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
• AnyPWM Revisited, a blog article by Nick Borko about PWMing 12 LEDs using software PWM
• PWMAllPins, an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM

Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations.  But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.


MQTT connection not being recognised in void loop()

I believe your problem is that you are attempting to use the MQTT connection before it's actually connected.  So your check:
if(mqtt.connected())

is always FALSE since it's not really connected.  The Adafruit library information here:
Adafruit MQTT
Says to initialize MQTT as:
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Serial.println("MQTT Connected!");
}


2 buttons pressed at the same time elevator logic

if we are in level 1, both the levels 2 and 3 are pressed it should go
  to level 2 even if level 3 was pressed first.

For this to work, the program should remember which buttons (mind the
plural!) have been pressed. Thus, instead of remembering only one
request, as in

int required_level =-1;

it should have a boolean variable for each of the possible levels,
telling us whether a stop was requested for that level.

For convenience, I would number the levels from zero, and hold these
variables in an array:

const int LEVEL_COUNT = 3;
bool requested_stop[LEVEL_COUNT];

  if we are in level 2 and both level 1 and 3 are pressed, it should go
  to the one that is pressed first as both levels are the same distance
  from level 2.

The part I emphasized doesn't make sense to me. The elevator should go
to the one that was pressed first, irrespective of the distances.
Imagine you are in an elevator at level 5, and press the button for
level 2. As the elevator just starts moving down, another rider presses
the button for level 6. Should the elevator immediately revert to going
up in order to reach level 6, which is closer? Of course not. If it is
going down, it should continue in that direction. Now, if the other
rider presses 3, it should stop by level 3 on its way down, even though
you pressed 2 first.

As stated by chrisl in a comment, a finite state machine is
definitely the solution for this kind of problems. I propose a state
machine with three states, STOPPED, GOING_UP, and GOING_DOWN:

when STOPPED, it should change to GOING_UP or GOING_DOWN as soon
as a button for another level is pressed
when GOING_UP, as soon as it reaches a level that has been
requested, it should change to STOPPED
same thing when GOING_DOWN.

And here is my proposed implementation:

void loop() {
    // Check the buttons.
    for (int i = 0; i < LEVEL_COUNT; i++)
        if (digitalRead(button[i]) == HIGH)
            requested_stop[i] = true;

    // Finite state machine.
    static enum { STOPPED, GOING_UP, GOING_DOWN } state = STOPPED;
    switch (state) {
    case STOPPED:
        requested_stop[current_level] = false;
        for (int i = 0; i < LEVEL_COUNT; i++) {
            if (requested_stop[i]) {
                if (i < current_level) {
                    analogWrite(pwmMot, PWM_DOWN);
                    state = GOING_DOWN;
                    break;
                } else if (i > current_level) {
                    analogWrite(pwmMot, PWM_UP);
                    state = GOING_UP;
                    break;
                }
            }
        }
        break;
    case GOING_UP:
        if (elevator_height() >= LEVEL_HEIGHT[current_level + 1]) {
            current_level++;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    case GOING_DOWN:
        if (elevator_height() <= LEVEL_HEIGHT[current_level - 1]) {
            current_level--;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    }
}

This code assumes you have written the function elevator_height() that
measures the height of the elevator, and have defined an array of
constants LEVEL_HEIGHT[].

Notice that this is still far from perfect. You should probably ensure
that each stop lasts at least some minimum duration. Otherwise, if the
elevator stops at level 1 while level 0 has also been requested, the
stop will only last an instant. This can be achieved by splitting the
STOPPED state in two distinct states, and switching from “waiting for
the riders to go in/out” to “waiting for a button to be pressed” on a
timeout. You may also want to ensure that, after a stop, the elevator
continues in the same direction if possible. Otherwise it will never
reach level 2 if some joker is repeatedly pressing 0 and 1.


How to compile and upload the specific (.cpp + .h) code?

The problem is that I need to import this code just a simple usual library.


Expand Arduino storage without an SD card

This may be relevant if you can get your hand on some old 30 Pin SIMM RAM.

Its a library some clever chap wrote to interface with 30-pin simm ram using an atmega328p on Arduino

https://github.com/zrafa/30pin-simm-ram-arduino

Also his video here: here https://youtu.be/Yah3ViEggxA

It is apparently quite wasteful though as you only get to use 256Kb of the RAM!

The author also states that "using this kind of RAM will put your Arduino CPU to refresh the SIMM RAM data part of the time. It means that your sketches (programs) could run a little slower than before. Also, we need to use most of the Arduino pins to be soldered with SIMM RAM pins so there will be just few available extra pins for your project."


Servo starts to shake when I added SIM900.begin(19200);

Servo.h use interrupts to generate the control signal. However, SoftwareSerial really messes interrupts up.

You can't use SoftwareSerial with anything that relies on interrupts for timing, like Servo.h.

Solutions:

Use a better Arduino with an unused hardware UART
Use an external hardware PWM controller to drive the servos
Use the internal hardware PWM (you'd need to find a library to do this) to drive the servos.


Best way to make an Arduino switch 8 12V LED's

I would recommend using something like the STP08DP05.  ST Microelectronics makes 16 and 24 bit versions as well.  You can also find TI and NXP parts that will do basically the same thing.

With these parts you can hardwire your max current value with a resistor to make sure you don't overdrive the LED.  Just because you can drive the LED at 90mA, doesn't mean you should... it will probably be way to bright.  The IC's can also be daisy-chained to your shift register and you can drive very large strings of LEDs... or use them for RGB LEDs.

Hope that helps!

EDIT - Based on Comments

There are a couple of options.  Note the Vdd represents the voltage supply to the IC itself and the nominal operating voltage is 3.0V up to 5.5V (I'm honestly not sure why they even added 7V as a max value when they specify 5.5V on the next page).

So, Vdd is not necessarily the voltage that your LED's are driven at.  You can drive the LEDs at 12V  (if you need to) and add a series resistor to the OUT pins of the IC's to dissipate the extra heat.

You would probably be fine with 200 ohms per pin.  If you set your current at 20mA, and assuming a 2.2V drop through the LED, that would give you approximately 5.8V at the OUT pins and the IC wouldn't have to dissipate much heat in terms of power.

However, if you don't need to drive them at 12V then I wouldn't bother.  Usually the forward voltage of an LED is 1.8 to 3.3V and you don't need 12V.  However, if you are driving a lot of them then it may be easier to use the 12V.  There are always trade-offs.


It is indeed possible and supported to use different CS (chip select) or SS (“slave select”) lines to address individual SPI devices on a single bus run by an SPI “master”.

Image from Wikipedia
Many SPI TFT Touch displays need this to address the display controller and the touch controller as individual SPI devices and/or an integrated SD Card interface (wich also uses SPI).
The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time. I.e. only one SS/CS may be active at any time and the software must support such sharing of SPI resources.


Code for mapping voltage on a sensor and outputting a value in liters

Curve fitting
Well, a lazy way to do it is just to fit a curve to it, using Excel, or Libreoffice, Google Docs or whatever.  Here's gnuplot being used that way to fit a cubic polynomial to it:
"points.txt" containing your data, tab-delimited:
4.04    94
3.981   88
3.902   84
3.81    81
3.703   77
3.637   72
3.564   69
3.483   65
3.393   61
3.293   57
3.18    53
3.053   50
2.908   46
2.546   42
2.192   38
1.726   35

Gnuplot session:
gnuplot> f(x) = A*(x**3) + B*(x**2) + C*x + D
gnuplot> fit f(x) "points.txt" via A, B, C, D
iter      chisq       delta/lim  lambda   A             B             C             D
   0 1.8323200047e+01   0.00e+00  9.28e+01    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
   1 1.8323200047e+01  -4.65e-10  9.28e+00    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
iter      chisq       delta/lim  lambda   A             B             C             D

After 1 iterations the fit converged.
final sum of squares of residuals : 18.3232
rel. change during last iteration : -4.6534e-15

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 1.23569
variance of residuals (reduced chisquare) = WSSR/ndf   : 1.52693

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 2.81842          +/- 1.156        (41.02%)
B               = -11.0015         +/- 10.22        (92.86%)
C               = 14.4765          +/- 29.11        (201.1%)
D               = 28.7358          +/- 26.52        (92.27%)

correlation matrix of the fit parameters:
                A      B      C      D
A               1.000
B              -0.998  1.000
C               0.990 -0.997  1.000
D              -0.974  0.987 -0.996  1.000

And here's what looks like against the actual data with plot "points.txt" with linespoints, f(x):

So you have a function:
float f(float x) {
  static const float A =   2.81842;
  static const float B = -11.0015 ;
  static const float C =  14.4765 ;
  static const float D =  28.7358 ;
  const float x_squared = x * x;
  const float x_cubed   = x * x_squared;

  return A * x_cubed + B * x_squared + C * x + D;
}

If you don't care about the code size and the slowness of float arithmetic, then that might be okay.
Otherwise you may want to convert that function to something like fixed point arithmetic.
A cubic polynomial may be overkill, but then whole technique may be also.
Peicewise Linear
You can make a table of you points and just do what graphing programs typically do, linear interpolation between the points.
float f(float x) {
  static const struct pt {
    float v;
    int l;
  } points[] = {
    {0.0  ,  0},  // I put this here for testing, but put a better value here.
    {1.726, 35},
    {2.192, 38},
    {2.546, 42},
    {2.908, 46},
    {3.053, 50},
    {3.18 , 53},
    {3.293, 57},
    {3.393, 61},
    {3.483, 65},
    {3.564, 69},
    {3.637, 72},
    {3.703, 77},
    {3.81 , 81},
    {3.902, 84},
    {3.981, 88},
    {4.04 , 94}
    // you should probably have another entry here so that readings up to 5V work.
  };
  static const size_t table_len = sizeof points / sizeof points[0];

  for (size_t i = 0; i < table_len - 1; ++i) {
    if (x >= points[i].v && x < points[i + 1].v) {
      return
            (x - points[i].v)
          / (points[i + 1].v - points[i].v)
          * (points[i + 1].l - points[i].l)
          + points[i].l;
    }
  }

  return -1;
}

Sitting in the center of this in the return statement is basically a crude implementation of Arduino's map(), but for floating point, which again, you don't really need floating point, even if you want to use this piecewise approach.
In short, you find which two entries of the table you're sitting between, and apply what amounts to map() on the line segment formed by the two table entries.
PROGMEM
Either of the curve fitting or piecewise approach could be used to generate a much larger lookup table out of which you could just chose the nearest point.
If you're doing this on an AVR-based Arduino, the table for the piecewise linear approach or a pure lookup table approach could use PROGMEM for the array.
Regarding float and fixed point
Any of these techniques could be adapted to fixed-point math.
Which ever you use, if you're on AVR based Arduino, keep in mind that there's no hardware floating point support at all, and although double exists as a type it is implemented in avr-gcc as a single precision float.
If you're using one of the non-AVR based Arduinos, it may have support for float (and maybe for double), in which case the generated code may not be so bad, though may still be slower than using integers.
If you can do everything with integers, resulting code should be a lot smaller and faster.  I'm guessing for what you're doing, if either of them are more important, it's probably being smaller.
For using integers, you may be able to keep your input "voltage" as an ADC count, not having an intermediate voltage calculation.  And even if you want single digit liters when you're done, the intermediate interpolation, curve fitting, or table lookup may require that you work in something like centiliters, milliliters, so that values like the A constant from the curve-fitting example can be represented as an integer, e.g.  2818 mL  rather than a cruder 3 L.  If you're not using a plain lookup table and finding the nearest entry, that is if you're using the curve or piecewise linear approach, doing everything in integer arithmetic from ADC count to mL.  Although you'll need to run another curve fitting, since the A, B, etc will representing mL-per-ADC-count not L-per-Volt.  Or scale them from the value given.
And there are other options, piecewise cubic splines, etc.


How to build circuit to switch to other power source if primary source dies?

Your $2 budget rules out some of the more-effective possible solutions, such as using an actual UPS (uninterruptible power supply) system.

One affordable approach is to connect the plus side of a 3.7 V lithium-polymer battery through a Schottky diode [such as MBR0520, SS14, 1N5819] to the +5 V line of an Arduino board.  (I haven't looked at Raspberry Pi schematics and don't know if this will apply there.)  Hook the minus side of the battery to Arduino ground.

Ideally, the battery voltage less the voltage drop through the diode (say .4–.5 V) should be just less than the voltage that USB supplies.  Ie, just under 5 V if you have a 5 V board, or just under 3.3 V for a 3.3 V board.  Note, most 3.3 V Arduino systems are specified to run at 8 MHz rather than 16.  There's a good chance a 5 V Arduino running at 16 MHz would continue to run ok when powered by about 3.3 V, but it's out of spec.

If your battery voltage exceeds 5 V you won't be able to make the connection quite so directly.  Besides certain risks of damage (see eg Method #5 and Method #8 of 10 Ways to Destroy An Arduino) there will be the practical matter that the higher battery voltage will cause its power to be used preferentially to the USB power, thus discharging the battery so that it won't act as a backup.

Edit: The question-edit says the system uses 5 V, and seems to suggest the primary 5V power supply uses 4 AA batteries and a DCDC converter.

If the DCDC converter is a step-down buck converter it will go out of regulation when the input voltage from the four AA's goes below 5 V, which is 1.25 V per cell.

As you can see from the following graph, if the discharge rate of a typical alkaline cell is 100 mA, it still has about half its power left when its voltage goes below 1.25 V.  To fully use up the alkaline batteries, you could use a buck-boost converter or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.

(Note, the AA-battery discharge curves shown above and below are from the powerstream.com's “AA tests”  web page.)

For the backup battery, where you also want 5 V output, an economical possibility is use of four AA NiMH cells, with nominal voltage 1.2 V per cell. However, initial voltage officially can exceed 1.4 V per cell, giving 5.6 V total:

A Schottky diode in series will bring that down to say 5.2 V, an acceptable level for powering a 5 V system.  But if the primary supplies 5.0 V, the backup will end up discharging slightly until its output voltage goes below that of the primary.  If that's acceptable, fine.  Otherwise, you could use a diode like 1N4001, with 0.7 to 0.8 volts of drop at 0 to 150 mA output.  Instead of losing some backup power at first (due to higher backup than primary voltage) you will lose some at the end, due to backup voltage going too low slightly sooner. That won't be a problem, however, if you restore the primary supply and recharge the backups in time to prevent over-discharge damage to the backup batteries.


This code should work. You will need to declare the following variables:

lastPress   // The last time the button was pressed
outputState  // The state of the timed output
outputPin  // The pin number for the timed output
PERIOD  // The amount of time that the outptu remains on

The code:

void loop()
{
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH)
    {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);

        outputState = HIGH;
        lastPress = millis();
    }

    if (outputState && ((millis() - lastPress) > PERIOD))
    {
        outputState = LOW;
    }

    digitalWrite(outputPin, outputState);

    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
}

A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.


Powering Motor shield and Arduino Mega Separately

On the side of the DC Motor Shield v1, there is an external power - +  2 pin terminal.

This can be used to supplement the shield with power.

Adafruit: "The motor controllers on this shield are designed to run from 4.5V to 25V.
MOST 1.5-3V MOTORS WILL NOT WORK"

If you are lucky to have the motor specs and ratings on hand, you will be able to account for how much power your motor(s) will need in your application.

Adafruit: "The motor driver chips that come with the kit are designed to provide up to 600 mA per motor, with 1.2A peak current. Note that once you head towards 1A you'll probably want to put a heatsink on the motor driver, otherwise you will get thermal failure, possibly burning out the chip."

Here is an important tid-bit for your scenario... (So no 9v Batteries for the motors!):

Adafruit: "You can't run motors off of a 9V battery so don't even waste your time/batteries! Use a big Lead Acid or NiMH battery pack. Its also very much suggested that you set up two power supplies (split supply) one for the Arduino and one for the motors. 99% of 'weird motor problems' are due to noise on the power line from sharing power supplies and/or not having a powerful enough supply!"

...

So makes sense,  get the Arduino powered, by itself, then get another power source for your motor shield.

Your sensors might be able to hop on the Arduino power supply if it's providing enough power.  I'd keep them separate from the motor power line, due to noise interference as suggested.

Try this, and see if the Arduino stays powered.

There is a lot of helpful info here, some new things I've learned just now.
https://learn.adafruit.com/adafruit-motor-shield/power-requirements


Reading a part of bitmap image on Arduino

Any coordinate in a bitmap (note: the term bitmap here [all lower case] refers to the concept of a grid of pixels, not the Windows BMP file format which I will always refer to as BMP all in capitals) can easily be calculated as long as you know the width.  The height is only needed to stop you going too far.

Any pixel offset in a buffer of pixels is calculated as y * width + x assuming a left-right / top-down pixel arrangement in the buffer.

The information you are really interested in with your bitmap is actually considerably less than is in the BMP that you show.  Your BMP is 56x96 pixels, but the information you actually care about is actually only in a resolution of 7x12 blocks.

It would be far simpler if you could pre-process the provided BMP on a PC to create an array of 84 entries each with a different tag or value to represent what it is.  Your image there could then be represented as the array:

{ 3, 3, 3, 3, 3, 3, 3,
  3, 1, 0, 0, 0, 1, 3,
  3, 0, 0, 0, 0, 1, 3,
  0, 0, 1, 1, 0, 0, 3,
  3, 2, 1, 0, 0, 0, 3,
  3, 1, 0, 0, 1, 0, 3,
  3, 0, 1, 0, 0, 0, 3,
  3, 0, 0, 0, 2, 0, 3,
  3, 0, 0, 1, 0, 0, 3,
  3, 1, 1, 0, 1, 0, 3,
  3, 0, 0, 0, 0, 0, 3,
  3, 3, 3, 0, 3, 3, 3 };

Where 0 is an open white space, 1 is a closed black space, 2 is a black space with a cross and 3 is a border space.

The two crosses would then be calculated as (1,4) = 4 * 7 + 1 = 29 and (4,7) = 7 * 7 + 4 = 53.

Working with BMP files is somewhat more tricky.  They come in multiple depths and multiple bit arrangements, as well as different versions with different header sizes.  They also have different padding requirements for different line lengths and bit depths, and are generally a rather nasty file format all round.

And on top of that they are upside down.  BMP is the only file format I know of where 0,0 is at the bottom left instead of the top left.  Consequently you have to invert all your Y coordinates to make sense of it, and parsing a BMP file from the top down is really slow because you have to keep jumping backwards in the file.

So it would be much better if you could write a program on a PC using software which already understands the BMP format and can render it into a buffer for your program to then parse each block to work out what it is and build up a small 84 byte file of the actual information you need for your robot.

If you must read the BMP file directly on the Arduino then I have code you use to help you.  It's not designed for the Arduino but for the chipKIT boards (though it's very similar) and is designed as part of my DisplayCore framework for chipKIT (and other more powerful) boards, but you are welcome to take whatever bits you like, or just use bits to give you more insight into how BMP files work.  You can get the code from Github here: https://github.com/MajenkoLibraries/DisplayCore/tree/master/ImageReaders/BMPFile

To parse your bitmap into an array you would have to take each 8x8 block of pixels and work out what shape is in it - whether it's all black, all white, a cross, or a border piece.


Receiving multiple Values from android via Bluetooth

If there are no other constraints, send them as a text with delimiters and a  terminating character.
e.g. something like "123;45;678\n"

On the arduino, either manually check for those delimiters and convert the digits to a number on the fly, or use strtok  and atoi after reading the whole line.


Liquid Crystal LCD and serial monitor not playing well together

On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.
Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


Disclaimer:   IANAL nor US regulations expert.

There are a few standard certifications that will essentially guarantee that a part will meet US regulatory requirements. Usually more of the form "your building burned down and you have no insurance because ..." rather than prosecuting you for non compliance.

Relays with UL rating bought via a reputable US supplier will usually quality.
eg if Digikey sell it it is PROBABLY Kosher.
Also if made by reputable manufacturers the same applies, as long as its genuine. eg (1 of many) Omron - they don't make no junk largely and even their junk is certified :-).

HOWEVER if you are building something using such parts the whole unit will need to be certified. For small volume applications it may be easier and cheaper to buy comething COTS (commercial off the shelf) which has the relevant certifications. That said,be sure these are legitimate.

As a guide:

US standards a useful introduction

Extensive international standards summary

Wikipedia on UL

MET Labs strut their stuff comparison with UL.

Intertek test labs bow in

Useful - Understanding electrical certification

Possibly useful templates


A datasheet for the HX711 is https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf  (On your board, it looks like E+ is AVDD and E- is AGND.)

Each of your two load cells could be a half-bridge of a wheatstone bridge, with excitation on the white and black, and sensing on the red like:

I have a similar loadcell with the colors as Blue-Red-Black, (instead of White-Red-Black as above, or the Red-White-Black in your image) with my red sensing wire in the middle.  The positive strain resistance (increasing resistance with increasing load) is between the Blue and Red, while the negative strain (decreasing resistance with decreasing load) is between the Red and the Black. The ~1000 ohm resistance in each leg changes by tenths of an ohm with hand pressure on the button, when the outer portion is supported, but the inner portion is not supported.  Your cells do not have the bridge-button part that create a balanced twist along the center portion, so it might be hard to reliably apply a load your cell.

To make positive deflections of the cells combine to unbalance the Wheatstone bridge, wire one cell's white and black opposite to the other cell, and attach them to E+ and E-, with the reds connected to A+ and A- like this:

   HX711.E+ : Cell1.White + Cell2.Black
   HX711.E- : Cell1.Black + Cell2.White
   HX711.A+ : Cell1.Red
   Hx711.A- : Cell2.Red

The labelling on the schematic isn't quite right-- the "Reference 1K" are actually the negative-strain portions of the cells, and might be better labelled as "-Active 1k Ohm".

If it moves in the wrong direction/wrong sign with increasing force, switch the reds or multiply by -1.

If you have only one three-wire cell, use a couple 1K resistors, or a 2K potentiometer to balance the existing cell as the other half of the Wheatstone bridge.  One issue with using discrete (10%, 5%, 1%?) resistors is that the precision and tolerances when configured as a voltage divider may produce a significantly different result as compared with the balance in a lead cell and its full-scale signal (+/-0.1%) in a loadcell.  A the center tap of a potentiometer can provide for tuning to match the load cell voltage.

Per @wirewrap's comment, the colors on the wire could be different than the picture I posted.  You can make certain by measuring the resistances between the wires and exciting on the pair with the greatest resistance, and sensing on the middle terminal.


How can I create analog signal which is similar to PMT(Photo Multiplier Tube) pulse using analog write?

Short answer: You can't.

The Arduino can't do analog output at all, much less matching a specific analog waveform of ≈40ns duration.

PWM on the Arduino simulates constant analog voltages using square wave pulses of variable duty cycle. It has no support for creating analog waveforms of any type, much less ones with such a short duration.

EDIT

As mentioned in this thread: Generate a ramp input with an Arduino Uno

You could use a resistor ladder to create a roll-your-own DAC, and then use direct port register manipulation (not digitalWrite) to set the pins controlling your resistor ladder and get a crude approximation of your waveform.


Redirecting Arduino Serial Output to a File

Well, I don't know about your ino program, but here's how I'd do it:

get_serial.py

import serial, sys

with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
    while ser.isOpen():
        print(ser.readline())

The idea, here, is to print on stdout the data coming on the serial line:

python get_serial.py /dev/ttyACM0 115200 > output.log

or you can do it this way:

get_serial.py

import serial, sys

with open(sys.argv[3]) as f:
    with serial.Serial(port=sys.argv[1], baudrate=sys.argv[2]) as ser:
        while ser.isOpen():
            f.write(ser.readline())

which is ran:

python get_serial.py /dev/ttyACM0 115200 output.log

Hope this helps!


The Cosa ST7920 library uses text mode only (16X4). The ST7920 class is controlled though an adapter. There are several adapters available depending on how you wish to connect to the Arduino. They range from parallel 4-bit to SPI with shift register. The adapters implement the interface HD44780::IO. There are several LCD examples. The CosaLCDbench shows the possible configurations with LCD and Adapters. Please see the file for further details.


Arduino Uno keeps looping on setup() everytime I press a specific button on the remote

How high can currentpulse get before it is reset to zero? It is used an array index and if it gets larger than the (number of array elements-1), your code will write outside of the array.

Can the array be so far over-written that it grows into the stack area? That could definitely cause a reset, or reset-like behavior.


Receive data from multiple wireless sensors simultaneously

It is possible to do this with Zigbee. The API mode in the Xbee modules enables this.

Unlike the AT mode in Zigbee the API mode enables you to distinguish between the packets that you receive from different slaves.

In the API mode, you send each data packet with as a frame with a header which contains start delimiter byte, most significant byte (which tells where the start byte is at), least significant byte (which tells the end of the byte), an API identifier, the data that you want to send and a checksum byte.

This link provides a nice tutorial which shows how to setup Xbees on API mode with an Arduino and Python:
http://serdmanczyk.github.io/XBeeAPI-PythonArduino-Tutorial/

I hope this helps.


How does code typed in Arduino IDE runs on a nodemcu?

how does code typed in Arduino IDE runs on Nodemcu

The IDE runs the compiler which turns the C into assembly and then machine code.  That is then uploaded to the ESP8266.

  what firmware is present on the nodemcu.

The code that you just wrote and uploaded.

  i want my esp8266-01 module to work with a Lilypad Arduino .So this is the way I want it to work Lilypad Ardiuno has acquires some data using a sensor it wants the post this data to a server on internet.So to do the job it uses a ESP8266-01.So will the configuration work?

Sure, if you program it to do that.  Two choices:

Use the AT firmware on the ESP-01 (installed by default)
Write custom firmware (as above) for the ESP-01 to do what you want.


I re-soldered all connections and used new wires. Now the board is recognized by the i2cdetect library. Upon multimetering all connections using the continuous mode (the one that looks like a loudspeaker), I noticed my breadboard sometimes does not conduct properly. Cheap breadboards and/or cables are at fault here, as far as I can tell - a rookie mistake. I'm guessing the ground connection is the only one I have not measured before


I2C communication between Attiny85 as master and arduino UNO as slave

The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the endTransmission() function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)

I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.

Chrisl aka lucullusTheOnly

EDIT: I had to think about this and looked into the library. The problem was found easily. In twi.cpp there is a NOISE_TESTING define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.

I have deactivated the NOISE_TESTING in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of NOISE_TESTING.


How does the reset button work on the Arduino?

The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.

The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.

When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

If you have anything else plugged into the Arduino then unplug it.
Try powering the Arduino from different power supplies.
If you have another Arduino or an AVR programmer try re-flashing the bootloader.


Using an Arduino as an LED controller for an arcade stick

I think the idea of putting the arduino between the button and ground is the problem here — 1P appears to be the input for the controller button, and you can't expect to take an 'input' from the button on both pins at once.

Try connecting one lead of the button back to its ground, and the other to 1P (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as INPUT_PULLUP.

This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share GND) when the button is pressed.


NEO-6M is working but it doesnt show data

I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.

Solution:

  The GND of every module must still connect on the Arduino.


Using an Arduino as the processor for a computer-mouse-like speed detector

Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.

If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.

Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to wikipedia, a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.

But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.

Voila; speed! :-)

This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.

Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.


The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.

Printers have been doing it that way with their print heads for decades.

http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/


Triggering a soft reset (Arduino Leonardo)

So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.


Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?

If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this https://www.sparkfun.com/products/12009 and Adafruit http://www.adafruit.com/products/757

if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

(source: arduino.cc)


There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.

The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.


How to connect ESP8266-01 (AT-commands) to its web server using AJAX

You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino.  It can't ever work.

Likes like:

server.on("/",WebsiteContent);
server.on("/xml",XMLcontent);
server.begin();

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.

So, either:

Do it all with AT commands only, or
Ditch the Arduino and program the ESP8266 directly instead.


Arduino + SIM808: How to get only the JSON object response without the header?

You need to receive the whole header and them trim what you don't want. The easiest way of doing this is scanning the header string for a new line (\n) character. From the start of the string to the new line gives you a line of the header. If the length of this substring is < 1 then look for the next line. Now scan between the start and the new line and see if you see a colon (:), if you do then this line is part of the header, look for the next new line. Otherwise use strtod() to convert the data to a double.

It should be something like this (not compiled, not tested):

char* response = ".........";
char* pStartOfLine = response;
char* pEndOfLine = response;
bool bFoundData = false;
while (!bFoundData && pEndOfLine)
{
  while (pEndOfLine != NULL && *pEndOfLine != '\n')
    pEndOfLine++;
  if (pEndOfLine && pEndOFLine != pStartOfLine)
  {
    char* pStartOfData = pStartOfLine;
    while (pStartOfLine != pEndOfLine && *pStartOfLine != ':')
      pStartOfLine++;
    if (*pStartOfLine != ':')
    {
      theData = strtod (pStartOfData, NULL);
      bFoundData = true;
    }
  }
}

If it's in a separate function then you could just return rather than use the Boolean.

The order of the lines in the header are not guaranteed, but will always be in the same order from the same device with the same software, so as a cheat you could look for 'Content-Length: 18\r\n' and then just take the next non-blank line after that, but this is a more hacky way of doing it.


How to read two byte register address using arduino wire library

i can use Wire.requestFrom and give the register address and how many bytes i want to read

So you give it 2 to ask for 2 bytes.
Then you combine them. How you do that depends on what the bytes represent.  If the first is the upper byte and the second the lower byte of a 16 bit value then you would:
uint8_t b1 = Wire.read();
uint8_t b2 = Wire.read();

uint16_t val = (b1 << 8) | b2;

If it's the other way around then just swap the variables in the combining section.
However if the values are some other arrangement (I saw something recently that had two registers with a 12 bit value with overlapping bits) you will have to combine it in the way that is required for that specific arrangement.


Yes, get an AVR programmer instead.

1) You can flash your arduino board with avrdude/avr-gcc. Install these tools, find the datasheet of atmega328 (google it), use the board pinouts to connect to your programmer (stk500v2/ISP) and voila!

2) Keep in mind that by "manually" flashing your atmaga on arduino board you're removing bootloader that is needed to load your sketches from ARDUINO IDE.

3) Use your favourite C/C++ IDE


Velleman KA02 not working on Mega 2560 r3

Nevermind, I solved it. There's 6 pins located on the Uno and Mega labelled ICSP, and those were the key. I simply connected the MOSI, MISO and SCK pins on the Mega to the audio shield (along with GND and 5V) and also the 10 pin (audio shield) to the 53 pin (Mega) via a male to male jumper. The header code was modified to work with the new values, and now I am able to send character signals via the serial monitor.


I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.


I looked the images you have on Google Drive. On the image called IMG_20170822_233722.jpg, I see you are using a 50k ohm potentiometer to control the display contrast. Normally you would use a 10k ohm potentiometer. Using the 50k will make the adjustment very sensitive and hard to adjust. If you are careful and adjust it slowly, it might work for you.

The other image, IMG_20170822_234242.jpg, clearly shows "poor solder joint" connections on the display. D4 - D6 (especially D5 to D6) look like they could be "shorted" together. I think you could fix them by using Desoldering braid or if you don't have any, you could heat up each connection with your soldering iron then quickly "flick" the display to remove the solder. After you have removed the excess solder from each connection, I strongly recommend applying soldering paste to the connections next. The soldering paste really helps the solder to flow into the connection. Now try re-soldering each connection. I'm not sure what kind of solder or iron you are using but I can tell you what works for me. 25 watt pencil tip soldering iron with 22 gauge / 0.71mm rosin core solder.

I can't tell for sure from the pictures if any of the display pins are shorted together and I don't know if shorting them together will damage the display, Arduino or both.


I2C device responding, but data is nacked

You want to get the resulting code working, but you should do small minimal tests.

Start with the i2c scanner.
Connect only one sensor, and if it is detected, add more sensors.

How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.

Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?


Should a delay be expected to cause deadlock?

You don't seem to use standard Arduino stuff since you defined your own main() which is normally avoided when programming Arduino.

If you take a look at Arduino provided main() (in hardware/cores/arduino/main.cpp), you'll see how it is defined:

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Did you notice the init() function call at the beginning?

Its code is defined in hardware/cores/arduino/wiring.c; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by delay().

In the same wiring.c file, you can also find the definition of delay():

void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

This will turn into an infinite loop if micros() always return the same value, and it does so if init() has never been called before.

This is what happens with your code.


How to connect GPS Neo-6M module to GSM Shield SIM900 V2?

For your program, I'll highly suggest to use softwareSerial. It pretty much emulates the serial communication on other pins (NOT PIN 0 & 1). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (NOT PIN 0 & 1). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.

The shield can cause problems if it uses Tx and Rx on pins 0 & 1, WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, NOT ON PIN 0 & 1.

Once again, softwareSerial is NOT ON PIN 0 & 1.


Need help with converting Celsius to Fahrenheit in the code

If you are using the Adafruit DHT sensor library, then you can get a
Fahrenheit reading by passing true as an argument to
readTemperature(). C.f. the comment in the source code. For
example:

Serial.print("Temp: ");
Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
Serial.println(" deg. F");

Note that this library offers also the conversion functions
convertCtoF() and convertFtoC().


Power Arduino from 230v with battery fallback

This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.

Probably 10 mA of that is the LED, so removing it would help. I have a page about power saving. You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

Example of waking using an LDR

I made up a test like this:

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.

#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precautionary while we do other stuff
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  }  // end of setup

void loop ()
{

  // flash LED 5 times
  for (byte i = 0; i < 5; i++)
    {
    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
    delay (100);
    digitalWrite (LED, LOW);
    delay (100);
    }

  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes high
  attachInterrupt (0, wake, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

  What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.


How should I initialize a RepRap Discount 12864 on u8glib?

I solved the problem myself. It turns out to be a problem of wrong pinouts.

My PCB of the project was originally designed for the LCD2004 counterpart, and I thought it was a drop-in replacement for 12864. But no, it's not.

This is the "Smart Adaptors". Notice that the orientation are 180 degree different.

If you have the same problem not lighting up a 12864 when switching from 2004, or vice versa. Check your orientation as above.

My solution will be crimping a different JTAG wire instead.


How Bootload an Lilypad Arduino USB using Arduino UNO

If you try uploading to a LilyPad USB with the wrong board selected, you may end up in a condition where the bootloader can no longer respond normally.

You can get the LilyPad Arduino into bootloader mode by tapping the reset button twice in under a second. Once in bootloader mode, the LED should blink at about 1Hz for about 8 seconds. My advice is to load a blank sketch (i.e., nothing in loop() or setup()) and then double tap the reset button shortly after hitting the upload button. That should restore the LilyPad USB to a working state.


What does “LSB per degree per second” mean?

Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.


Getting inverse values of acceleration and tilt for the MPU 6050

There are a lot of libraries, I wouldn't use the accelerometer library in wire, download and add the I2Cdev library, you can get it on a variety of different sites like github.com


Such intermittent issue looks to me a hardware signal integrity problem, specifically around the I2C bus RTC chip. Did you experience any problem from any other device on the same I2C bus (e.g. when all the LEDs are on)? If not, then check on the noise level on RTC chip power and GND. Also, the I2C spec has limit on the bus capacitance load as max as 400 pF. When there are too many I2C device loads on the same bus, the bus may become vulnerable to the system noise.

Debug Suggestion: To narrow down if it is I2C load issue, add an I2C bus driver chip between the main Arduino board and your peripheral. For example, P82B96 from TI. See the spec here. http://www.ti.com/lit/ds/symlink/p82b96.pdf


Is it bad to leave my Arduino UNO on uninterruped?

This question has a very broad answer. As it depends upon your implementation of both hardware and software.

In very short -

That all depends on your code. The hardware should be able to be left on indefinitely, assuming it is all within spec's. Assuming that, then the biggest concern is the code running on it. Where largest problem of concern is running out of resources. Such as memory. If your code as a memory leak then it will be a problem. Or if there is a bug in the code that can cause it to get stuck. The later can be addressed by employing the WatchDog, which will reset (loose all data) if the code gets unexpectedly stuck.


Ultrasonic Sensor(HC-SR04) recording random distance

These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to "chatter". There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.
EDIT
Here is a rudimentry example, where I take multiple readings (nb_measurements measurements) and then take the average over it:
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i < nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep nb_measurements at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.


Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.

My advice:

Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.

For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).

Update after your comment below.

What you can try:

Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
Double check the wiring (although it seems easy).
Try different wires (maybe a jumper wire is malfunctioning).
Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).


This is an old post, but for future people:

The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.


To put the comments into an answer:
You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the breakout board from Adafruit, but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).
The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.
As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.


Powering 3 servo motors and Arduino Uno with one 9 V battery

I don't think anything should get damaged; the regulator is rated for 1A, and even beefy servos don't draw more than 200mA when moving against heavy load. The problem is that your battery won't last long. Even the heavy-duty Li primary 9V batteries are under 1000mAh, and the actual capacity is heavily dependent on the discharge rate.

Why can't you use a rechargeable Li-ion pack with an appropriate step-up or step-down converter?


As always I recommend the old RTFM (read the f***ing manual) of the LedControl.h library.
In the FAQ its clearly stated:

  Why don't you use the hardware SPI-Bus of the Arduino?

  When I wrote the first version of the library I didn't knew much about
  the Arduino or AVR processors in general and I knew nothing about
  writing code for the hardware SPI-bus on an ATMega. But I knew how the
  SPI protocol works and how I could make this work using simple
  digitalWrite() commands. I turned out the library code is fast enough
  for common use cases, so there is no need for doing Hi-Speed
  communications.

  Other strong points in favour of the (admittedly trivial) code design
  are - Use any three free IO-Pins of your board for the hardware -
  Simple to debug. Much easier than managing 3 differnt SPI devices
  connected to the same hardware bus - Library is easily portable to
  other platforms, since it uses only two very basic functions from the
  Arduino language

So with this library you clearly have never used hardware SPI (although you could use the pins, but only via softwareSPI)


Added at top:
Your code runs correctly on a $US3 Arduino Nano :-)
It seems extremely likely that you have a hardware problem of some sort.
If you have a voltmeter you can try these easy checks.
I carried these out to be sure that I got what was expected and the results are as you would expect them to me. Use a meter set to DC Volts - typical common meter circuitry averages the PWM well.

Remove LED etc connection to pin 9.
Measure the voltage from the 5V pin to ground. If powered from USB this will usually be slightly below 5V.

Run your code with the analogWrite set to 128 ie
analogWrite(pinNine, 128);

Measure the voltage on pin 9 relative to ground. It should be close tohalf the voltage on the 5V pin in 1. above. This is because the analogWrite value is controlled by PWM with values from 0 to 255. 128/255 ~= 50% so output is 50% of Vref = 5V by default. in a 5V system.

Set analogWrite to
 analogWrite(pinNine, 25);

The voltage on pin9 should be about 10% of the voltage on the 5V pin.

IF you get approximately the voltages shown in 3. and 5. your code is working OK and your hardware is OK.  If not then 'summat aglae'.
Try another analog pin.
Check that the red wire to the LED goes to UNO ground.
The voltmeter is a surer way of checking that the LED is as you can see actual numeric values that result.

OLDER:
It always helps greatly if you show PIN IDs on photos so people can be confident re what you have done.
If you view the whole UNO-R2-R3 connector with numbering it is obvious that the important pinouts are the same.
If however you view part of the connector with no numbering/ pin names shown,  then on the R3 there are additional pins on the ARef end of the connector which make comparisons'more difficult).
You APPEAR to have an Arduino UNO R3
It would help if you gave actual model and weblink in future "just in case it matters". .
You appear to have connected to pin 9  (as you intended to)
Pin 9 has PWM capability, as required.
It seems that your code should work.
Thusly

IF the red wire connects to ground the circuit seems electrically correct.
Does it?
Code LOOKS OK.
Try digital write on / off on pin 9 to see if LED changes and that the port behaves as expected. A bad port pin is possible.
What pin is serial on?
Try another pin with PWM capability to see if it changes.

ARDUINO UNO R3 from UNO home page
The connector pinouts vary widely between models of UNO.


pulseIn() is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.

Also, I don't know which implementation of the ESP8266 plugin you are using, but the one I use has pulseIn available.


Global Variable does not Change when Value is set within Boolean Function

You have local variable mPass in the function restoreConfig. It 'shadows' the global variable.


FastLED library: How can I adjust the brightness of a single pixel on an absolute scale?

There is no dedicated function to do this, because you can just do exactly this by using the HSV color model. Hue (H) controls the color it self, S stands for saturation of the color and V is called lightness or value. That is what you try to control. Just set the LEDs color to a HSV value and change it's V value:

leds[i] = HSV(color, saturation, brightness);

While color and saturation are staying the same (to keep the same color), you can change the brightness directly with the thirds value. Note, that leds[i] is still defined as CRGB, not as HSV. This assigment uses an implicit conversion, that is defined in the library.

You can see the usage of HSV in the Cylon example of the FastLED library. There it is the Hue value, that get's changed, but it is the same principle with the brightness.

Now there is a problem to solve: The FastLED library can convert HSV colors to RGB colors, but not the other way round. So you cannot simply get the hue and saturation of an RGB color with this library. You can go 2 ways here:

You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a HSV color in the second array, convert that array to RGB by using CRGB(hsv_leds[i]) and save that in the first array, which get's used by the FastLED library). This is relatively easy, but you effectively need double the memory for storing the color values. This is not an issue, if you have enough memory or few enough LEDs to control.
You can write your own function to convert RGB values to HSV, then use it to access the hue and saturation values of the targeted RGB color, create a new HSV color with it and the new brightness and use it to set the RGB values for the FastLED library. In this forum thread there is a brief discussion about that, though it leaves you with the implementation yourself. I think there are suitable implementations, that can be found on the web. A quick search gave me this code from github gist. I have not tested it, so I cannot say, if it really works correctly, but you should give it a try. I'm sure there are also other implementations.


Connect arduino with C# Desktop application wireless using esp8266

Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.

How you would do either of those in C# is outside the scope of this website.

The ESP8266 has AT commands that perform the task for you - chiefly AT+CIPSTART.

The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.

A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.

Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.


All the inputs are clearly marked.

The battery connects to +12V and GND
The Arduino's 5V and GND connect to 5V and GND.

The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.

The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.


EPS8266 ESP-01 Blue led stays lit unless 3.3v logic divider is bypassed, works when reconnected

A wiring diagram would help.

Also, measure the 3.3v regulator's output, especially under load; 9v batteries are best in low-drain long-life applications like smoke detectors. Another supply, perhaps Arduino's 5v supply, might be a better source for the 3.3v regulator.


arduino + GSM/GPRS SIM 900A cannot able to read a message

Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of them


Which arduino will be suitable with bill acceptor

Define 'lot of code', the Arduino Uno has 32 KB Flash, the Mega 256 KB.
Define 'fast', the Uno/Mega are 16 MHz, the Due 48 MHz
Three switches use 3 GPIO's, shouldn't be a problem on neither of them; the Mega has more GPIOs than the Uno, but both have plenty for your needs.
The Ethernet shield are available for all three
I don't know the 'bill acceptor', add a datasheet.

Conclusion: it depends on what is lot of code, and what is fast.


Arduino Yun Disk Expander low memory but it looks like my memory is fine

I don't have a YUN or a lot of experience with OpenWRT, so I'm not sure I'm going to be of much help but, I'm guessing the error you're seeing is from this line of the sketch.
Excerpting that here:
Process awk;

awk.runShellCommand(F("df / | awk '/overlay/ {print $4}'"));
int output = awk.parseInt();
if (output < 1000) {
  Serial.println(F("\nYou don't have enough disk space to install the utility software. You need to free at least 1MB of Flash memory.\nRetry!"));
  halt();
}

So, it appears they are executing df / | awk '/overlay/ {print $4}' on the YUN.
They're using awk to extract the fourth column ($4) of the line containing overlay (/overlay/), which by the way is awfully hackish.
Given that they expect the result of awk.parseInt() to compare less than 1000 to mean you have less than 1 Mbyte available, it's fairly clear they expected this column to be reported in kilobytes.  And yet in your own df listing
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /

the fourth column is 6.3M and the rest are choosing different units, what is sometimes called "human" output.  So, we know what they care about is the overlay mount point.  And that at the time someone tested this code it either they didn't try an SDCard of any size or the output of df was different back then, which is why parsing something like df isn't a good idea.
And that's about as far as I can take you with any real confidence.  I don't know how overlay is set up on a YUN.
I guess, if you wanted to "fix" the code with a minimal change, it would be to add -k to the df command-line to force kilobyte based output, assuming -k works on whatever df comes with YUN.  If you wanted to go a step further, I suppose you could use -P to get POSIX output from df, again assuming that's supported, and change the expected units in the sketch accordingly.  But if this is just for you, and you know overlay has more than 1 MB free, you could just as easily change the function so it cannot fail:
void haltIfInternalFlashIsFull() {
}

All that said, I wouldn't be surprised if you run into another problem just like this in another part of the sketch.


Apply patch to library for custom changes in Arduino IDE

Save the patch to a file, put it in the directory holding the library,
open a terminal on that directory and type:

patch -p1 < patchfile

You may have to install the "patch" utility if you don't have it yet. On
a Debian-like OS (I don't know for other OSes):

sudo apt install patch


Which board to use for wireless communication of small packages?

WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.

On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.

Also, there are ZigBee module. They developed for home automation specially.


OBOE: Need help understanding, possible type conversion issue

way too complicated:

int convertTo10(char *num_26, int len) {
  int tmp = 0;  //hold the output
  int i;  //indexing the input
  while (len--) tmp = tmp * 26 + (num_26[i++]-'A');
  return tmp;
}

note:
 1. "* 26" can be further simplified;

error checking could be built-in here, or somewhere else (better).
better structuring could get rid of one of the temporary variables.


The setOutputPins() function sets the pins for a pulse for a single stepper. Depending on the used stepper motor a different number of pins has to be set (normal stepper drivers have 2 pins, the ULN2003 and its siblings have 4) in a different way. For that the function first determines the number of pins to use via the _interface member variable of the class.
The mask parameter contains the states of the pins. Each bit represents one pin. If the corresponding bit is set to 1, the pin will be set to an active state. If not, it will be set to an inactive state. Normally an active state (like I have called it here) is HIGH, an inactive state is LOW. But when working with different stepper drivers, some pins might work with an inverted logic. Thus the value (LOW or HIGH) is inverted, if the pin is marked as inverted in the _pinInverted array. This logic is in the line
digitalWrite(_pin[i], (mask & (1 << i)) ? (HIGH ^ _pinInverted[i]) : (LOW ^ _pinInverted[i]));

The idiom condition ? expression : expression represents an embedded if condition. If the condition evaluates to true, the first expression is used, else the second expression. With mask & (1 << i) we are checking, if the ith bit in mask is set. If yes, we use the next expression: HIGH ^ _pinInverted[i]. Here the ^ bitwise XOR operator is used to invert the value, if _pinInverted[i] is set to 1 (and thus marked the pin as inverted). If _pinInverted[i] is zero, the value will stay as it is. The handling of the LOW value is similar.
For understanding that better, you might want to read more about bitwise operators, if you haven't already done so.

why is it [the mask parameter] using uint8_t?

uint8_t is the smallest type, that could be used: 1 byte. As each bit represents one pin, and the library supports steppers with up to 4 pins, only 4 bits are needed at max. Thus using the smallest type with 8 bits is sufficient.

Is this line sending a step signal to multiple stepper?

No, it is setting the pins of a single stepper motor. Each instance of the AccelStepper class represents a single stepper motor. Thus every function in it also only talks to one single motor. You haven't really explained, how you want to add the feedback functionality. But you should not change the AccelStepper class to handle multiple motors. That does not make sense to me. Each motor has to be controlled individually and this class is there to capsule the work behind that. Thats the idea behind making a class for this.
I guess you want to drive multiple motors, each with it's own feedback loop. So then you first need to change the AccelStepper class for supporting that feedback loop. How this is done depends very much on your type of feedback loop. Also the setOutputPins() method is not a good place for that. It is a very low level function. You need to start further up in the call chain, maybe in the step() method or the runSpeed() method (this really depends on how you want to handle the feedback). Also you need to write methods to set up and handle the encoders input. You may need to configure timers and/or interrupts for reading them correctly.
For then supporting multiple stepper motors, you could still look into the MultiStepper class. You could change it to fit with your changes in AccelStepper or write your own wrapping class. That mostly depends on how you want the multiple steppers to behave.


Is it possible to use the Arduino Due's specials pins for digital writing and reading?

Yes, although you may need to modify the variant files to allow access to them.

Every function on the SAM3X8E is a "multiplexed" function. That is, it shares pins with other functions.  For example CANTX0 is an alternative function on pin PA0.

You can find all the alternative function mappings on page 40 of the datasheet.

You may find that many of these pins already have an Arduino pin number assigned to them in the variant file. If that is the case then you can just use it as you would any digital IO pin.

I have included the comments from the variant files here for quick reference:

/*
 * DUE Board pin   |  PORT  | Label
 * ----------------+--------+-------
 *   0             |  PA8   | "RX0"
 *   1             |  PA9   | "TX0"
 *   2       TIOA0 |  PB25  |
 *   3       TIOA7 |  PC28  |
 *   4       NPCS1 |  PA29  |
 *           TIOB6 |  PC26  |
 *   5       TIOA6 |  PC25  |
 *   6       PWML7 |  PC24  |
 *   7       PWML6 |  PC23  |
 *   8       PWML5 |  PC22  |
 *   9       PWML4 |  PC21  |
 *  10       NPCS0 |  PA28  |
 *           TIOB7 |  PC29  |
 *  11       TIOA8 |  PD7   |
 *  12       TIOB8 |  PD8   |
 *  13       TIOB0 |  PB27  | LED AMBER "L"
 *  14       TXD3  |  PD4   | "TX3"
 *  15       RXD3  |  PD5   | "RX3"
 *  16       TXD1  |  PA13  | "TX2"
 *  17       RXD1  |  PA12  | "RX2"
 *  18       TXD0  |  PA11  | "TX1"
 *  19       RXD0  |  PA10  | "RX1"
 *  20             |  PB12  | "SDA"
 *  21             |  PB13  | "SCL"
 *  22             |  PB26  |
 *  23             |  PA14  |
 *  24             |  PA15  |
 *  25             |  PD0   |
 *  26             |  PD1   |
 *  27             |  PD2   |
 *  28             |  PD3   |
 *  29             |  PD6   |
 *  30             |  PD9   |
 *  31             |  PA7   |
 *  32             |  PD10  |
 *  33             |  PC1   |
 *  34             |  PC2   |
 *  35             |  PC3   |
 *  36             |  PC4   |
 *  37             |  PC5   |
 *  38             |  PC6   |
 *  39             |  PC7   |
 *  40             |  PC8   |
 *  41             |  PC9   |
 *  42             |  PA19  |
 *  43             |  PA20  |
 *  44             |  PC19  |
 *  45             |  PC18  |
 *  46             |  PC17  |
 *  47             |  PC16  |
 *  48             |  PC15  |
 *  49             |  PC14  |
 *  50             |  PC13  |
 *  51             |  PC12  |
 *  52       NPCS2 |  PB21  |
 *  53             |  PB14  |
 *  54             |  PA16  | "A0"
 *  55             |  PA24  | "A1"
 *  56             |  PA23  | "A2"
 *  57             |  PA22  | "A3"
 *  58       TIOB2 |  PA6   | "A4"
 *  69             |  PA4   | "A5"
 *  60       TIOB1 |  PA3   | "A6"
 *  61       TIOA1 |  PA2   | "A7"
 *  62             |  PB17  | "A8"
 *  63             |  PB18  | "A9"
 *  64             |  PB19  | "A10"
 *  65             |  PB20  | "A11"
 *  66             |  PB15  | "DAC0"
 *  67             |  PB16  | "DAC1"
 *  68             |  PA1   | "CANRX"
 *  69             |  PA0   | "CANTX"
 *  70             |  PA17  | "SDA1"
 *  71             |  PA18  | "SCL1"
 *  72             |  PC30  | LED AMBER "RX"
 *  73             |  PA21  | LED AMBER "TX"
 *  74       MISO  |  PA25  |
 *  75       MOSI  |  PA26  |
 *  76       SCLK  |  PA27  |
 *  77       NPCS0 |  PA28  |
 *  78       NPCS3 |  PB23  | unconnected!


Arduino output voltages may "fluctuate" a few mV but what you showing us in that gif is really unstable.

What you should be doing is:

Disconnect everything from Arduino except the power source
measure the voltage again;

Is it stable? the problem was because of pulling too much current that causing voltage drop and instability .

Is it unstable?

Try checking with another MM and/or change auto-range to manual.

Is it stable when measuring the voltage with another MM? something was wrong with your previous MM.

Still unstable?

Connect the Arduino to a 9V power adapter and disconnect the USB cable.

Measure the voltage again, if it's stable the problem was because of some error in the cable or USB power source.

Voltage is still unstable?

change the 3.3V voltage regulator.

It should fix the problem if not report back to do some more in-depth problem solving.


Basically with your shield you have two options:

Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal.  The first option is completely out since that rules out all PC communication.  The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).

What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee.  That will leave the Arduino's TX and RX pins free for communicating with the PC.

Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.


"Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.


Simulation of IoT based systems in Software

There are tools to simulate Arduino, but it's not meant for anything beyond basic (i.e. simple circuit). Support is limited, you can't just simulate any and every sensor and shields (e.g. LAN, Wireless). Furthermore, ESP8266 is so cheap that hardly anybody has actual use-case to simulate them. I suggest you work on a real device =)

If you need to simulate data stream into your cloud or IoT platform, I suggest you just spin up a machine and run some code to generate data.


The servo sweep library code - "delay" versus "in steps of"

Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:

Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).

In order to perform four 60° movements in one second you should wait roughly 4ms between calls.

In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.

Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.


At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.

Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.

The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.

It's still the same chip, and still connected up in the same way.


How do powering arduino both barrel jack and lipo battery together?

As is described in this post from the arduino forum, There is a MOSFET switch in series with the USB connector +5V input line.  If the battery booster 5V output is connected to the USB input jack, then it will automatically power the UNO whenever power is disconnected from the barrel jack, and will be automatically disconnected whenever at least 7.0V is available at the barrel jack.
If you are experiencing over-heating problems, then you are probably overheating the linear regulator that steps down the barrel jack voltage to 5V.  You need about 7-7.5V at the barrel jack to overcome the 2-2.5V loss through the linear regulator, but anything higher than about 7.5V will just cause the linear regulator to get hotter.


Cast from uint8_t* to char - loses precision

Well, you are trying to cast pointer to uint8_t to one character, so it warns you about that. If you cast it to pointer to char, it should work:

JsonObject& root = jsonBuffer.parseObject((char *)payload);


Arduino in Eclipse IDE: How to add SPI library (core library already added)?

As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)

The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.

In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.

As such there is no SPI.a file created during the compilation process.
In CDT you can have both options (with or  without .a file) but the Arduino IDE way is the easiest, by far.

So lets first assume you want to compile the "Arduino way" aka without SPI.a.
What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path.
That is all there is to it.

If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build

Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.

I would strongly advise to start your arduino eclipse development with my arduino eclipse plugin because it is simply easier. Later you can evolve to the full freedom of CDT.

If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.


Creating and Arduino synthesizer without the tone library

You just have to add the waveforms. For example, if you want to play
pure tones (the simplest and most boring timbre), you generate a sine
wave for each of them and add them together:

struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}

The function output_sample() should be called as frequently as
possible. You can change the notes array any time to add, remove or
change notes.

There is some room for optimization here, like:

storing 2*M_PI*note->frequency*1e-6 as the “frequency” in order to
save some calculations
using a wave table instead of the cos() function (I don't know how
good is the Due at transcendental math)
replacing elapsed_time by a constant if you can manage to output the
samples at a fixed rate.

Edit: I wrote “You can change the notes array any time to add,
remove or change notes.” Here is how to start or stop a note, i.e. to
add or remove it from the list of active notes:

// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}


Arduino ethernet shield not responding to every request because it is busy

The delay was occurring because, in some cases, I was storing the RS232 data into a character array past the initialized length. It looks like it was causing the Arduino to reboot.


Are hardware interrupts used while controlling an LCD screen using the LiquidCrystal library?

The LiquidCrystal code shows that delays are used. That can cause audio glitches in the sound.
The LiquidCrystal library does not use interrupts.

You could try to change the LiquidCrystal code according to the instruction on the Mozzi page.


2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:

2500L * 1000L == 2500000L

Floats work also, but are more expensive:

2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


Can I cause breaking the main loop from an interrupt?

It is possible. You could use a setjmp()/longjmp()
combination, or you could just manipulate the stack in assembly right
before returning from the interrupt. This however, makes the program
very difficult to reason about, which can easily lead to introducing
very hard to find bugs. It is certainly not a good solution for your
specific problem.
The straightforward solution to your actual problem is to make your loop
non blocking, and this is achieved with the technique explained in the
Blink without delay Arduino tutorial. Your case is a little bit more
complex, as your LED can be in three modes. I suggest you consider
instead that it can actually be in four modes by saying that, while
it's blinking, the ON and OFF states are different modes:

static enum { OFF, BLINK_OFF, BLINK_ON, ON } mode;

I would let the interrupt handler take care of the button-controlled
mode switching:
void switchMode()
{
    // Debounce.
    static uint32_t last_interrupt_time;
    uint32_t interrupt_time = millis();
    if (interrupt_time - last_interrupt_time < DEBOUNCE_TIME)
        return;
    last_interrupt_time = interrupt_time;

    // Switch modes.
    switch (mode) {
        case OFF:  // OFF -> blink
            digitalWrite(LED_PIN, HIGH);
            mode = BLINK_ON;
            break;
        case BLINK_OFF:  // blink -> ON
        case BLINK_ON:   // ditto
            digitalWrite(LED_PIN, HIGH);
            mode = ON;
            break;
        case ON:  // ON -> OFF
            mode = OFF;
            break;
    }
}

And the loop() only has to deal with the blinking:
void loop()
{
    // This only has to handle the timing of the blinking.
    uint32_t now = millis();
    static uint32_t last_toggle_time;
    switch (mode) {
        case BLINK_OFF:
            if (now - last_toggle_time > TIME_OFF) {
                digitalWrite(LED_PIN, HIGH);
                mode = BLINK_ON;
                last_toggle_time = now;
            }
            break;
        case BLINK_ON:
            if (now - last_toggle_time > TIME_ON) {
                digitalWrite(LED_PIN, LOW);
                mode = BLINK_OFF;
                last_toggle_time = now;
            }
            break;
        default:
            // Nothing to do in the other modes.
            break;
    }
}

Another option is to have the interrupt handler only set a flag to
signal the button press. Then loop() would take care off all mode
changes. This can be a good option if you want the “state machine” (the
control of the mode) contained in a single function.


: Failed to open /dev/ttyACM0 (port busy)

sudo apt-get purge modemmanager
It helps me for linux user and for many other peoples.
Now I am playing with stm32f103 and opening port was painfull.
That  was problem only for stm32 chip. Arduino nano was working without problems.
Before I need reopened few times port to initiate communication.
That was painfull. After finding that solution now Arduino ID is working without problems.
 I am not sure if deleting modemmanager will have impact for my system.


Arduino with bmp280 sensor not entering void loop

It could be a faulty library/sensor, most likely the sensor, sometimes sensors can begin but then another connection could be faulty or the chip itself is faulty and so the Arduino might just be waiting forever for a response that will never come.
To see where it gets stuck, you can add Serial.println(F("1")); after bmp.setsampling then Serial.println(F("2"));  after bmp_temp->printSensorDetails to see where exactly it's getting stuck
One thing I also like to do is to buy two/three of a sensor, so that I can replace a sensor with another one. That way if a piece of code doesn't work for all three sensors then I can pretty sure it's a problem with the code and not the device. Not sure if you have a spare sensor to try that but I would recommend it in future


Press on pressure sensor, then wait 5 seconds, turn on LED

The basic concept for tracking timing in the loop() is as follows:

1) when your event occurs, you store the current time in a variable:

unsigned long lastReading = 0;
uint8_t waiting = false;

if ( !waiting && fsrReading > 1022 ) {
  lastReading = millis();
  waiting = true;
}

2) you compare the lastReading variable against the current time and when enough time has passed, you can perform you timed action. ie:

int timeToWait = 5000; // 5 seconds

// are we waiting? and has enough time passed?
if ( waiting && millis() - lastReading > timeToWait ) {
   waiting = false; // reset

   // Light up lights
   ...
}

Note: this specific implementation only requires the sensor to rise above 1022 once, then wait 5 seconds before executing the timed action. If you want the sensor reading to be maintained above 1022 for the entire duration then you would add a check for a release with something like:

if ( fsrReading < 1022 ) {
  waiting = false; // reset because reading fell below 1022
}


How does the microcontroller know which clock to use?

Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.


Arduino Uno WiFi - WiFi mode keeps changing

OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to http://<IPADDRESS>/wifi/info you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to http://<IPADDRESS>/wifi/setmode?mode=<MODE> to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'.
I've created a little cron job on my server that checks the wifi mode and changes it if needed.


Arduino stops logging data after ~32761 seconds

Instead of comparing absolute times you should use the following:

unsigned long now = millis();

if(now - time_last_log >= freq){
    logCount += 1;
    LastLoggedDate=date;
    DataLogg(date);
    time_last_log = now;
    // or if you really want fixed intervals
    // time_last_log += freq;
}

This is guaranteed to be overflow proof.


How to detect if the arduino wire is still connected

You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.

digitalWrite(Ax, INPUT_PULLUP);

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.

Otherwise, use some vinyl duct tape.... this would securize the thing a bit!


I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.


How can I make an AC analog voltage with Arduino?

You have a few options:

Use a low-pass filter to round the square wave's edges some so they look more AC-ish.
Use a low-pass filter and have your code create steps of voltage that look AC-ish by varying the PWM widths.
Use an external SPI DAC chip that you can control with more discrete levels to make smoother looking AC.
Look into Direct Digital Synthesis (DDC) to learn more. Google "analog via ddS", lots of hits.


Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library?

The Kinesis 66 (the chip on the Teensy 3.6) has two ADC modules. Each one talks to different pins.

By default the configuration functions in that library configure ADC0, so unless you tell it otherwise, you will only be configuring half the ADC pins.

You should call each of the configuration functions twice, once for ADC0 and once for ADC1:

adc->setAveraging(16, 0); // set number of averages
adc->setResolution(16, 0); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 0);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 0);

adc->setAveraging(16, 1); // set number of averages
adc->setResolution(16, 1); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 1);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 1);


Problem with STM32 and SDFat lib on other SPI port

Ok, I found out that the sdFat library is not supported on stm32 bluepill (sd card HAL peripherals are not enabled), so I decided to use basic Arduino SD library (it uses SPI commands, not HAL).
Also I have to change pins (from SPI1_1 to SPI1_2) in variant.h and PeripheralPins.c files of bluepill board. - And finally it works (SPI1_2).