How to dynamically set pinMode and dynamically write value to pins in Arduino using arrays?

It seems in the LeftToRight method, you didn't comment out enough (or too much), because  you use a for loop inside another for loop which is probably unintended.

In the RightToLeft' method I will try to fix the problem, so you can change theLeftToRight` method similarly.

void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
  for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

The first for loop is to switch off the LEDs, I would make this a separate method, so it can be reused in both the LeftToRight and RightToLeft method, so you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i + 1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

void LED::SwitchAllLedsOff()
{
  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
}

The problem is also, that you always write HIGH to a pin, since it overwrite the possible LOW assignment within the if statement. To correct this you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel ? HIGH : LOW);
    delay(delay_ms);
  }
}

You also can use an if statement, but in this case the ternary (? :)  statement is more clear since the assignment is for a single destination (_pins[i + 1]). So in case i >= channel, it is set to HIGH, otherwise set to FALSE. I also inverted the operator, but you can keep it inverted too.

Third, _channel seems to be the number of elements in the array, if you use it in an index it should start with _channel - 1, so you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel - 1; i >= 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel - 1 ? HIGH : LOW);
    delay(delay_ms);
  }
}

There might be more problems, but the above are at lest some of them.

Also I changed your way of using spaces, although it's a matter of personal style, yours I never saw before (which doesn't mean it's incorrect of course).

(note I have not tested the program).


There is really no reason to save the key as a string, as you are doing. You can just save it as a normal number. Then you can also use the hexadecimal representation on your code:
unsigned long key = 0xB8C4F9;

Then you need to send out each bit of that number:
for (int n = 0; n < KEY_LEN; n++)
{
    if (key & (1 << n)) { //If the bit read == 1
        sendSignal(One);
    } else {//If the bit being read == 0
        sendSignal(Zero);
    }
}

The following is happening in the if statement: (1 << n) will take the value 1 (binary 0b00000001) and will shift the bits to the left by n digits. For example: If n is 2, we get (0b00000001 << 2) = 0b00000100. With this we can select a bit in our number. Then we take that and do a bitwise AND & with the key. That will set all bits to zero, which are not currently selected. The resulting number is zero, if the corresponding bit in key is zero. If the corresponding bit is 1, this will return a number different from zero (which is interpreted as true. Thus we check, if the n-th bit of key is one or zero.

How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

Generally you can calculate the size of an array with the sizeof() function:
unsigned int size_of_array = sizeof(array)/sizeof(array[0]);

sizeof() returns the number of bytes. So to get the number of elements, we need to divide by the number of bytes in each element;
For the way shown above this is not that easy. Normally it is not really needed, since such keys normally don't change length very often. If you find a variable type, which exactly fits your key size, you could use sizeof(key)*8 to get the number of bits in it. But your current value 0xB8C4F9 only needs 3 bytes. I don't know a type with 3 bytes, but maybe somewhere you can get something like uint24_t. Honestly here I would just use a hardcoded size, just like you are using a hardcoded key value.


How does Arduino digital input pin measure its input voltage?

Assuming you are asking about digital input pins on an Arduino:

Digital logic operates at the saturation and cut off regions of the transistor logic used.  Most modern day processors use CMOS transistors.  The logic levels are Low: 0 V to 1/3 VDD and High:2/3 VDD where VDD is the supply voltage.  This information can be found here.

So, if your processor is designed to operate at 5 volts and is likely made of CMOS logic gates, the low level voltage is from 0 to 1.67 volts and the high level voltage is from 3.33 to 5 volts.

But to address your question specifically:  Digital input pins do not measure the voltage.  Not like an ADC input.  Instead, it is agreed that nothing operating normally that is to interface with a digital pin will produce (linger at) a voltage other than those designed to force the transistors into cut-off or saturation.

So do be careful not to do this.  It could result in unexpected behavior.

Now, if you can not avoid voltage between the designated upper limit of the low logic signal and the lower limit of the high logic signal you man need to buffer your signal with a device called a Schmitt Trigger.  This device adds hysteresis to your signal and converts it into either a low or high logic state.  Examples of hysteresis include the thermostat control for your furnace.

A final word, do not exceed the voltage at a digital input to that which is supplied at the power pin of that digital circuit. This can cause all kinds of problems.  Usually this is not a problem as most devices / projects are powered off of one power source.  But in case multiple power supplies are used, keep this in mind.


How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)

Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.


Unable to retrieve heart rate reading and send to JY-MCU Bluetooth

assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works.  Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.

const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

unsigned long myBeatFreq;
unsigned long myBeat;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
    pinMode(signal, INPUT);
    pinMode(2, OUTPUT);
    Serial.begin(9600);

    previousBeatTime = millis();
    myBeat = previousBeatTime;
}

void loop() {
    if ( millis()-myBeat > myBeatFreq )
    {
      digitalWrite(2, HIGH);
      myBeat=millis();
    }
    else
    {
      digitalWrite(2, LOW);
    }

    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
}


Ok, so more info from the OP:

non-electrical engineering students needs a prototyping platform
minimize possible damages, support hot plug-and-play
not too expensive

Dedicated connector
I suggest using standard subD9 connectors. Sensors shall have male pins, while the control board female socket (this makes very hard to do accidental short circuits on the control board). We were using these connectors in a daily basis in a lasershow system, and I was very statisfied. Inexpensive, easy to solder, works with a wide range of cables or separate wires.
In many cases, you can integrate the sensor into the housing of the connector. For example, an IR receiver, an accelerometer, etc. fits well.
You can use off-the-shelf serial cable extenders which makes it very versatile.
Since it is a D shaped connector, there is only one possible way to connect a sensor to the mainboard, and we're golden.
Dedicated connector light
NSL25 and NSG25 are my favorites:
http://www.soselectronic.hu/?str=371&artnum=4927&name=nsl-25-2-g
http://www.soselectronic.hu/?str=371&artnum=4934&name=-nsg-25-2
Although these are inexpensive wire to board connectors, it is very hard to misconnect them. Criping is a PITA, but you can purchase pre-crimped connectors with wires such as http://www.soselectronic.hu/?str=371&artnum=6175&name=-p-35003
One 3 wire female connector with wires costs about 50 USD cent.
Note though that in this case, the control board has the male connectors. By accidentally dropping a coin to the connector, or using a screwdriver, it is easy to run into short circuits. This leads us to the next plan...
Any inexpensive connector with proper electric protection
Probably the most inexpensive solution is to use standard headers and pins. Here you may also wish to buy ready made cables, than start crimping yourself:
http://www.soselectronic.hu/?str=371&artnum=6171&name=-p-2543
This however opens up a can of worms of misconnection:

connection by one or multiple pin off
connection in reverse direction
shorting the pins on the board

Against sorting, you shall have a multifuse on the power pins, say, 250mA. On each IO pin, you shall have a series resistor of 470 ohm, this ensures that no miswiring can destroy the Arduino.
On the sensor-side, things are a little more tricky. You need a shottky (or an equivalent P fet diode) to ensure that reverse polarity connection will not destroy your sensor. If the sensor has output pins, also use a series 470 ohm resistor.
Considering all the hassle, using a standard subD9 connector is a way easier:

it has enough dedicated pins for I2C, SPI, and a generic IO for dumb sensors
the pins can handle more current, and there are more pins you can connect in parallel to have enough power for small motors
it is impossible to misconnect (once all sensor sockets use identical wiring)

Don't forget ESD protection
In any case, it is a good idea to have some sort of ESD protection whenever you have connectors, and wires, and rough external world.
Have at least a TVS diode on the power pins (say, an 5.8V or 6V unidir TVS will do). On IO pins you can use a simple series resistor, or you can opt for a TVS.
During hot plug and play, it may happen that sensitive sensors get powered in a strange way. E.g. first 5V then the sensor output is getting connected, but no GND for a short moment. Some sensor may get damaged in this case. Use diodes to fix this.
For sensors requiring sudden current peaks (e.g. WIFI, or a motor), add at least 470uF/16V electrolyte capacitor right to the sensor end of the connector. This way once the sensor is connected to a long extension wire, you still have acceptable power to use in sudden current peaks.
Some sensors (e.g. IR receivers) are sensitive to power glitches. Consult their datasheet, use the suggested RC filtering network on the power pins.


Why do ESP boards break out the SPI flash pins?

Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?

The ESP32 is not designed specifically for Arduino. There are other boot modes, such as SD card boot, whereby the internal flash is not directly used. In this situation you are free to use those pins as you wish (given that there is a flash chip attached to them).

The "ESP32 Development Board" was not primarily designed for Arduino. Instead it's a generic board designed by Espressif (and copied many times), and is usable with the Arduino core as one of many options.

In short: the pins aren't there for Arduino users, they're there for other users.

Addendum:

The SPI flash pins can also be used for (and are most commonly used for):

Adding more SPI flash chips which then get integrated into the normal memory space and with the internal caching system, and
Adding PSRAM to increase the RAM memory space.

A good example of the latter is the ESP32-CAM which has an SPI-connected PSRAM chip for framebuffering and image analysis connected to the SPI pins.

You can think of them not so much as SPI pins but as the EBI pins of the PIC32MZ or the EMB of the ATMega2560, etc. Used for expanding the memory rather than for adding random peripherals.


Debugging a RadioShack Arduino motor/sensor shield

There is a bit of info on the DC6688F2SCN here: Chip Selection Guide, but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.

If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.

That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the Bs can do a full Amp.

The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.


Questions on how to connect Arduino to Matlab through the serial port

I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.


What Arduino board are they referencing in the guide linked above, that we can just connect to out of the box?

The first Uno WiFi was made in 2016 by arduino.org. It is retired and not available in stores.

  How can I get OTA support for my particular board?

The OTA support for Uno WiFi Rev. 2 is ready or almost ready, but the required additions are not merged in GitHub firmware and library repository even if they wait some months now. It looks like Arduino focuses on something else.


Relationship between avrdude's "programmer" and bootloaders

If you are using the bootloader, you are not using a programmer. The programmer, when used, is connected to the ICSP pins on the Arduino. The bootloader however expects a well-defined sequence of data from the Arduino through the serial port immediately after reset. The bootloader recognizes that (if received) and reprograms the flash.

If you turn on verbose mode for uploading you will see the programmer type:

-carduino

That is, the Arduino is using the bootloader programming method.

See my post here: What happens when code is uploaded using the bootloader?

  Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't).

Yes, with "Upload Using Programmer" you need a programmer, such as the AVRISP which you would plug into your USB port, and then select that as the type of programmer to use. In this case, your Arduino does not need to be plugged into the USB as the serial port is not used for programming.

Note that some programmers supply Vcc (ie. +5V) to the Arduino and some don't. The AVRISP doesn't.

  Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino.

As far as I know, recent Arduino Unos (and probably others) ship with Optiboot. Its main advantage is that it is smaller (only 512 bytes).

  More in general, do avrdude need to know the particular bootloader?

I think the smaller boards use STK500 protocol (see links below) and the larger ones (eg. the Mega) use STK500 Version 2. That is because they have a larger address space. So yes, it needs to know the protocol.

When I switched my board type to Mega2560 the "-c" option changed to:

-cwiring

I am guessing from that, the "arduino" is code for "STK500" and "wiring" is code for "STK500 V2".

Protocols

AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2


Would Arduino Nano be good for Bluetooth + Sound

There are Bluetooth boards and chips that you can connect to a Nano.

You can play sounds with a Nano. Crudely with PWM and a direct connection, for finely with an external digital-to-analog converter.

But if super-smallness is what you are after, there may be better options.

The Blue Bean is a complete  BLE microcontroller on a single board that is smaller than a Nano+board.

If you want even smaller, you could get something like the new Cypress EZ-BLE module...

http://www.cypress.com/products/ez-ble-module-bluetooth-smart

It is a complete programmable BLE system on a tiny module. It is hard to imagine anything smaller than that!


Time delay without using delay() and millis()

You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the maximum delay you can have is 50 days.


Most compact way to power 5V Arduino boards?

I made a torch locator which looks like this:

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.

You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).

I have a page about power saving which might help you with your design.

A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.


Can Arduino Uno's serial handle to foward push through 1-wire protocol?

Ok, so there's two issues at stake here.

Can the Arduino generate a 1-wire protocol with enough accuracy?
Can you transfer the data fast enough through the UART to tell it to do that generation?

You can't just stream a 1-wire protocol through serial and expect it to work.  The low-level serial protocol would very much get in the way.  So you have to send instructions to the Arduino to say "Raise the IO pin" and "Lower the IO pin" and "Tell me when the IO pin changes level", and "Set the IO pin to input" etc.

Each of those actions would be a discrete item that you would have to send.  Given that you could have a single byte per action (send "I" for set to input, send "O" for set to output, send "L" for set to low, etc - Arduino sends "H" if the pin goes high, or "L" if it goes low, etc), what kind of response could you expect?

Well, at 8 bits + start + stop per byte (so 10 bits) at a good fast rate (say 1MBaud), you would expect one byte to take (1/(1000000/10) = 0.00001s (10µs) to transfer.  That's raw transfer speed.  On top of that you then have to add the processing of that incoming data - the Arduino adds it to a circular buffer to allow your sketch to read it, and that takes time, and your program then interpreting it, you could expect a latency of say 15µs.  At maximum stream rate (no breaks between characters being sent at all) you would have a basic granularity of 10µs (processing the last incoming character while the next one is being received).

That's not counting any other factors such as the UART buffers on your computer, latency before the character even gets to the USB port's endpoint, etc.

So all in all there might be a slim chance that you could do it, but it would be very slim and not easy to achieve a stable result.

Far better would be to implement the 1-Wire protocol on the Arduino and just send/receive the control information to tell it to go ahead and do the work and return the results.  After all, that's what the Arduino is designed for - low level interfacing like that.


Arduino program wont work properly for some reason

On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.

Here's a useful pinout: http://t.co/MKtmCILSdj

Here's a Nano pinout:

Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.

If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)


The reason you can't find the answer is because the answer is both Yes and No.

For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C.  The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of foo(int x) you have foo(MyClass *this, int x)) but that's so small as to not be noticeable.

The big differences come when you start playing with polymorphism and other advanced topics.  When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions ("garbage collection"). So you may well end up with bigger code.

That doesn't mean slower code, just chunks of code that are hanging around that never do anything.

Of bigger importance is managing your dynamic memory better than you are used to.  Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily.  Dynamic creation and destruction of objects (new myClass, delete myClassObject, etc) is very bad.  Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances).  Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).


What happens to the Arduino if you don't use a resistor with an LED?

From page 411 of the ATmega328P data sheet, we have a graph of the output current vs voltage.

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.

A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.

I = (5-2)V / 25Ω = 120mA

This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.

That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.


SPI.transfer(buffer, size) does not send data from buffer

SPI.transfer(&SPI_message,2) is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; SPI.transfer16(SPI_message).

To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.

There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].

Cheers!

Ref.

https://www.arduino.cc/en/Reference/SPITransfer
https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137


The ESP8266 connects to open WiFi hotspots, even If I supply a password

It's probably by chance - however it's impossible to know.

Connecting is done by wifi_station_connect(), which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.

However, the sequence is probably something like:

-> Connect
<- Ok, give me a password
-> Here it is
<- Right, you're connected

Or, with no PSK:

-> Connect
<- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.

Can you force it? Not without knowing what's going on in the mystery wifi_station_connect() function.  There is nothing much in the documentation for the SDK that even hints at a clue.


First you need to think about your axes configuration, then about the actual implementation. I for example can directly think of 2 options:

You could arrange your axes perpendicular to each other, like a Cartesian coordinate system. Here you might need more parts to build it, than with other arrangements, though it is a sturdy system and the positions and paths are easily to calculate. For implementation there are 2 common ways, both using stepper motors in most cases:

You could let the magnet travel on the 2 perpendicular axes pulled by a belt and stepper motor for each axis. As you have to mount one axes onto the other, you might need to use 2 stepper motors (one for each side) for the first axis (depending on your dimensions, how smooth the axes glide and how much force is introduced by dragging the figurine). This approach is mostly used by 3D Printers, since they need rather fast movement, which is also rather precise, but don't need to accommodate high forces.
Instead of belts and pulleys you could use threaded rods for each axis. The magnet is mounted on nuts on these rods. Rotating the rots will move the magnet over the axis, since the magnet is fixed in it's orientation. The precision is highly dependent on the used rods, but all in all it is often more precise, than belts. But it is also way slower.

You could use only rotational axes, like a SCARA robot. It has a rod on a rotational axis and another axis at the end of it. This approach might use less parts, than the Cartesian approach, but you need good servos to have precise and jitter-free positioning (though you could also go for a geared stepper motor here). Also the arm of the robot can look out under the field quite a bit, when positioning it to the far one side.

All of the above approaches can be way more precise, than you need it. They are all viable options.

I personally would go the first way, Cartesian axes with belts and pulleys. The principle is straight forward and you can easily hide it under your piece of plywood (including a margin for all the mechanical stuff of course).


Arduino pro mini not compiling after changing fuse to 128khz

At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a much slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.


You're going to face significant challenges with this.

The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.

I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack.  The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).

So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.

Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.


How to save the SHA256 with HMAC into a variable instead of serial print?

My solution was making a new function that returns a String with the hash

String GetHash256(uint8_t* hash) {
    char tmp[16];
    String sHash256 = "";

    int i;
    for (i=0; i<32; i++) {
        sprintf(tmp, "%.2X",hash[i]);
        sHash256.concat(tmp);
    }

    return sHash256 ;
}


Arduino motor shield orange/white pin usage

...which pins are mapped to the data pins etc.

The shield page provides a schematic

I would like to know some more information about the orange and white pin blocks on the board

These have the reference printed on the board

TWI IN and TWI OUT
They are the same and are both connected to the same I2C pins of Arduino (SCL, SDA). They are intended to help in case you want to connect more than one device.

OUT 5, OUT 6
Connected to Arduino pins 5 and 6 (PWM outputs)

IN 2, IN 3
Connected to Analog in A2 and A3

The power outputs of L298 intended to drive the motor are the blue screw connectors.


Can all Arduino Due pins be used as digital input/output?

Bear in mind that this has nothing to do with "Electrical Engineering".
This simply is an arduino question. And should be asked on arduino Stack Exchange.

Yes.

They can be used as input/output pins. [Simple 'tutorial']
If that even isn't enough or not working on your type of arduino, you can use I/O expanders or shift registers.
Check them out on the internet. [I/O expanders]


That seems to be pronto hex format for codes. A quick google showed this explanation: http://www.remotecentral.com/features/irdisp2.htm and this sample code: https://gist.github.com/probonopd/5793692


It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.
Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

In that diagram the red arrows (not the aerial display team I hasten to add) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.


How do I handle multiple interrupts and outputs simultaneously?

I quite like rachet freaks's idea, however whilst making an example for you his answer hadn't been posted. SO i'll chip in anyway!

In general it is possible to control and measure more than one input and output at the same time by the use of millis(). millis() is an arduino function that returns the number of milliseconds since the arduino fired up.

This probably doesnt sound overly useful to you straight away. But millis can be used in place of delay() if used correctly. Essentially you create a long variable to hold the beginning of an event and check the time since that event started with an if statement. If the difference in the current time and the start time is equal to the time you want the event to occur. Stop the event.

I appreciate my explanation might not be overly clear. So I wrote an example sketch. The sketch has two button inputs. And two button outputs. If one of the buttons is pressed one led will blink for 10 seconds, pressing the button mid blink will extend the time the led blinks by another 10 seconds. Whilst this is happening if you press the second button the other led will turn on, but only when the button is pressed. Using delay() to achieve this would not work nearly as well.

//Setup led and button pins
int ledPin1 = 3;
int ledPin2 = 4;
int butPin1 = 5;
int butPin2 = 6;

//Setup timers
unsigned long currentMillis = 0;
unsigned long blinkStartMillis = 0;
unsigned long ledOnMillis1 = 0;
unsigned long ledOffMillis1 =0;

//Setup variables to store input and output states.
int ledState1 = 0, ledState2 = 0; //State 1 for on, 0 for off;
int butState1 = 0, butState2 = 0; //State 1 for trigger, 0 for off;

//Setup trigger for event
int blinkTrigger = 0;

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(butPin1, INPUT);
  pinMode(butPin2, INPUT);

  delay(500);
}

void loop() {
    //Sets current millis for this loop
    currentMillis = millis();

    //Reads Button States
    butState1 = digitalRead(butPin1);
    butState2 = digitalRead(butPin2);

    //Setup to start blink if button 1 input is high
    if(butState1) {
      blinkTrigger = 1;
      blinkStartMillis = currentMillis;
    }

    //Handles Blinking
    if(blinkTrigger) {

      //If led1 off, and has been off for 500 milliseconds. led 1 on
      if(ledState1 == 0 && currentMillis - LedOffMillis >= 500) {
        digitalWrite(ledPin1, HIGH);
        ledState1 = 1;
        ledOnMillis = currentMillis;
      }

      //If led1 on, and has been on for 500 milliseconds. led 1 off
      if(ledState1 == 1 && currentMillis - LedOnMillis >= 500) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        ledOffMillis = currentMillis;
      }

      //If led1 has been blinking for more than 10 seconds
      //Stop blinking
      if(currentMillis - blinkStartMillis > 10000) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        blinkTrigger = 0;
      }
    }

    //While Button 2 pressed led 2 on
    if(butState2) digitalWrite(ledPin2, HIGH);
    if(!butState2) digitalWrite(ledPin2, LOW);

}

Note: The code style is a bit off because i rushed it, I would also usually use structs to hold the timers and event triggers.

Now for the Wave module rachet is bang on the money, you would need a file for every single note and every single chord.

I hope I helped, if not for your project maybe you may have learnt how to handle more than one event using event timings.


Inaccurate and non-precise voltage reading from Arduino Analog pin

This should be a lot of fun but you might consider doing some research on analog circuits and A/D circuits. You have way too many digits to the right of the decimal, the accuracy is not there. The best you can get is 0.0044 volts per count with a 4.6v reference. What are you using to make your measurements, you need at 5 1/2 digit meter to have the decade better accuracy then what you are calibrating to. Your reference you state is 4.6 volts, something is not correct is should be 5.000V. You know any load placed on the on board regulator will have an effect on your A/D readings. The tolerance of the resistors you are using will have an impact on your reading. They generate noise that could be affecting your readings. 100nF should be enough capacitance,this will lower the input impedance. Increasing capacitance beyond this will slow the settling time of the circuit. If you are powering this from a computer USB expect noise from that power source, That would also explain the lower reference voltage on the A/D. With what you indicate you have, you are actually doing very well.


Slave to Send Data after Receiving Command using I2C

found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups

void loop() {

        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}

void requestEvent(){
    if ( fin == true){
      Wire.write(1);
     fin = false;
    digitalWrite(ledPin, HIGH);
    }

}


Which type of Motor Drivers to drive Unipolar Stepper Motors?

It does matter.  There are pros and cons to each different driver setup.

If you wire the motor as a bipolar, which I'm not sure that you can, you can use the driver that you linked, but it is not very good for driving stepper motors.  https://www.sparkfun.com/products/11876 is a better driver for steppers for half the price.  (still have to wire it bipolar)

If you need to stick with unipolar wiring, PCBheaven.com shows an example using a CD4017, MOSFETs, and diodes to run a unipolar motor.  It will only turn one direction.  Instead you could use a micro-controller, such as an Arduino, in place of the CD4017 along with logic-level MOSFETs to go both directions.

A tutorial on the Arduino site uses a ULN2003A, which is not powerful enough to drive your motor to its full potential (does it need to turn, or turn well?) and doesn't have the diodes (important to protect your IC!), but the Arduino sketches would still work using the schematic from PCBheaven.

A couple of complete driver boards:

UNIPOLAR STEPPER MOTOR DRIVER

FANCY UNIPOLAR STEPPER MOTOR DRIVER


It is a mistake that became a feature for polarizing the shields: forum.arduino.cc/index.php?topic=117441.0

In an 2008 discussion Massimo says:

  "I made that mistake, when I made the first arduino board."

at http://forum.arduino.cc/index.php?topic=22737.msg171839#msg171839
with:


From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.


Connecting DAC output from Arduino Due to another arduino

The inputs to Arduino pins are CMOS inputs, and present very high impedance.  (There is a tiny capacitor on every CMOS input, and the only current into the input is the very small amount needed to charge that capacitor.)

You don't need resistors when connecting inputs and outputs (digital or analog) between Arduinos. Should be the same with Raspberry Pi GPIO lines, or any other CMOS devices.


ESP8266 does not reconnect to WiFi on reboot

The esp8266 SDK libraries starts the STA connection, but it is handled by other thread then the Arduino sketch. You can wait for this connection in setup with waitForConnectResult. It returns status().

  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }

to connect with remembered STA mode, ssid and password, but with static IP address

  WiFi.setAutoConnect(false);
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);
  WiFi.begin(); // uses remembered ssid and password
  WiFi.waitForConnectResult();


Connecting multiple MAX30100/30102 via I2C

LTC4316 is what you need. I haven't used it yet, but I know it from a project that did: mocap. It is an I2C translator IC.

Of course, if you need those ICs to be far away from each other, use a uC (or a separate Arduino) with all of those, and connect them with a different protocol!


How has Arduino been used in the classroom?

I've used Sparki from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.

Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.

The Community seems pretty active and engaged too so the material should build over time.


How do I send a string from an Arduino Slave using SPI?

Remember the master controls the transmission (provides the clock), however it can be done. For example:

Master

// master

#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (1000);  // 1 second delay
}  // end of loop

In this example the master initiates a transmission by sending 0x01 to the slave. Then it gets bytes back until a 0x00 byte (signifying the end of the string). The delayMicroseconds is there to give the slave time to respond.

Slave

// Slave

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

volatile char buf [20] = "Hello, world!";
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

}  // end of loop

The slave does everything inside the ISR. The arrival of the 0x01 byte makes it reset its "pointer" to the start of the buffer. After that it responds with another byte from the buffer until it has reached the terminating 0x00 byte.


You could achieve that by this simple rewrite:

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

volatile bool changed = false;
int i = 0;

void loop() {
  if (!changed) return;
  Serial.print(F("Interrupt registered - waiting "));
  Serial.println(i);
  delay(3000);
  Serial.print(F("done waiting "));
  Serial.println(i);
  i += 1;
  changed = false;
  clearInterrupt(digitalPinToInterrupt(2));
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void test() {
  changed = true;
  detachInterrupt(digitalPinToInterrupt(2));
}

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);

An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:

volatile bool changed = false;
bool waiting = false;

const unsigned long waitIntervalMillis = 3000UL;
unsigned long waitStartMillis = 0L;

int i = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void loop() {

  // Check for change
  if (!changed) return;

  // Check for change before wait interval
  if (!waiting) {
    Serial.print(F("Interrupt registered - waiting "));
    Serial.println(i);
    waiting = true;
    waitStartMillis = millis();
  }

  // Check if wait interval has expired
  else {
    unsigned long currentMillis = millis();
    if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      waiting = false;
    }
  }
}

void test() {
  changed = true;
}

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).

Cheers!


I find the ATTiny85 working well with software serial port. Serial UART (or in fact any of the protocols like I2C or SPI) are just bit banging - and you can do that pretty well in software. Of course, having a hardware support makes things easier and faster, but there is nothing badly wrong with a software uart either. Except that you have to continuously check if there is some data arrives.

I was using software serial on Adafruit Trinket (ATTiny85) in various projects to talk to a Bluetooth 2.1 module, and it worked pretty well.

Here
http://arduining.com/category/trinket-projects/ they use the same approach to talk to an ESP8266.

You may wish to look for the SoftwareSerial lib for Trinket, or in certain cases you may want to go for the SendOnlySoftwareSerial lib (send only, but smaller code footprint).

Also a hardware based serial lib is available:
https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/


A few questions on the first steps with an ESP32/ESP8266 NodeMCU

Checking if everything works fine

  After you connect to the relevant COM port, using either putty, Arduino IDE or any other method, what are some basic commands to check the version and the status of hardware in general?

Program it. If it behaves as you expect then it's working.

  Reassuring a restore point

  Is there a way to keep the initial/factory firmware in some kind of image? Or is the basic firmware stored in some kind of ROM that can't be changed by a user no matter what? In other words, is it possible to "brick" a NodeMCU in case something goes wrong, and how to prevent that?

Why would you want to? You can just download it. And "bricking" is hard, since you are programming the board afresh every time you hit "upload" in the Arduino IDE.

  Restore from backup

  What is the proper reverse process to restore a NodeMCU to a previous state?

You just upload whatever you had loaded on there before.

  C / microPython

  I have seen some projects using microPython instead of C, what is the standard way for start using a NodeMCU with microPython?

Install it, then interface with it, however that is done. We're Arduino here, so we support using the ESP8266 etc with the Arduino API. We don't support MicroPython.

  LUA (LUA shell)

  What exactly is the role of LUA in a NodeMCU? Is it just the interface a user has available after the COM connection?

It is another programming language. Like MicroPython. Use it if you like - however, it's a dying language and learning it is not recommended. Again, we don't support Lua.


It would seem you are attempting to power the motor's coils from VIN of the Arduino. If you are powering the whole system from USB or from the barrel connector on the Arduino, then it's likely that the small voltage regulator on the Arduino cannot supply sufficient current to the motor.

You should connect the black and red wires of the ESC directly to a high-current power supply, and ensure the black (GND) wires of the ESC, power supply, and Arduino are tied together.


For most purposes, a global variable is no different than any other variable. For example:

int var1;

void setup()
{
    int var2;

    var1 = 123; // global
    var2 = 123; // local
}

You can assign to global and local variables in the same way.

The only difference is that you need to be careful if you're using a global variable in an interrupt. You may need to declare it as volatile for it to behave correctly elsewhere in your code. If you don't know about interrupts then you probably don't need to worry about that though.


LinkNode D1 Serial stops working when using pinMode

Move int greenLedPin = D1; and int redLedPin = D3; to another pin, because D1 and D3 is Tx and Rx.

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html


Perhaps you could count the number of lines in the console and the print out enough carriage returns ("\n") to fill it with empty whitespace.

For example, with a console with 100 lines:

for(int iter = 0; iter < 100; iter++) {
   client.write('\n');
}


If you are trying to toggle the LED when a signal comes in, then there is a glitch in the code and I have no idea how the UNO worked for you as I tried and it only spat out Serial, but didn't do anything with the LED.

Try changing this line of code:

state != state;

to

state = !state

you are not actually toggling the LED state with the other line, but instead doing a logical not equal to which won't do what you want.


Fastest way to test if two integers differ by 4 or equal to each other

If you need to do the same comparison 4 times you can just put the result into a boolean variable.

boolean b = (x == y || x - y == 4 || x - y == -4)

if( b )
{
     //do something...
}

If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.

void test(int x, int y)
{
    if(x == y || x - y == 4 || x - y == -4)
  a8:   86 17           cp  r24, r22
  aa:   97 07           cpc r25, r23
  ac:   39 f0           breq    .+14        ; 0xbc <_Z4testii+0x14>
  ae:   86 1b           sub r24, r22
  b0:   97 0b           sbc r25, r23
  b2:   84 30           cpi r24, 0x04   ; 4
  b4:   91 05           cpc r25, r1
  b6:   11 f0           breq    .+4         ; 0xbc <_Z4testii+0x14>
  b8:   04 96           adiw    r24, 0x04   ; 4
  ba:   09 f4           brne    .+2         ; 0xbe <_Z4testii+0x16>
    {
        asm ("wdr");
  bc:   a8 95           wdr
  be:   08 95           ret

first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is 0.

EDIT

As to Dave X's suggestion; using if(abs(x-y)<=4)

void test(int x, int y)
{
    if(abs(x-y)<=4)
  a8:   86 1b           sub r24, r22
  aa:   97 0b           sbc r25, r23
  ac:   04 96           adiw    r24, 0x04   ; 4
  ae:   09 97           sbiw    r24, 0x09   ; 9
  b0:   08 f4           brcc    .+2         ; 0xb4 <_Z4testii+0xc>
    {
         asm("wdr");
  b2:   a8 95           wdr
  b4:   08 95           ret

So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if x==y. So if 90% of the time x==y, the previous code will be faster 90% of the time.

As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If -4 <= x-y < 0 the carry bit is set. Then it subtracts 9 (so it's like (x-y)-5 because of the previous +4). If 0<= x-y <= 4 the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.


The easiest way is to define how many degrees you want to move totally .

In your case it is 180 steps (from 90 to 180, which is 90 steps, and 180 to 90, which is another 90 steps).

Than use a for loop with a 180 step-counter and make 3 simple formulas to map the 180 possible degrees to the wanted servo position.

So the first formula will look like (step 0..90 -> move from 90 to 180, step 90..180-> move 180 to 0).

int calcServo1(int step)
{
    if (step < 90)
    {
        return 90 + step;
    }
    else
    {
        return 270 - step; // 180 - (step - 90);
    }
}

For the second it should be:

step is 0..45: first iteration: 90, otherwise 135..90
step is 45..135: 90..180
step is 135..180: 180..135

The code will be something like:

int calcServoPos2(int iteration, int step)
{
    if (step < 45)
    {
        if (iteration == 0)
        {
            return 90;
        }
        else
        {
            return 135 - step;
        }
   else if (step < 135)
   {
         return step + 45;
   }
   else
   {
       return step - 45; //  step - 180 + 135
   }
}

Servo 3 I will leave up to you.

From your main loop you call the positions:

 int iteration = 0;

 while (loop)
 {
      for (int step = 0; step < 180; step++)
      {
         int servo1pos = CalcServo1(iteration, step);
         servo1.write(servo1pos);

         int servo2pos = CalcServo2(iteration, step);
         servo2.write(servo2pos);

         int servo3pos = CalcServo2(iteration, step);
         servo3.write(servo3pos);

         delay(mid);
     }
     iteration++;
  }


Arduino: how can I stop while() when bluetooth send a data?

Your problem is with this line:

while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing = (assignment) with == (comparison).

You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.

Instead you want:

while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."

Now you just need to program in some way of changing the value of mode within your while loop.

You can read more on while loops here:

http://hacking.majenko.co.uk/the-while-loop


You cannot. Wire uses hardware I2C, and on the Uno only A4 and A5 are connected to the TWI peripheral on the MCU. You will need to either switch to a bit-bang I2C implementation or change the protocol you're using.


Check your power source, if you are powering the module from arduino/USB=>part or something like that, there can be not much power for the module.
Also you can try powering it 5v (not 3,3 as they should be powered by reference).

In my case I have had problems reading some types of cards, and I have solved that problems by giving better power supply, also higher power supply than in reference for some of the cards.

"By magic" the cards that were not working started working as a charm.

Also you should check if the cards you are using are all  ISO14443 A

Only that kind of cards is compatible with that reader.
So if you got type B, or other type of ISO cards, that will not be working.
Some of them may use different frequency, there is a bunch of standards around.

Also as said before the cards can be damaged, or could be corrupted if you tried reading UID while writing to the card, the problem is known , and in that case you can damage the UID.

I hope it helps you.
cheers


avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47

I had the same exact problem and fixed it, just by molding the two reset pins on the arduino together. Just check if they are properly connected as the error probably is caused by that.

If that doesn't work, check the LEDs on the board. When you are uploading a sketch both RX and TX should be lightning up.


Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?

Because buying a car is considerably easier and more reliable.  Plus your "friends" don't laugh at you when they see you trying to drive it to work.

Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.


Arduino HTTP Request Fails Slow Cellular Connection

Buffering and flush()

Many arduino libraries suffer of slow communication because the authors didn't use buffering. To not to send every small piece of data over a connection with overhead of protocol bytes use buffering. Data are collected until the buffer is full and then the collected data are send and the buffer is ready for next bytes. The flush() functions sends the buffer even if it is not full, but you do not have more data. (The flush() 'dilemma' was resolved and in Arduino core classes the flush() method is declared in Print class which is the Arduino standard interface for output streams.)

My StreamLib library offers a BufferedPrint class which wraps the target stream and buffers the data to be send over the target stream. Of course, do not forget to use flush() after last data printed.

HTTP data length

It is common practice in Arduino sketches to not to send the Content-length header with POST requests. In most cases it is because when the HTTP headers are send, the size of data is not known. The WebServer then doesn't know if it received all the data and waits until the connection is closed or timeout is reached. It leads to long time until a Web Server sends the response to requesting Arduino sketch.

If the data can be prepared to a string in memory, fill the Content-length HTTP header.

If the data to be send as response or in POST request wouldn't fit into available memory, ChunkedPrint from my StreamLib can be used with HTTP chunked Transfer-Encoding. And ChunkedPrint is an extension of BufferedPrint so the Web Server handles your request without hesitating.


Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?

The 3.3v is regulated and will always output 3.3v if the device is powered on.


Connect 5V relay to ESP32 WROVER B board

Assuming a relay module: check if it is OK to drive it with 3.3V logic when it is on a 5V power supply, or show the specs for us to look at.
Driving a relay module with 3.3V logic is unlikely to harm the ESP32, but it may not drive the relay properly if the relay module expects 5V logic.
Generally, I would even prefer using an external power supply rather than the 5V pin on a microcontroller board to power a relay module.
As long as you connect everything as you describe, it should work just fine (if the relay module accepts 3.3V logic).


Why are LED's receiving different voltages connected to Arduino

After trying another Arduino I realized the problem. I did not use pinMode in the setup for all of the pins. Darn.


Esp8266 not responding to GET request from Android app created using MIT App Inventor

I have found out the solution to this problem. The code that I had written in the Arduino IDE for the Esp8266 was not correct for handling the GET request.  It only accepted data as a simple Web Server and not as a HTTP server. I am posting the modified code below .

https://gist.github.com/TheMagicSmoke/adaae1e4d92f258c88184c8690e68f08


Using 8-bit instead of 16-bit in Adafruit library

Did you read the datasheet of the LCD screen? The LCD expects you to
send the data in a specific format, and you should comply with that
format rather than invent your own and expect it to magically understand
it. If the LCD expects you to send 16 bits, you should do so. Or maybe
it has a 8 bit mode and there is a way for you to tell it “I'm switching
to 8-bit mode”. Read the datasheet to be sure.

If you want to display 8-bit color on an LCD expecting 16-bit, you
should find a way to map the 8-bit values into 16-bit values. The most
obvious way to map the range [0, 255] to [0, 65535] is to multiply the
8-bit numbers by 65535/255 = 257. Which is the same as sending the byte
twice.


Managing 2 ultrasonic sensors without blocking the other

I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.

Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link), credits to "cattledog".

volatile unsigned long LastPulseTimeA;
volatile unsigned long LastPulseTimeB;
int durationA;
int durationB;
//unsigned long startTime;
#define trigPinA 7
#define echoPinA 2
#define trigPinB 8
#define echoPinB 3
void setup() {
  Serial.begin (9600);
  pinMode(trigPinA, OUTPUT);
  pinMode(echoPinA, INPUT);
   pinMode(trigPinB, OUTPUT);
  pinMode(echoPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
}
void loop(){
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPinA, HIGH);
  digitalWrite(trigPinB, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  Serial.print("Sensor A  ");
  Serial.print(LastPulseTimeA);
  Serial.print('\t');
  Serial.print((LastPulseTimeA/2) / 29.1,1);
  Serial.println("cm");
  Serial.print("Sensor B  ");
  Serial.print(LastPulseTimeB);
  Serial.print('\t');
  Serial.print((LastPulseTimeB/2) / 29.1,1);
  Serial.println("cm");

  delay(1000);
}
void EchoPinA_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(echoPinA)) // Gone HIGH
        startTimeA = micros();
    else  // Gone LOW
        LastPulseTimeA = micros() - startTimeA;
}
void EchoPinB_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(echoPinB)) // Gone HIGH
        startTimeB = micros();
    else  // Gone LOW
        LastPulseTimeB = micros() - startTimeB;
}


Standalone Arduino with ATMEGA328P / Serial working, but serial programming not (only once after buning bootloader)

There is a problem with your circuit and the way you have it wired when programming. You have failed to use the RTS line for Serial programming. You need to have that line connected to the RESET of the ATMega328, this is as the bootloader for programming ove rserial will not start if the IC is not reset. Also you should burn the Arduino UNO bootloader rather than the one you chosen.

Seems you clarified you were using the diode as ESD protection, thank you. It is the recommended arrangement if you have a capacitor attached to the reset line in noisy environments.

The circuit between the RTS signal and the Arduino RESET pin needs to be this:

            C
 RTS >>----||------->> RESET(PIN1)
           0.1µF

From the same "Have I bricked my Arduino" that you linked, about 3/4 down Nicks post he mentions the use of serial programming of an Arduino

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

What you can do if you don't have the proper serial programmer with an RTS output, you will have to manually reset the microcontroller to enter the bootloader just as the IDE says "Uploading...".


Its really heavy to give a correct answer, if you don't show us the context where the for loop is used. But I'll try:
There should be a part in the void loop method where you detect that the "bankValue" is down to zero. Like:
if (bankValue == 0)
{

}

First you must be sure that, the for loop is called within this block.
if (bankValue == 0)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    led HIGH
    delay(500);
    led LOW
    delay(500);
  }
}

Then you need a flag int blinkingDone = 0;  to indicate that the for loop has executed. This flag must be initialize with a falsy value, set to trueish after the loop is done and reset if the user "fills" the bankValue again.
Then you could use it as a guard to enter the for loop. Like:
int blinkingDone = 0;
int bankValue = 0;

..... somewhere else

if ( coin inserted or so )
{
  // fill bankValue
  blinkingDone = 0;
}

..... somewhere else

if (bankValue == 0 && ! blinkingDone)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    // led HIGH
    delay(500);
    // led LOW
    delay(500);
  }
  blinkingDone = 1;
}

There are potential better ways to do it. But I don't know your code. So this is the simplest way I can imagine.


Can't get deep sleep to work on Wemos D1 ESP8266

I had to physically connect D0 to RST to wake up the wemos.


Is there a way to update Arduino uno Over The Air

Not with WiFi, nor with Ethernet. People have managed it with Bluetooth, but only because it can create a transparent serial bridge. The bootloader only talks serial, so you have to use something that is serial to program it.

The only possible way is to use another WiFi (or Ethernet) device, such as the ESP8266, to act as a serial bridge to connect the Arduino's serial port (and reset signal) to your computer over WiFi. A bit of a waste of an ESP8266 since that is then the sole task it would have (unless you craft a far more complex sketch for the ESP8266 to allow it to do other things as well).


Serial communication between nodemcu and Arduino Uno

Arduino UNO is 5v logic and esp8266 is 3.3v logic.  You need a level shifter for them to be able to have bidirectional serial link.


What does a higher clock signal frequency actually mean for my AHRS?

What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.

For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.


I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:

#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12

A better way is to use standard C++ constants, eg.

0b00001100

instead of:

B00001100

  Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.


You cannot add C strings (i.e. NUL-terminated arrays of char) with the
+ operator. It only works with String objects. You can, though, add
a String object and a C-string, because in this case the compiler
implicitly converts the C string into a String object:
String phone_number = "901234567";
phone_number = "+" + phone_number;

The last line is interpreted by the compiler as
phone_number = String("+") + phone_number;

That being said, I encourage you to try to avoid String objects if
possible. These use dynamic memory allocation which carries the risk of
heap fragmentation. The same thing can be achieved with plain C strings:
char phone_number[] = "901234567";
char full_phone_number[strlen(phone_number) + 2];
strcpy(full_phone_number, "+");
strcat(full_phone_number, phone_number);

Note the size of the second string: strlen(phone_number) + 2. You need
one extra char for the + sign, and another one for the NUL string
terminator.
Now, with C strings you can do better, and avoid copying: reserve enough
room in an array for the full number (“+” included), and then fill the
digits starting from the second slot in the char array. You can then
add the + sign later:
char phone_number[16];
strcpy(phone_number + 1, "901234567");
phone_number[0] = '+';

Although I personally would write the “+” sign and a NUL while
initializing the array:
char phone_number[16] = "+";
strcat(phone_number, "901234567");


If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}

void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

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

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}


Arduino Pro Mini (5V) Raw Pin and VCC Pin

As others have pointed out, without a current limiting resistor you may have fried the LED. Thus you might need another LED to test with. On a typical LED with a 1.2 forward voltage drop, a 220 ohm resistor will limit current to about 17 mA (i = v/r.)

forward voltage = supply voltage - LED voltage drop
forward voltage  = (5.0 - 1.2) = 3.8

current = 3.8V/220ohms = 17 mA.

Check the specs on your LEDs. 1.2 V forward voltage drop is common on little LEDs. Max current of 20 mA is common as well, but it doesn't pay to go all the way to the max. That's the "do not exceed or you may destroy it" level.


What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it

Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.

The reception code in the core is:

void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0)) {
    // No Parity error, read byte and store it in the buffer if there is
    // room
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    // if we should be storing the received character into the location
    // just before the tail (meaning that the head would advance to the
    // current location of the tail), we're about to overflow the buffer
    // and so we don't write the character or advance the head.
    if (i != _rx_buffer_tail) {
      _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer_head = i;
    }
  } else {
    // Parity error, read byte but discard it
    *_udr;
  };
}


The method is visible from within your sketch. You just need to first create a cid_t struct like this in your sketch:

cid_t cid;  // at the top with the other globals

Then call readCID() anywhere in setup() after the card has been initialized.

card.readCID(&cid);
Serial.print("Serial number: "); Serial.println(cid.psn); // psn is the serial number field of the struct

Check out SdInfo.h for the other struct members.


Is there any way I can turn off the 5V pin?

For energy-efficient switching (along with relatively high-current capability), I recommend using a Darlington transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call  pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.


The green board is an ITG-3500 (3 axis gyroscope) evaluation board of some form.

The blue board is some form of microcontroller evaluation board. It probably has one of the Atmel SAM chips on it since it mentions ARM.

That's about all you'll get from us I'm afraid, unless there is the highly unlikely situation that someone here happens to have the exact same boards as you.


Can I supply the board's 3.3V directly to the AREF pin?

In Atmel's doc8271 pdf (with specification details for ATmega48A; ATmega48PA; ATmega88A; ATmega88PA; ATmega168A; ATmega168PA; ATmega328; and ATmega328P), table 29-20 on page 117 shows R_REF (the AREF input resistance) as 32KΩ (typical).  Section 24.5.2 on page 248 suggests that AREF is to be treated as a high-impedance input or output:

  ... the reference voltage can be made more immune to noise by connecting a capacitor between the
  AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that
  VREF is a high impedance source, and only a capacitive load should be connected in a system.

Also note that there is no reason to connect anything to AREF (pin 21), because on a standard Uno, AVCC (pin 20) is connected to VCC (pin 7), and one can select AVCC as the reference voltage during analog converter setup [as explained below].  Quoting again from section 24.5.2:

  VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin.  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC...

Summary: you can connect the 3.3V pin and the analog reference pin (AREF) directly, but on a 3.3V system  there is no reason to do so.

Selecting AVCC as the reference voltage:  Say analogReference(DEFAULT) to select AVCC as the reference voltage.  According to arduino.cc, this will choose “the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)”.


Waveshare 1.54 inch ePaper display requires 5Vs from Arduino Uno

The answer lies in the FAQ for that display:

  Why the e-Paper cant work with Arduino?

  Answer:

  The I/O level of Arduino is 5V, and the e-Paper should be driven with 3V3. If your Arduino cant drive the e-Paper successfully, please try to convert the level to 3.3V

  You can also try to connect the Vcc pin to the 5V of Arduino to see whether the e-Paper works, but we recommend you not to use 5V for a long time.

So while you can run it from 5V, you really shouldn't, since you run the risk of breaking it.

Instead, you should employ proper logic level shifting to reduce the Arduino's outgoing signals to 3.3V and, more importantly, boost the incoming signals from the display to 5V.


The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.
NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!


What purpose does the yellow and green LEDs have on the Arduino?

The green LED is marked with ON, and it indicates that the Arduino has power.

The yellow LED is marked L and is just connected to pin 13. So when you set pin 13 to HIGH the LED lights up. You can however still use pin 13 for other things.

When the green LED stops shining you most likely have a short somewhere. As the short will drain all power away, so the Arduino has no power left to light the LED(s).


Yes.  The shield is easier to user, but the breakout board you've shown uses the same chip.  I'd suspect that the breakout board, which has a much bigger heat sink, can handle larger motors, though.  You'll need to put wires from PWM and digital pins to the breakout board you're showing, but it's not super challenging to use those.  I've used extremely similar boards in the past, as well as shields, and both work great.  How big are your motors?  If they're WAY too big (the breakout board can only handle 2 amps IIRC) then you'll need something else anyway.


Problems integrating Reed Switch and Solenoid Lock in Arduino Code

The problem is, that you don't initiate the LED's pin to an output. On reset the pin is configured as input. Doing a digitalWrite(led_pin, HIGH) in this state just enables the internal pullup resistor. If you measure the voltage without the LED connected, it will be 5V, but since the pin only provides a very small amount of current through the pullup resistor, the LED cannot light up when connected.

You need to configure the LED's pin as an output through

pinMode(led_pin, OUTPUT);

in your setup() function.

So actually the beginTransaction() function was correctly executed. You just couldn't see it.


Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program

There are multiple threads on how to combine two different sketches. One of the main things you have to do is refactor your code to get rid of calls to delay(). Do a Google search on Arduino blink without delay and read one of the tutorials you find. The idea is to make a call to the millis() function for each thing you want to do on a time intervl, save the current millis count, and then wait until the new value of millis() is greater than the saved value by your desired time interval. By doing that, your code does a very fast series of checks:

"is it time to do <thing 1> again?"

"Is it time to to <thing 2> again?"

"What about <thing 3>"

And repeats.

Then it doesn't freeze the rest of your sketch waiting for time to pass. (That is what delay() does. Everything stops until the delay time has passed, which is bad.)


Problems burning bootloader on custom ATMEGA2560 board for High-powered model rocketry

I have thus far been completely unable to burn the bootloader.

In what sense? What (error) messages did you get?

In your shoes I would be seeing if I can "talk" to the chip. My chip detector sketch will help you to see if the chip is "alive" or not. See my post about Have I bricked my Arduino Uno? Problems with uploading to board

You may possibly have inappropriate fuse settings for your clock source. If you get some sort of response from the chip using the chip detector sketch please post what it is.

  Also to note is that this is a completely virgin chip from the manufacturer, so I'm not sure what the clock settings come as in that case

According to the datasheet, 8 MHz internal oscillator with CKDIV8 fuse set. That should work.

However you need to resolve that before going any further. I would be taking voltage readings at various points.

Make sure you have Vcc at all the appropriate places, and Gnd.
Note that there are multiple Gnd and Vcc pins. You should also have 5V at AVcc.
Check that /RESET is normally high (5V) and check that it drops to 0V during the programming attempt (and stays there).
Check you have decoupling capacitors between Vcc and Gnd where necessary.
Assuming you have the TQFP-pinout chip, make sure that you have your SPI connections at pins 19, 20, 21 and 22.
If you have a scope or logic analyser make sure that there is some "action" on SCK, MOSI pins during attempts to program it. There should also be a response on MISO.
There should not be a capacitor in series with /RESET as I have occasionally seen people do. The programmer has to hold /RESET low during the entire programming sequence.


Firmware gets stuck at obj.printto(client) in esp32

I see that you are using SSL. SSL uses a lot of RAM and it is possible that the stack and the heap are colliding which will corrupt the running sketch. I recommend you add the amount of free heap to your log statements so that you can see how it changes, which will help you see if this is what is happening.

To obtain the free heap you can use esp_get_free_heap_size() - there's more documentation about this function in the espressif online documentation.


DC motor with L289N driver cannot set RPM lower than 130

Looks like you are controlling two motor outputs via the H-bridge, where the logic inputs are in1,in2 and in3,in4.  First of all, you need

pinMode(in1,OUTPUT);
pinmode(in2,OUTPUT);

One reason why the motors may not spin for analogWrite value less than 130 is that, coincidentally, the voltage output is too low and motor stalls.  Test this two ways: does (1) changing the motor supply voltage or (2) changing the argument of analogWrite actually change the speed?

If no, it may be that pinMode(enA,OUTPUT); sets the output as digital and should be removed.  In that case a number less than 128 gets interpreted as a logic 0 and the motor will not spin.

P.S. your code can be neatened up using port syntax and bitwise operators.

digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);

can be written on a single line with

PORTD |= _BV(in1);

Also

digitalWrite(in1,LOW);
digitalWrite(in2,LOW);

becomes

PORTD &= ~(_BV(in1) | _BV(in2));


Lipo Battery level display using nodemcu

It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on


Convert library from using bitbanging to hardware SPI

The standard AVR library has SPI handling. See, for example: http://www.gammon.com.au/spi

You don't have to write a library if you don't want, just communicate directly using SPI.

The datasheet for the MCP3008 has some tips for using an 8-bit SPI system to communicate with the device. In particular this chart:

You can see from that, that you will need 3 x SPI.transfer. I don't have one here to test with, but the code would look like this:

digitalWrite (SS, LOW);  // select device
int result;
SPI.transfer (0x01);  // start bit
result = SPI.transfer (0b10000000);  // single, ch0
result = (result & 0b11) << 8;  // move to high-order byte
result |= SPI.transfer (0);   // lower order byte
digitalWrite (SS, HIGH);  // deselect

Untested, but this should be roughly it.


I just realized, what your actual question might be, so I'm prepending this to my answer:
With I2C and the typical register communication protocol, you have 3 communication patters:

Master wants to write:

Master does transmission with first byte being the address of the register and following bytes being the data, that should be written to the addressed register (and following registers)

Master wants to read:

Master does a 1 byte transmission with the address of the register, that is wants to read
Master starts a request for 1 or more bytes and the slave will send the previously requested register (and following registers, until no more bytes are available or requested)

Some devices have sequential reads. For these devices the register address is not reset, when an operation is done. Thus the master could do more requests and read more data from the registers. Here the current register address is incremented on each read.

This means, that a master write cycle has only 1 transmission (only 1 endTransmission() in the master code), since every first byte in a master send transmission is handled as a register address. Your code snippet does not allow that. To solve that, just remove the check of numBytes and the return statement.

As mentioned in the comments, your question is really unclear. It seems you are asking things, that doesn't really make sense in the context of general I2C communication. So I will go over the basics and then point you in a good direction to solve your problem interfacing the Wiimote as peripheral.
The I2C protocol: This is the general communication protocol, that the Wiimote uses for its peripherals. It uses 2 lines and a master-slave structure. That means, that any communication is controlled by the master (the Wiimote in this case) and the slave (the peripheral, like a Motion+, a Nunchuk or your Arduino) cannot do anything by itself. The I2C protocol has markers for the start and end of a message and can address each slave on the bus with its specific address (which is send before the data). The protocol does NOT include any rules about the content of each message. So when writing code with the Wire library (the Arduinos library for interfacing the I2C hardware), you only get a buffer full of data bytes. It is up to you to interpret these bytes as needed for your application.
Data structure protocol: This protocol is imposed onto the data, that is end via I2C, so this is a higher level of abstraction and does not really have much to do with the I2C interface (you could use this data structure protocol with any binary communication interface, that has the concept of separated data packages). The data structure protocol defines the logic of the communication.
Here the registers come in. I2C is often used to interface simple sensor chips. These chips work by reading and writing to their internal memory. So the I2C interface exposes this internal memory to the master, who can now configure the sensor by writing data to the internal memory of the sensor, or read data from it.
An example: Lets imagine a simple distance sensor. It has 2 bytes/registers of internal memory. The first byte/register is for configuration of the sensor; the second byte/register represents the measured distance. The common communication protocol for such a chip can be:
Master sends the address of the register, that it wants to access
if Master wants to write to the register
    Master sends bytes to the slave
    Slave saves bytes into previously chosen register (and following registers)
if masters wants to read form the register
    Master requests X bytes from the slave
    Slave sends X bytes with the content of the previously chosen register (and following registers)

The I2C master now wants to configure the sensor (for example setting the measurement frequency), thus writing a corresponding byte to the first byte/register. It will first send the address of the configuration register to the slave, which is 0 (first byte/register). Then it will send another byte, which is the new value of the configuration register.
Then our I2C master wants to read the distance measurement the sensor. For this it first sends the address of the register, that holds the distance measurement (1 aka second byte/register). Then it will request 1 byte from the slave. The slave will then send the content of the previously chosen register (register 1 aka distance measurement register).
So for the slave, the first byte of a Master send transmission is to be handled as a register address. More complex slave classes might have a 16bit (2byte) register address or even more.

Now to your problem mimicking a Wii Motion+. The description on the site, that you linked to is rather difficult. Unfortunately I cannot help much with that. But you can try to use an already existing library, that mimics a Wiimote peripheral: Arduino-Wiimote
I cannot guarantee, that is will work, but it is definitely a good start. If you don't want to use a library, but implement this yourself, you can still learn from how the library does it.
With more searching (for term combinations like "github wiimote arduino") you might find more libraries for this. I have only invested a limited amount of time.


Thank you gre_gor. You were right about correct pins. If you want start ESP on "normal mode" you must plug pins like:

(ESP) GND ------- GND
(ESP) GPIO15 ---- GND
(ESP) VCC ------- VCC 3.3V
(ESP) EN -------- VCC 3.3V
(ESP) GPIO0 ----- VCC 3.3V
(ESP) GPIO2 ----- VCC 3.3V

But if we must use GPIO0, GPIO2 and GPIO15 how we have 9 GPIO, 2 UART and 1 ADC?


Connecting an Arduino Nano, Mega and LCD via I2C works but fails when shutting down Mega

See
How to setup an I2C bus which stays valid if a slave is powered down or fails?

Basically I2C uses pull-ups to have all lines HIGH until any device bring it LOW. Arduino uses INPUT_PULLUP / OUTPUT+LOW states for this. But if you switch Arduino off (turn off Vcc), internal diodes cut the power on pins to Vcc (which is zero) +diode voltage (which is small), effectively to logical LOW. And I2C see that as the device is activelly sending LOW all the time - so communication is blocked.

If you just add pullup resistors, you either have them high enought so it not prevent this state or you have them low enought to draw the lines HIGH even when there is LOW on device, which prevents other devices to draw them LOW for communication. You need "cut off" such incactive lines - either physically disconnect (pull wires from connector - such as if you just get the Mega out of socket, or use some relays powered from Mega Vcc, which disconnet them when the power goes out) or electrically disconnect - using some circuits designed for it. There are some already sold or you can create your own to the same efect (if you are skilled in this area - otherwise it is much easier and faster to pay for some already made solution)


What are the distances between Arduino Mega connectors?

The pin layout and dimensions of the Mega are as follows:

Dimensions are in thousandths of an inch. Source


A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's RX/TX pins, you'll have to go through an RS-232 transceiver chip.

It also gets its power from the RTS line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!

Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
The X delta was encoded in the second byte;
The Y delta was encoded in the third byte.

  http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
The leading bit was still used to indicate start of packet;
The X, Y (and Z) wheels still indicated deltas.

  http://www.cpcwiki.eu/index.php/Serial_RS232_Mouse


Help understanding Print::write()--it calls write()--where is write() defined? Help reading code

write is implemented in the class that inherits the Print class - such as HardwareSerial.

There are a number of write functions, and they are overloaded, which means that they are all distinct functions identified using their parameters as well as their name (write(uint8_t) and write(uint8_t *, size_t) are different functions).  The child class overrides the write(uint8_t) function that is pure virtual1 in the main Print class, but the other write functions with other parameter lists aren't overridden and are just "used".

The using Print::write tells it "the write functions to which I am referring are from the Print class."

  Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

I'm not entirely sure why they feel they need to use it, since the write functon(s) in Print are public and thus exposed already.

  What does it mean/how does it work defining functions in .h files? I've never done this before

Exactly the same as if you had defined the function in a .cpp file, but with a few minor differences, the most important one of which is that the compiler finds it easier to inline the function (or if you're really lucky eradicate the function altogether). It's great for simple functions such as setters and getters that just set or return the value of a variable. In such cases inlining is desirable, and the compiler may even be able to replace the entire function with just direct access to the variable (if it's clever enough).

Another important thing to note with functions in .h files is that you can only really do it with class member functions or static functions. Otherwise you end up with compilation errors complaining about multiple definitions if you use the header file in more than one place.

1: A Pure Virtual function (such as virtual size_t write(uint8_t) = 0;) is one which has to be implemented in the child class. Failure to implement it results in a compilation error. The pure virtual function defines part of the interface but doesn't implement the software for it - that is down to the child class to implement.


Class is not tracking changes to a private field

It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.

This is call-by-value (the incoming command is not updated, a copy is passed as parameter):

void Widget::init(Command _command)
...
widget.init(command);

This is call-by-reference (a pointer to command is passed as parameter):

void Widget::init(Command* _command)
{
   __command->registerDevice(...);
}
...
widget.init(&command);

Alternative syntax is:

void Widget::init(Command& _command)
{
   _command.registerDevice(...);
}
...
widget.init(command)

Cheers!


Installing a different firmware on Arduino

To answer the aspect of your question regarding the "firmware" on the ATmega328p MCU used in most of the Arduino boards:

There is no firmware on the ATmega at all aside from the bootloader. The programs you write are running directly on the hardware.

There are certain "fuse" settings which are set with a ISP programmer. However, there are only 24 of them (three bytes), and they largely relate to low-level configuration, and are not what I think you're asking:

There is also the Bootloader, which is a small program that sits in a separate segment of the MCU's program memory and allows it to update itself at startup (which is how all arduinos are programmed). However, it only runs for a short period of time at startup, and is completely removed from memory after the MCU has jumped to the main program.

Lastly, there are auxiliary MCUs (ATmega16U2/8U2) on most arduino boards that are used as USB-serial interfaces, that can be updated to behave differently (e.g. emulate a keyboard/mouse), but again, this isn't actually a change to the core processor, so whether it counts as "installing a different firmware" depends on how you define the arduino.

Really, I'd strongly reccomend reading the ATmega328P datasheet. This is the documentation for the MCU that basically forms the "Arduino". It should address what seems to be misconceptions.


How does the PID controller actually work?

How a PID controller works depends on the particular implementation.

There is a algorithm/library for PID on the Arduino: http://playground.arduino.cc/Code/PIDLibrary and an excellent explanation of the all of functions within it at http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/

Over on stackoverflow and electronics, there are some good questions and explanations that might help:

https://electronics.stackexchange.com/questions/190606/understanding-a-pid-controller
https://stackoverflow.com/questions/14614124/how-do-i-use-a-pid-controller?rq=1
https://stackoverflow.com/questions/21516143/pid-control-value-of-process-parameter-based-on-pid-result?rq=1
https://stackoverflow.com/questions/13542447/i-dont-understand-integral-part-of-pid-controller?rq=1
https://stackoverflow.com/questions/21534996/pid-controller-intuition-for-when-error-0?rq=1


Store floats in and reading them from flash

There is a helper macro in avr-libc that is designed just for this purpose:

#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space.

Use it like:

PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);


How to find the peak value of analog signal?

See if I understand this correctly: For a given time period you want to find the peak.

void setup()
{
  unsigned long int cur_time = 0 ;
  unsigned long int time_elapsed = 0;
  int peaks[20]; // say you want to find 20 peaks , 1 peak for data arriving between 5 secs
  int time_period = 5000;
  int data = 0;
  int mx=0;
}

void loop()
{
   for(int i = 0 ; i<20;i++)
   {
      cur_time = millis();
      while(cur_time - time_elapsed <=time_period)
      {
             if(mx==0)
              { mx = analogRead(A0); }
              else:
               {  data = analogread(A0);
                  mx = max(data , mx);
               }
              cur_time = millis();
        }
         time_elapsed = cur_time;
         peaks[i] = mx;
         mx = 0;
        }
  }

Hope this helps!!


Programming ATMega328p using VP812 programmer (for AVR/Atmel chips)

Yes - the settings created this problem. You have erased and disabled (via default fuses) the bootloader. It means that your application will run perfectly fine on an Arduino board, but you will not be able to flash over USB.

If you want to use Arduino USB bootloader again then you have to follow this guide


Re-visiting the issue, I have found a simple answer:

I set the SPI pins as outputs and inputs respectively:

const int chipSelect = 10;
const int MOSIPin = 11;
const int MISOPin = 12;
const int SCKPin = 13;

and

  pinMode(chipSelect, OUTPUT);
  pinMode(MOSIPin, OUTPUT);
  pinMode(MISOPin, INPUT);
  pinMode(SCKPin, OUTPUT);

Now, before I power down my machine, I do the following:

  SPI.end();
  digitalWrite(SCKPin, HIGH);
  digitalWrite(chipSelect, HIGH);
  digitalWrite(MOSIPin, HIGH);

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!

Thanks for reading!