Learn about:

Built-in pullup resistors in Arduino
Debouncing

and checks this code: https://blog.adafruit.com/2009/10/20/example-code-for-multi-button-checker-with-debouncing/


do digital input pins act as a positive or negative

Digital pins sink or source current. They don't provide negative voltages. If the pin is set to INPUT then it is high impedance and will not "send out positive voltage".

However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.


How to convert Arduino GSR values to microsiemens?

A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.

You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads.
Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.

https://en.wikipedia.org/wiki/Siemens_(unit)


stdlib.h defines a few psuedo-random number functions. I am not familiar with a random function taking two arguments, presumably the low and high end of the desired range, that you've specified in your code.

For what it's worth, in plain old C use the modulo operator to achieve the range you want using stdlib's srand and rand functions:

/* seed psuedo-random number generator during setup with something */
srand(0xdeadbeef);

and in your function simply use modulus to get your range:

int ranDpart = rand() % 3; /* range: 0,1,2 */
int ranDparent = rand() % 2; /* range: 0,1 */

If your ranges should be inclusive e.g. [0,3] and [0,2] then

int ranDpart = rand() % 4; /* 0,1,2,3 */
int ranDparent = rand() % 3; /* 0,1,2 */


There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.

The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.


The lines in a typical hex file include a VLI (variable length indicator). The hex files output from the IDE might have different lengths than those produced by avrdude. As a simple example:

File 1:

03ABC
03DEF

File 2:

06ABCDEF

Those files will compare differently to each other but convey the same information, split differently between lines.

To do a genuine comparison you would need to account for that.

  Board Type?

Different boards, but with the same processor, might have identical files.

  Microprocessor type?

Different processor would almost certainly have different hex files.

  avrdude version?

Probably not, however see my comments above about the VLIs.

  anything else?

As I said, the compiler may generate lines with (say) 16 bytes per line, but avrdude might read back lines with 32 bytes per line. Thus they would look different but convey the same hex codes, once you allow for that.


Cannot enter programming mode on Arduino Uno

I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.


Arduino Interrupts Classes and Namespace

In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have one single handler for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for this instance), but it can be
a static method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.

I would try something along these lines:

class LcdMenu : public Adafruit_RGBLCDShield
{
public:
  LcdMenu();
  void begin([params]) {
    Adafruit_RGBLCDShield::begin([params]);
    attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
  }
  void MenuFoo();
  void update() {
    if (flag) {
      MenuFoo();
      flag=false;
    }
  }
private:
  static volatile bool flag;
  static void handleInterrupt() { flag = true; }
}

volatile bool LcdMenu::flag;

Then you just have to call LcdM.update() in loop().


Atmega328 PWM frequency setting not working

Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden initialization?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.


An easy way of accessing any type of data in PROGMEM is to use this small library:

PROGMEM_readAnything.h

#include <Arduino.h>  // for type definitions

template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
  {
  memcpy_P (&dest, sce, sizeof (T));
  }

template <typename T> T PROGMEM_getAnything (const T * sce)
  {
  static T temp;
  memcpy_P (&temp, sce, sizeof (T));
  return temp;
  }

You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called PROGMEM_readAnything and put that folder inside the libraries folder, which is inside your sketchbook folder.

That lets you copy from the memory in PROGMEM (using memcpy_P) into RAM. The template is used to work out how many bytes to copy.

Example, using your structure:

#include <PROGMEM_readAnything.h>

struct SimulatorRecord
{
  uint8_t iSensorNumber;
  unsigned long lTriggerTime;
  uint8_t iState;
};

const SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
 //    ...   omitted for brevity
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

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

  for (int i = 0; i < ArraySize (SimulatorQueue); i++)
    {
    SimulatorRecord thisItem;
    PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
    Serial.print (i);
    Serial.print (F(" = "));
    Serial.print (thisItem.iSensorNumber);
    Serial.print (F(" / "));
    Serial.print (thisItem.lTriggerTime);
    Serial.print (F(" / "));
    Serial.print (thisItem.iState);
    Serial.println ();
    }  // end of for loop
}  // end of setup

void loop ()
{
}  // end of loop

I found that it decreased RAM usage by 166 bytes, which is almost 28 * 6 (a couple of bytes must have been used by something).

Reference

Putting constant data into program memory (PROGMEM)

Putting PROGMEM into a class

In response to some comments below, this explains how to put the constants into a class.

Alex originally had:

class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

   constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
   //    ...   omitted for brevity
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

   SimulatorRecord PendingRecord;
};

Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:

class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

  static const SimulatorRecord SimulatorQueue[28] PROGMEM ;

  SimulatorRecord PendingRecord;
};

Now in your main class file (Simulator.cpp in your case):

 const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
    { 1, 41708, 1 }
    , { 2, 60692, 1 }
   //    ...   omitted for brevity
    , { 1, 20454580, 1 }
    , { 1, 20456368, 0 }
   };

That now compiles OK.


This statement:

static unsigned long timing=micros();

...only gives it an initial value.  It is not executed during loop.  These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.

This requires the definition to be pulled out, to the file scope:

static unsigned long timing;

void loop(){
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);

Here, the static keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.

Make sure to give it an initial value in executable code somewhere:

void setup()
{
  ...
  timing = millis();  // Just once?  When the alarm is set?
}

... and update it as you do in countTime.

UPDATE  It's not clear from your snippet as to when the timing variable should be initialized, so I originally avoided addressing that.  If it is really initialized just once, at program startup, you can set it in setup.  Otherwise, it should be set when the initial timing value is finally known.


Assuming you are using the EtherCard library you can send a UDP packet with:

ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in hisip and dstPort.

The prototype for the function is:

void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example udpClientSendOnly.ino with the library shows you UDP sending in action.


In general:

There can be only one setup, in most cases you can put the code from all three setup's together, but checkout the code does not interfere, i.e. does not use the same pins. In that case, change the pin numbers if possible (and change the circuit accordingly).
For the loops it can be more tricky:

Check how often each loop should be called. If one loop costs e.g. 500 ms that means the other loops will be called less often, which can affect the precision or even good readout of the sensor.
If all loops are relatively small and the duration do not matter, you can just call them after each other (rename the loops and call them one by one).
If there is a time constraint, than split the lengthy loop in a small part, and call it whenever needed. There is no clear rule for this.

What you can try is:

Check for reach loop how long it takes
Than for each loop add a delay with same time as the other loops, thus:

Test the duration (average) of loop 1, than of loop 2, than of loop 3. Assume loop1 takes 100, loop2 200 and loop3 300 ms.
Test loop1 without calling loop2 and loop3, but just add the delay (200+300=500 ms).
Check if it works, if so, it means you can call the other loops without problems.
Do the same for loop2 (with 100+300ms delay) and loop3 (100+200ms).
If all loops work correctly, than you can call the loop1, loop2, loop3 in sequence.
If not, you have to call the loop(s) that do not work either more often or in a different way.


How can I reduce the redundancy of this code, so one function can perform the task of printing on Serial and Softserial?

Just send your data to a tee: this is a type of pipe fitting where you
push the data through one end and it goes out through the other two
ends. As it happens, both Serial and Softserial (and almost anything
that can print()) inherit from the virtual Print class. You can
implement a tee as a Print that outputs to two Prints:

class Tee : public Print
{
public:
    Tee(Print &_p1, Print &_p2)
    : p1(_p1), p2(_p2)
    {}

    size_t write(uint8_t c)
    {
        size_t count1 = p1.write(c);
        size_t count2 = p2.write(c);
        return min(count1, count2);
    }
private:
    Print &p1, &p2;
};

The write(uint8_t) is the only method you really need to implement to
have a working Print. Then, all the print() and println() methods
will work.

Example usage:

Tee dualSerial(Serial, mySerial);
dualSerial.print("The answer is ");
dualSerial.println(42);

Note that parseInt() will not work, as it is not a method from
Print. But if you think twice, you will realize that parseInt() on a
pair of channels just does not make sense.


Wiegand doesn't have a baud rate as such. It's an edge-based input protocol where it looks for HIGH to LOW transitions on two different input lines.

There are certain timing requirements, in that you can't send data faster than the receiver is capable of receiving and pulses have to be wide enough for the receiver to read, and there is a minimum time for the gap between messages, but other than that there is no defined baud rate.


Changing parameters in Arduino without the IDE

Sounds like you need a Standalone programmer. I offer one, it loads the target device from a program you select on SD card.  Up to 256 programs can be stored on 1 card.
Check it out here  www.crossroadsfencing.com/BobuinoRev17/Programmer.html


Can I damage an arduino by setting pins high with no load

Nope, you should be just fine.

Having a pin set to any state while unplugged will not cause any problems with your microcontroller.


Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
Rin should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
If you use the 6V output system I recommend below then you could allow closer to 3V drop in Rin.
If Imax is 100mA then Rin = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if Rin is used. Without Rin the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.
The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.
9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).
Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.
One superb version of this regulator is the LM2931-N [Data sheet here] - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.
The datasheet description states:

Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.


ESP32 WiFiClient request missing response

You are assuming that all 15000 bytes are available all the time.

They won't be.

Instead of "while available read something" you need to "While not enough has been read, then if available read something".

When reading from (assuming) HTTP you first need to read and interpret the headers (the lines before a single blank line).  One of these will be the "Content-Length:" header, which will tell you exactly how many bytes are in the body of the response. Then you use that to read the right number of bytes from the body.

So the sequence is:

Read line by line for the headers interpreting the ones you need to, until:
You receive a single blank line
Read the data byte-wise until you have read the number of bytes indicated in the Content-Length header.

If you aren't reading from an HTTP server and you are certain that the data is exactly 15000 bytes in length then you need to skip to point 3 above. Never assume that all the data is there. If there is data then read it, and repeat until you have totalled 15000 bytes.


how to get esp32 ip address ,which is being connected to local network

You don't. You configure mDNS (as you already suggested in your question...!) and the client device then queries mDNS to find the device by the name you allocated it.

Look at the ESPmDNS library examples for how to use mDNS.

Edit: if you really want the IP, you can do WiFi.localIP() (station mode) or WiFi.softAPIP() (access point mode).


Wireless Bluetooth USB HUB using Arduino nano

I agree with Majenko. The best way for you is to buy an active USB extension cable, so that you can handle the distance easily (the signal gets refreshed in the cable by active electronics, so that you can use USB over longer distances).

You consider this to be easy, because you haven't dug into the depth of these topics yet. Here are some important information on that:

Bluetooth and USB are fundamentally different. The term "serial" outside of the Arduino world is just a term for one bit after another. It doesn't describe any protocol or working principle. Interfaces as SPI and I2C are also serial interfaces, but that doesn't mean, that they work similarly, not even in their topology and also not in their protocol behavior. A bridge between these different interfaces is better described as a translator. And translation is always difficult.
Serial in the Arduino world means the UART interface. No similarity to USB or bluetooth.
The Bluetooth spec is rather big. There are many types of connection interfaces, that can be build with it. Examples are the UART (Arduino Serial), HID (like a mouse or keyboard on a PC) or audio (like headphones) interfaces. Each connection has it's specific function. The USB spec is even bigger, way bigger to be precise. You would need to understand how bluetooth and USB work at their core for implementing something like that.
The HC-05 is a chip for getting an UART interface over bluetooth. To change that, you would need to reprogram it with a new firmware. I doubt, that any firmware, that you can find in the web, would be sufficient for your case. Not generic enough. Also the chips hardware is limited, so you can only get limited resources out of it. Most likely you have the HC-05 on an adaptor board, which has a voltage regulator on it (since the HC-05 is a 3.3V device). You would need to ditch that board and solder the chip itself.
The Nano is a bad choice for everything involving USB. The Atmega328p on it, that you program when programming the Arduino, does not have an USB interface. For that the Nano has a second chip, the Atmega32u4, which acts as USB to UART adaptor. You would need to hack it to do anything different than that. Doing it is possible, but you would need to ask yourself, why you are trying to do something so complex with such an incapable board. Also the Nano cannot be an USB host, nor a hub. There is an USB Host shield for the Uno, but that also is limited.
Getting anything even remotely near to 12Mbit/s is illusionary. You won't be able to process nearly one bit every clock edge. You already need several clock edges to do very primitive processing (going into an ISR and then moving the data into a different register, as you put it). And the translation between the protocols will not be that easy. You will need much processing power and also quite some RAM and flash (you will certainly need to buffer some data and the program itself will also be very big to implement something like USB). "A little lower speeds" don't cut it there. Even if possible, that would be painstakingly slow in comparison to a real USB hub.
Most of the software, that you would need for such a project, is non-existent. Doing something that complex with such crappy hardware is an edge case. So you would need to write your own USB stack software. As mentioned, the USB interface is very complex and if you need to ask this question, you are currently not capable of doing this (and neither am I).

I don't say it is absolutely impossible to implement a bit USB functionality with the Nano. But you won't get a satisfying result, that you really can use, even if you were an absolute expert on microcontrollers and the USB and bluetooth stacks (which you really would need to be for it). That is at maximum a project, that an expert would do just for the grind, not for real results.

You have a real life problem, that you want to solve. Choose the easiest way and buy an active USB extension cable.


Why is there a clock in my arduino?

Because that is how computers and microcontrollers, etc, work.

  With a 16mhz clock, each line of my program will take 1/16000000 second, right?

No.

  even a very very big line will only take 1/16000000 of a second ?

No.

The clock defines at what speed the machine code instructions are fetched from memory and executed. Most instructions take 1 clock cycle, but some take more.

One line of C code may be compiled into any number of assembly instructions, which then get converted into machine code (raw numbers).  That could be anywhere from 1 assembly instruction to thousands of assembly instructions, depending on what the line does.

  With a 8mhz clock, each line will take the double of the time, right? So the whole "main loop" will take the double time too, right?

Every operation in the chip is governed by the clock. If the clock is half the speed the chip is running at half the speed, so every operation will take twice as long, yes.


WizNet chip on Ethernet Shield oddly hot

According to the WizNet forums this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)


This camera module requires the use of additional hardware, as the camera and Arduino operating frequencies differ, which can result in loss of synchronization and changes to the image, and other connection problems.

Thus, we must use an integrated circuit intermediary, making the connection between the camera and the Arduino. The function of this chip is to receive the camera information, store them and then send them to the Arduino using the digital doors, much faster than if we used the serial communication.

An example of an integrated circuit that could be used is AL422, suitable for treating a video signal, which also is embedded in some OV7670 modules.

Looking like the connection pins behave in 7670, your module should be equal to it. So spare pins to be able to make other necessary connections.

Would better check the connection through the datasheets:

7670 datasheet

AL422 datasheet

An example of project

But to answer your question; You'll need to purchase a piece more if you don't have AL442.

Regards,


Get one of the servo's working at full load & measure the current flowing through it, multiply that by 30.

That's a lot of servos :D


Sounds like there's a basic misunderstanding here.
Setting a pin as "output" mean it'll either supply +5V ("HIGH") or 0V ("LOW"). Both those states are considered "outputs", and the pin can source or sink current in those states. When driven "LOW", the circuit does "input" current to the chip, but that's not what "input" usually means.
"Input" means you can use the pin to read the voltage applied to the pin. When connected to a PWM source, this might manifest as the pin quickly switching between "1" / "HIGH" / "+5V" and "0" / "LOW" / "0V".
Normally, you would use the "input" mode to read things like switches, or potentiometers on the analog input pins.
Your desired use of "current input" pins will require you to configure the pin as "output", and then set it to "LOW", which will make it able to sink current.


How can I send/write two doubles via Bluetooth (nRF8001 Bluefruit LE) in Arduino?

As the link "Adafruit - nRF UART In Detail" describes, the function write(sendbuffer, sendbuffersize); is waiting for a buffer of uint8_t followed by the size of the message.

Here are the step--by-step solution to send the 2 doubles by using that function.

Step1 - convert the floating-point values into a char string.

  In the Arduino environment, the standard format-specifier %f or %lf
  is not well-managed and the function dtostrf() is recommended.

The format is char *   dtostrf (double __val, signed char __width, unsigned char __prec, char *__s) where:

__val is the floating-point value to be converted,
__s is the array of char to store the result,
__width is the number of characters to store the result,
__prec is the number of digit

The conversion is:

char sValueOne[16], sValueTwo[16];
char sBuffer[33];

strcpy(sBuffer,dtostrf(valueOne, 15, 8, sValueOne));
strcat(sBuffer,",");
strcat(sBuffer,dtostrf(valueTwo, 15, 8, sValueTwo));

Step2 - write the buffer over the BTLEserial object.

BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

  Alternate output solution using BTLEserial.print() function.

BTLEserial.print(sBuffer);


In general there is several ways to do it, none of them is the perfect one...

pointer to mqtt at global scope Adafruit_MQTT_Client * mqtt_ptr; and initialize it by mqtt_ptr = new Adafruit_MQTT_Client(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); in setup. Then you have to use arrow operator instead dot to access its methods. Or you can make an alias in loop (or whenever you need it) by Adafruit_MQTT_Client& mqtt = *mqtt_ptr; and access it in the same way as before.
returning reference to static variable created inside of function (singleton), but you have to provide parameters every time, even they're needed only for the first time. The static variable gets constructed only for the first call of function.
For esp8266 there might be available std::optional template. It's similar to pointer, but you don't have to use arrow -> operator. But there might be extraneous copy when you assign (create) it's value.
You can also extend 1. or 2. by own class to hold parameters and then return instance of Adafruit_MQTT_Client


Conditional compilation, how to determine whether a variable has been declared?

Normally you use the "#ifdef" directive.

The opposite is "#ifndef".

For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my_variables.h":

#ifndef MY_VARIABLES_H
#def MY_VARIABLES_H

int counter;
bool flag;

#endif

In this way, no matter how many times you include this file, you only define the variables once.  Because after the 1st time the compiler sees this file, the variable MY_VARIABLES_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.


It isn't working probably because the output of the Arduino isn't simply an on/off signal.

That library uses a pulse width modulated output on the Arduino to drive an LED.  When the LED is "on" the signal driving it is actually pulsing at a very high rate.

I don't know what all you'd have to change to make that work with a direct wired connection.

Another thing that might becausing problems is that without checking, you can't be sure that the signal level you are sending matches the levels that the IR receiver would normally produce.


Arduino uint8_t to String or char- retrieve from usb device

A unit8_t is an 8 bit unsigned integer - it can have any value between 0 and 255, and can be compared to any numeric value in that range.

You can do "further processing" on the received uint8_t value whether it is a printable ASCII value or not.


Blew my arduino pro mini s4 named component

Many Arduinos have a Schottky diode between the power connector and the voltage regulator as a protection against accidental reverse polarity connection. The official Pro Mini, or the Sparkfun variant, does not.
So you can either de-solder the diode or break it off the board using diagonal cutters and then replace it with either a similar diode -- or with a solder-bridge if you are confident about never connecting power the wrong way around.
It's possible (likely even) that other components that look OK visually are actually damaged. Especially if you can't power the board by connecting a regulated 5V supply to the VCC pin.


Your code has no idea when the string is finished. At the moment it is just waiting until the receive buffer is empty (Serial.read() returns -1), but since serial is a slow protocol that could happen at any time, not just at the end of the string.

You need something to terminate your string so it knows when the end is. The most common way is to use a line feed character (\n, character 10) or a carriage return (\r, character 13) or a combination of the two.

char c;
while ((c = Serial5.read()) != '\n') {
    if (c != 255) {
        str.concat(c);
    }
}

// Output the string on the serial debug interface
Serial.print("Read: \"");
Serial.print(str);
Serial.print("\"\n");


Using PWM signal to decrease power of laser over time

I dont know your circuit but...
Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...

To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.

Somewhere to start anyway :)


Can I convert 3.7V to 5V's using 3.3v to 5v converter

No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.

It does not convert voltage, it merely switches.

To create 5V from 3.7V you need either a boost converter (inductor based circuit) or a charge pump converter (capacitor based circuit).


guidance on Mikrobus NFC tag and connecting to arduino

To find an Arduino library for a device, you can search for the term combination

Arduino github <devicename>

because most libraries are hosted on github. The devicename here means the chip on the product, not the product itself. You won't find much for "Mikrobus NFC", but when you search for the chip on it - the  M24SR64 - you can find some promising results.

For example this library, which looks good to me. It was used for this blog article, which is where I found it (though that is a german site. I just wanted to link as reference for the german speakers). It has some examples, that show the usage of the library.

In general: Sometimes there might be no ready to use library for a chip or product to use with Arduino. In that case you need to write that code yourself. Let's take this product as example. It uses the I2C interface and the seller also links to the datasheet of the used chip. In the datasheet you can read, how the chip is used, including the communication protocol, that is imposes on the I2C interface. You could then write the corresponding I2C code using the Wire library.

Fortunate for you there already is a library, so you can first try that.


Setting 10 RGB Strips Independently from Single Arduino

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLED library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

Wiring:

Example code:

#include <FastLED.h>

#define NUM_LEDS 10
#define DATA_PIN 3
#define CLOCK_PIN 2

CRGB leds[NUM_LEDS];

void setup() {
    FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

int hue = 0;
void loop(){
    for(int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
    }
    FastLED.show();
    delay(20);
    hue += 2;
}


You need to isolate the slave device from the I2C bus since it is causing interference with the signals.

Adafruit have published a good application note about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

  2.3.4 Isolation of the powered-down “Lower voltage” section.

  An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
  VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
  below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
  noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
  stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
  may have the same value, e.g. both 3.3V or both 5V.


You cannot "add" character arrays like that. You may try to use a
String object instead, as these do support the + operator as a way
to concatenate them:

String message = (String(celcius) + " deg Celcius, "
               + relativeHumidity + " relative humidity");
const char *c_message = message.c_str();

And then you use c_message in place of your test variable.
Note that only the first element (celcius here) needs to be explicitly
converted to a String object. The other conversions happen implicitly.

Edit: Updated the code to avoid using the internal state of a
(possibly destroyed) temporary object.


HMC5883L not working in continuous mode!

The problem stems from this function:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

  To minimize the communication between the master and this device, the address pointer updated automatically without
  master intervention. This automatic address pointer update has two additional features. First when address 12 or higher
  is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to
  address 03.

So you are actually writing:

REG  CONTENT
0x00 0x07
0x01 Configuration_Register_B (0x01)
0x02 0x01
0x03 Mode_Register (0x02)
0x04 0x00

You need to either start a new transaction for each register you want to set a value in (explicit setting) or rely on the address pointer increment to move to the right register for you (implicit setting).

So either:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

Or, since the registers are in sequence in the address space:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(0x01);
  I2C_tx(0x00);
  I2C_stop();
}

Oh, and don't forget to have an I2C_stop() after reading your register in:

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop(); // <----- MISSING
  Serial.println(reg_dat);
}


Since it's blink without delay, the next loop will happen immediately. Not after the blink function is don't. So loopCount will increment continuously. You don't limit loopCount to 9, so it will after a few milliseconds try to access, e.g. values[12] which doesn't exist. (see @jfpoilpret's comment)

// constants won't change. Used here to set a pin number :
const int ledPin =  13;      // the number of the LED pin

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated
int blinkValues[] = {1000, 1000, 1000, 200, 200, 200, 1000, 1000, 100};
int loopCount = 0;

// constants won't change :
//unsigned long interval = 1000;           // interval at which to blink (milliseconds)

// Number of times to blink
const long blinkMax = 10;
// Counter for number of times blinked
unsigned long blinkCount = 0;

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  blink();
}

void blink()
{
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= blinkValues[loopCount]) {
    previousMillis = currentMillis;
    loopCount = (loopCount + 1) % 9;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

Also note that the blink function will toggle the led, after the interval. So you need to add intervals, for how long the led should be off between flashes. But I leave that for you to figure out.


Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between 0 and 255, and reading that on the other end.

One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.

Where the example master code shows:

// Reading the potentiometer
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 255);
Serial.write(potValueMapped); // Sends potValue to servo motor

You instead write:

// Reading the potentiometer 1
pot1Value = analogRead(A1);
int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
Serial.write(1);
Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

// Reading the potentiometer 2
pot2Value = analogRead(A0);
int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
Serial.write(2);
Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

And on the slave side, where the example has:

if (Serial.available() > 0) { // Checks whether data is comming from the serial port
  state = Serial.read(); // Reads the data from the serial port
}
// Controlling the servo motor
myServo.write(state);

You have to separate out the two possible choices:

if (Serial.available() > 0) {
  servo_num = Serial.read();
}
if (Serial.available() > 0) {
  state = Serial.read();
}

switch (servo_num) {
  case 1:
    myServo1.write(state);
    break;
  case 2:
    myServo2.write(state);
    break;
}

Note that you'll also have to declare the servo_num variable, and instantiate two of the Servo objects. The code above is just a guide.

The simple expansion above is not robust, as it's possible that the 2nd byte is not received by the time the 2nd Serial.read() is called, and then that byte would be caught next time around the loop() by the first Serial.read() call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.

Edit: What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.

You can re-map the servo values to go from 2-255, rather than 0-255, and set the servo_num to either 0 or 1. In the slave, if you get a number <2, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.

Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a delay(100) or something in the loop() function, or change your code to use a millis()-based state machine (see the "BlinkWithoutDelay" Arduino example).


EEPROM put and get not working on ESP8266 (NodeMCU)

The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).


Got it working: my Uno can now wake up a PC. I followed the HoodLoader wiki and I used the HID-Bridge sketches (below). It took about 2-3 hrs.

HoodLoader

HID-Bridge


How to protect my arduino, while hotplugging its power supply and other related electronics

There's usually a number of scenarios that can cause hardware to go poof when you plug it in to a live system.  Most of them you have managed to identify, so I won't go into detail here.

Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.

There are two main critical things to consider when designing your system:

Suppression

Invest in TVS diodes to suppress ESD.  All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression.  Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

Connector

The connector itself is pretty critical.  Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order.  Normally you want your ground and shield to connect first.  Then your power supplies, and finally your IO pins.  Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.

If you can't use a proper hot-plug connector then there are ways you can simulate it internally.  You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through.  Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.

One other small trick is to ensure that all your IO lines have a series resistor in them.  This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware.  470Ω - 1KΩ are good values.


Well I don't know exactly why this work, but base on this question this. To solve this I should add 'inline' keyword in every method definition on the MPU6050_6Axis_MotionApps20.h
Like this:
inline uint8_t MPU6050::dmpInitialize() {
    // reset device
    DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
    reset();
    delay(30); // wait after reset

    // disable sleep mode
    setSleepEnabled(false);

    // get MPU hardware revision
    setMemoryBank(0x10, true, true);
    setMemoryStartAddress(0x06);
    Serial.println(F("Checking hardware revision..."));
    Serial.print(F("Revision @ user[16][6] = "));
    Serial.println(readMemoryByte(), HEX);
    Serial.println(F("Resetting memory bank selection to 0..."));
    setMemoryBank(0, false, false);

    // check OTP bank valid
    DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
    DEBUG_PRINT(F("OTP bank is "));
    DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

    // setup weird slave stuff (?)
    DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
    setSlaveAddress(0, 0x7F);
    DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
    setI2CMasterModeEnabled(false);
    DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
    setSlaveAddress(0, 0x68);
    DEBUG_PRINTLN(F("Resetting I2C Master control..."));
    resetI2CMaster();
    delay(20);
    DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
    setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

    DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
    setIntEnabled(1<<MPU6050_INTERRUPT_FIFO_OFLOW_BIT|1<<MPU6050_INTERRUPT_DMP_INT_BIT);

    DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
    setRate(4); // 1khz / (1 + 4) = 200 Hz

    DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
    setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

    DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
    setDLPFMode(MPU6050_DLPF_BW_42);

    DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
    setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

    // load DMP code into memory banks
    DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
    DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
    DEBUG_PRINTLN(F(" bytes)"));
    if (!writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) return 1; // Failed
    DEBUG_PRINTLN(F("Success! DMP code written and verified."));

    // Set the FIFO Rate Divisor int the DMP Firmware Memory
    unsigned char dmpUpdate[] = {0x00, MPU6050_DMP_FIFO_RATE_DIVISOR};
    writeMemoryBlock(dmpUpdate, 0x02, 0x02, 0x16); // Lets write the dmpUpdate data to the Firmware image, we have 2 bytes to write in bank 0x02 with the Offset 0x16

    //write start address MSB into register
    setDMPConfig1(0x03);
    //write start address LSB into register
    setDMPConfig2(0x00);

    DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
    setOTPBankValid(false);

    DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
    setMotionDetectionThreshold(2);

    DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
    setZeroMotionDetectionThreshold(156);

    DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
    setMotionDetectionDuration(80);

    DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
    setZeroMotionDetectionDuration(0);
    DEBUG_PRINTLN(F("Enabling FIFO..."));
    setFIFOEnabled(true);

    DEBUG_PRINTLN(F("Resetting DMP..."));
    resetDMP();

    DEBUG_PRINTLN(F("DMP is good to go! Finally."));

    DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
    setDMPEnabled(false);

    DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
    dmpPacketSize = 42;

    DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
    resetFIFO();
    getIntStatus();

    return 0; // success
}
inline bool MPU6050::dmpPacketAvailable() {
    return getFIFOCount() >= dmpGetFIFOPacketSize();
}
inline uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[28] << 24) | ((uint32_t)packet[29] << 16) | ((uint32_t)packet[30] << 8) | packet[31]);
    data[1] = (((uint32_t)packet[32] << 24) | ((uint32_t)packet[33] << 16) | ((uint32_t)packet[34] << 8) | packet[35]);
    data[2] = (((uint32_t)packet[36] << 24) | ((uint32_t)packet[37] << 16) | ((uint32_t)packet[38] << 8) | packet[39]);
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[28] << 8) | packet[29];
    data[1] = (packet[32] << 8) | packet[33];
    data[2] = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[28] << 8) | packet[29];
    v -> y = (packet[32] << 8) | packet[33];
    v -> z = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[0] << 24) | ((uint32_t)packet[1] << 16) | ((uint32_t)packet[2] << 8) | packet[3]);
    data[1] = (((uint32_t)packet[4] << 24) | ((uint32_t)packet[5] << 16) | ((uint32_t)packet[6] << 8) | packet[7]);
    data[2] = (((uint32_t)packet[8] << 24) | ((uint32_t)packet[9] << 16) | ((uint32_t)packet[10] << 8) | packet[11]);
    data[3] = (((uint32_t)packet[12] << 24) | ((uint32_t)packet[13] << 16) | ((uint32_t)packet[14] << 8) | packet[15]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = ((packet[0] << 8) | packet[1]);
    data[1] = ((packet[4] << 8) | packet[5]);
    data[2] = ((packet[8] << 8) | packet[9]);
    data[3] = ((packet[12] << 8) | packet[13]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    if (status == 0) {
        q -> w = (float)qI[0] / 16384.0f;
        q -> x = (float)qI[1] / 16384.0f;
        q -> y = (float)qI[2] / 16384.0f;
        q -> z = (float)qI[3] / 16384.0f;
        return 0;
    }
    return status; // int16 return value, indicates error if this line is reached
}
inline uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[16] << 24) | ((uint32_t)packet[17] << 16) | ((uint32_t)packet[18] << 8) | packet[19]);
    data[1] = (((uint32_t)packet[20] << 24) | ((uint32_t)packet[21] << 16) | ((uint32_t)packet[22] << 8) | packet[23]);
    data[2] = (((uint32_t)packet[24] << 24) | ((uint32_t)packet[25] << 16) | ((uint32_t)packet[26] << 8) | packet[27]);
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[16] << 8) | packet[17];
    data[1] = (packet[20] << 8) | packet[21];
    data[2] = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[16] << 8) | packet[17];
    v -> y = (packet[20] << 8) | packet[21];
    v -> z = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
    // get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
    v -> x = vRaw -> x - gravity -> x*8192;
    v -> y = vRaw -> y - gravity -> y*8192;
    v -> z = vRaw -> z - gravity -> z*8192;
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
    // rotate measured 3D acceleration vector into original state
    // frame of reference based on orientation quaternion
    memcpy(v, vReal, sizeof(VectorInt16));
    v -> rotate(q);
    return 0;
}
inline uint8_t MPU6050::dmpGetGravity(int16_t *data, const uint8_t* packet) {
    /* +1g corresponds to +8192, sensitivity is 2g. */
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    data[0] = ((int32_t)qI[1] * qI[3] - (int32_t)qI[0] * qI[2]) / 16384;
    data[1] = ((int32_t)qI[0] * qI[1] + (int32_t)qI[2] * qI[3]) / 16384;
    data[2] = ((int32_t)qI[0] * qI[0] - (int32_t)qI[1] * qI[1]
           - (int32_t)qI[2] * qI[2] + (int32_t)qI[3] * qI[3]) / (2 * 16384);
    return status;
}
inline uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
    v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
    v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
    v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
    return 0;
}
inline uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);   // psi
    data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y);                              // theta
    data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1);   // phi
    return 0;
}

#ifdef USE_OLD_DMPGETYAWPITCHROLL
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
    return 0;
}
#else
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan2(gravity -> x , sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan2(gravity -> y , gravity -> z);
    if (gravity -> z < 0) {
        if(data[1] > 0) {
            data[1] = PI - data[1];
        } else {
            data[1] = -PI - data[1];
        }
    }
    return 0;
}
#endif

inline uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
    return 0;
}

inline uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
    uint8_t status;
    uint8_t buf[dmpPacketSize];
    for (uint8_t i = 0; i < numPackets; i++) {
        // read packet from FIFO
        getFIFOBytes(buf, dmpPacketSize);

        // process packet
        if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;

        // increment external process count variable, if supplied
        if (processed != 0) (*processed)++;
    }
    return 0;
}

inline uint16_t MPU6050::dmpGetFIFOPacketSize() {
    return dmpPacketSize;
}
#endif

I don't know why the guys that made this library didn't add this. Maybe I'm missing something.


Is this assignment valid or needs casting?

First part:

uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
  Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

Buffer[n] will be filled with an uint16_t and implicit casting to an uint16_t will be used. I suggest you do such implicit castings explicitly (so add (uint16_t) ... if you want).

However, if you do not want this, either define the Buffer as float, or at least add + 0.5 to give better roundings (if that is improving, depends on your situation, but mathematically it is better).

thus:

static const uint8_t BUFFER_SIZE = 40000;
uint16_t Buffer[BUFFER_SIZE];

for (int n=0; n<BUFFER_SIZE; n++)
{
  Buffer[n] = (int) (0.99 * cos(((2.0*PI)/BUFFER_SIZE)*n));
}

The next one:

int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

This is also 'compiler-correct', and an int value can be more easier converted to a float. You will not lose digits. However, to make it clear an explicit cast with (int) ... is better.

Thus:

int intVal;
float floatVal = (float) (intVal - intVal*Buffer[intVal]);


Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw

9V batteries can only supply  very little current. So two servo's is too much.

Just use another set of multiple AA batteries for the servo's.


The problem with the circuit was a bad rs232-ttl converter. Not sure how that messed up the openlog, but replacing it fixed the problem.

In the photo above, D1 on the converter is an led which should be normally on.


Detecting if a push button was pressed and released

No, I wouldn't consider that good practice - for one good reason: it's blocking.

Your system can't be doing anything else at all while you're waiting on the button. That may be fine for some situations, but far from ideal for 99% of others.

It is better to remember the state of the button and detect that change of state.

Personally, to make it properly portable, I would implement a class to contain all the state information.  Something like:

class Button {
    private:
        bool _state;
        uint8_t _pin;

    public:
        Button(uint8_t pin) : _pin(pin) {}

        void begin() {
            pinMode(_pin, INPUT_PULLUP);
            _state = digitalRead(_pin);
        }

        bool isReleased() {
            bool v = digitalRead(_pin);
            if (v != _state) {
                _state = v;
                if (_state) {
                    return true;
                }
            }
            return false;
        }
};

Then you can do something like:

Button myButton(3);

void setup() {
    myButton.begin();
    Serial.begin(115200);
}

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released"));
    }
}

Every time myButton.isReleased() is called the current button state is compared against the state it was last time it was called. If it's changed then the button must either have been pressed or released. So you remember that change. If it's been released then you return a true, otherwise return a false.

You can now easily have it work with many buttons:

Button myButton(3);
Button myOtherButton(4);

void setup() {
    myButton.begin();
    myOtherButton.begin();
    Serial.begin(115200);
}

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released 1"));
    }
    if (myOtherButton.isReleased()) {
        Serial.println(F("Released 2"));
    }
}


The 16u2 is related to the ATmega328p, and includes USB, but is more limited in resources.   While it would be possible to make an Arduino-type board from alone, this is unlikely to be what you have.

Rather, it is likely that you have a board with an ATmega328p as the main processor, and also a 16u2 which serves as a USB interface for it.

You could know for sure from what board type you select in the dropdown menu of the Arduino IDE.  If you are selecting something like "Uno" or "Duemilanove" you have a 328p as the main processor.

(The other presently common type of board is the "Leonardo" style where a 32u4 - essentially a bigger version of the 16u2 - is used as a single-chip solution that is both the primary processor and the USB interface.  But if that is what you had, it would not say 16u2 on it, unless it was an attempt to make a more limited "budget" version).


How to use an Arduino Speaker module with DFPlayer Mini?

The DFPlayer already has an amplifier on it, so you can connect the speaker directly.
You can just leave out the board you bought from AliExpress, and only use the speaker.


Arduino onboard LED pin number as a constant

Try LED_BUILTIN:

pins_arduino.h:static const uint8_t LED_BUILTIN = 13;


How to use an Arduino to measure speed of rocket

You can use an accelerometer or a barometre for measure speed and for RF you can use:

Radio NRF24L01
wifi ESP8266
bluetooth HC-06


Get yourself a Arduino Leonardo, Micro or Pro Micro (or Due, Zero, M0). Those can emulate a keyboard.
Start with reading the Arduino Keyboard Mouse reference.

The Arduino Nano can not use the Arduino Keyboard Mouse library.

Since many years, there is a library called "V-USB" that requires some extra hardware and makes it possible for a ATmega328p microcontroller to act as an USB device. It is not something for a beginner.

A few years ago, Arduino has changed the way the USB is used. The NicoHood HID library makes use of the new possibilities. It makes it possible for example to have extended features for a USB keyboard, like the media keys.

For a normal keyboard and mouse, the Arduino Keyboard Mouse library will do. It will be perfect for a ignition button. But you have to buy one of those boards (Leonardo, and so on).


What kind of distance sensor are optimal to measure distances to surfaces at an angle to the sensor?

Using ultrasonic sensors would be a very sensible solution in your use case.
I am currently working on a similar project with a company in Denmark, where the objective is to detect cars on parking spaces. For this task, I used two of these ultrasonic sensors from DFRobot for the prototype:
https://www.dfrobot.com/product-1935.html
They were very easy and simple to setup on an Arduino UNO and worked perfectly fine even when two were sensing at once.
Though I have to mention, that they need a serial connection each, but this can be worked around using a multiplexer or a developer board with more serial connections.
I also found that the ultrasonic sensors work better than time of flight sensors in outdoor conditions. They are very robust and wont be as affected by dirt for instance.
A little speck on the lens of a ToF sensor and it will be rendered useless.
Ultrasonic sensors are also widely used in the car industry for parking aid solutions where they have to detect lots of different surfaces and be very precise in doing so.
Ultrasonic sensors are great. And yes, they can interfere with each other, but as long as you dont put them on top of one another, it should not be an issue.
You should be able to detect the distance to a trailer in two different places using ultrasonic sensors as long as the trailer is within the sensors range.


How to append float value of into a string ?

This has been answered in the previous question but I can repeat it here:

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

An alternative is to use dtostrf() as in your snippet:

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

Cheers!


How to improve response time of this sound operated LED?

I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.

So check more often (reduce the delays) and check for so many sound detections within one second.

Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.


MQTT PubSubClient connection problem with ESP32

When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:

PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
    this->domain = domain;
    this->port = port;
    return *this;
}

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.

It is really intended to work with string literals and global constant variables that never change.

If this is the one and only time that you ever set the server you could get away with using strdup() to duplicate the string data on the heap, but without direct access to the domain member variable of the PubSubClient class you have no way to free() the memory again should you ever wish to change the server.

String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strdup(strSBM.c_str()), port);

To make it so you can free the value you need to keep track of it separately:

static char *temp = NULL;
if (temp != NULL) {
    free(temp);
    temp = NULL;
}
temp = strdup(strSBM.c_str());
mqtt.setServer(temp, port);


If you got zapped touching an LED and the circuit doesn't work any more, and since you're sure the Arduino uploads programs OK, then either the LED (or something else on your breadboard) or the pin driver within the Arduino is probably damaged.

Try changing the LED.
If that doesn't work, try changing the pin(s) the sketch uses to talk to your breadboard, rewire your breadboard to use those pins, and test again. If it works this time, the pin driver was probably damaged.
If there are any other components (e.g., not wires or resistors) on the breadboard whose failure might cause the LED not to light, replace those and test again.
If replacing the external components doesn't fix it, and if your Arduino's MCU is a 28-pin chip in a socket, a new one with the bootloader already loaded into it typically costs $5-$6 in the US.

Update:

  ...i have listed all these things as already tried.

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that must be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.

You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.


How to make arduino show cpu usage with 10 leds?

There's three basic steps you need to cover:

Get the CPU usage of your computer
Communicate that to the Arduino
Have the Arduino respond to the data

We can't really help you with step 1.  That's outside our remit.   You should head over to StackOverflow for that. How you would do it depends on your host OS since each one has its own way of reporting it.

For step 2 you would need to write software for your computer, incorporating what you have learned from step 1.  Once you have the correct data you need to send it over to the Arduino through its serial connection. You'd need to come up with a good way of doing that, but probably just sending the usage percentage as plain ASCII text separated by new-lines is probably simplest.

Step 3 would entail reading in the data you sent in step 2, deciding what the numbers you have got mean, and then turning on the relevant LEDs.

Another option, which might simplify things a little, might be to use something like Firmata, where your PC sends the instructions to turn the LEDs on and off, and the Arduino just becomes a kind of dumb interface that doesn't do much on its own.


First of all you want to buy some solar panels or cells. Although they can be found on eBay for very cheap, but they not be as efficient as they say. I would say try to buy from a reputable dealer to see reviews on the product or trust that they work efficiently. Sparkfun datasheets are generally accurate and can be trusted.

Most optimal configuration: Do not use a regulator and some sort of step-up booster. Try the TPS61200 or TPS61202 chips. They will not regulate the voltage, they boost the voltage dynamically. This is much more efficient and therefore generates less heat. They work like a reverse voltage regulator, taking .3V to 5.5V and turning it into anywhere from 1.8V to 5V (xxx0) or 5V exactly (xxx2). Hack a USB B end and just connect the power lines to the Arduino.
Discharge/charge simultaneously: Yes, however I'm not sure how to. I believe that if you hook up a charger IC and a load, the voltage won't go through the battery, it will go through the path of least resistance. However, your battery wouldn't get charged then. This is outside the scope of the question, so I would recommend EE on how exactly to do this.
Is LiPO the best: Try a Lithium-Ion Battery. (A.K.A. Li-ion) According to this site:

  Although the lithium-polymer battery is sleeker and thinner, lithium-ion batteries have a higher energy density and cost less to manufacture.

Therefore, it seems like Li-ion is the best choice for you. Note: Since you are dealing with very dense batteries that if overvolted can go up into flames [Note: please mute your speakers!], make sure to go with Sparkfun/Adafruit/etc...
Economic way: If you don't mind a big "homemade" solar panel, go this way. Buy through eBay or a similar site solar cells. They are small plates that are connected to create a solar panel. Try looking for "grade B" or similar solar cells that work fine, they just may have minor imperfections. It won't be as pretty, but you'll save some cash.

See this EE.SE post for more information. One cool thing that I saw was:

  This is really cool. You can connect the Li-Ion voltage through an op-amp to generate a pulse wave, which can be picked up by your MPU to tell your bot to go charge –  Raaj Oct 18 '13 at 18:44

I'm not exactly sure how to do this, but it might be useful. I couldn't find anything online about it.


Why does an `.ino` file have to be in a folder of the same name?

AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:

ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

, where myproj.cpp just #include's main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.

Update:

I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could

#include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to #include each of the files in the src folder, if it the compiler doesn't figure out on its own, that that's where your other files are.

BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().


The m library is the "math" library. You have to link with it in most flavours of gnu compilers (it is typically not required in other, as it is included in the standard lib) when using functions and stuff from the header file "math.h".


Detect where pressure is being applied by using force resistors

Let's assume that you have only two FSR sensors. With those you can make three virtual buttons (above the left sensor, above the right sensor and in the middle).

To measure someone's weight, it is allowed to have a scale under each foot and add both weights. We can use that to calculate the total force pressing to the board, by just adding the two forces.

The FSR sensors have a curve to calculate the force in newtons. It is very inaccurate, but works more or less. That can be added later. For now let's assume that it is linear to the ADC value of the Arduino.

Are the FSR sensors connected to an analog input and GND ? Do you have a resistor between the analog input and 5V ? I assume you do. You need the resistors so that a nice pressing force to the board results somewhere in the middle of the ADC range.

Pseudo code:

setup()

  Measure both ADC values (or a number of values and use the average)
  Store them as offsets in a global variable.

loop()

  Measure both ADC values, substract the offset.

  Translate the ADC values into force.
  The more force the higher the number should get.
  Any range is okay for now.
  They can be translated into Newton later.

  The total force is by adding the two forces.

  The position in percentage is the force of the right sensor
  divided by total force times 100.
  Then the position will be 0 for left sensor, 50 for middle
  and 100 for right sensor.

  If the total force is above threshold, then check the position.

  for example position -50 to 20 for left virtual button.
  for example position 30 to 70 for middle virtual button.
  for example positition 80 to 150 for right virtual button.

You can start by printing the forces to the serial monitor. Press the board and check if the numbers increase when pressing more.

Don't get confused when you print the position. It will be very noisy when no force to the board is applied. It should be valid when the total force is above the threshold.

For the position I allow a large error of 50 percent left of the left sensor and right of the right sensor. It depends on the mechanical construction and the rest of the code if that makes sense.

Print the results to the serial monitor.
If that is working well, then you have to detect a single press.

Let's assume that as soon as the threshold is reached, a press to a virtual button is accepted. Let's not wait until the peak of the force is reached.
The State Change Detection example can be used to create a single event for pressing the virtual button.

Any jitter or noise (for example a single press to the board results into two events for the virtual button) can be solved by averaging or filtering in software. I think that it will be needed.

I'm not sure if all of this is okay. I hope that someone else will look into it as well.


How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables?

You can assign the pointer to NULL, and in the setup function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).

#include "Adafruit_NeoPixel.h"

Adafruit_NeoPixel* pixels = NULL;

void setup()
{
  pixels = new Adafruit_NeoPixel();
}


Light communication from pc/app to arduino

Doing bit stuffing can prevent timing problems when you are sending a lot of 0s or 1s in an row. Alternatively use Manchester encoding (slower).

On the browser side, I'd suggest using <Canvas>. Combine this with requestAnimationFrame which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.


In this situation, it may be useful to look at the differential of the signal.

One way to do this is to store the value, wait some time and read another value. You can then do:

dv = current_value - last_value

Or if you have some time metric (Perhaps clock ticks, or a rtc):

dv = (current_value - last_value) / (current_time - last_time)

You would then want to only count significantly large changes in dv. As the day progresses the light value will only change at a small rate but if someone were to block the light then there will be a large difference between current_value and last_value, causing dv to be largely negative (Indicating a loss of a lot of light) and when they no longer block the light you will get the opposite, indicating there is no longer an obstruction. (Or rather, less of an obstruction.)


Buzzer - Does the voltage change with the frequency?

No, the frequency of the "buzzer" has no relationship to the voltage.

The duty cycle of the generated tone is proportional to the average voltage though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the average voltage is 50% of the supply voltage.

If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.

Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.

The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to droop.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


Can I use 5V 1A Adapter to power Arduino UNO?

If we look at technical specifications, it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (never go above 20V). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.


Based on the documentation :

  These core libraries allow a 32u4 based boards or Due and Zero board to appear as a native Mouse and/or Keyboard to a connected computer.

Core libraries (such as Keyboard.h) are not availabe if your board doesn't mentioned.

I don't know which one is right, since your question title mentioned "Arduino Micro" while at the end of your question, the board is "Arduino Uno".

Just for further information, Arduino Uno is based on - ATmega328P, and Arduino Micro is based on - ATmega32U4. So sure, that "hello world" program will works on Arduino Micro, but not on Arduino Uno.


There are several "Arduinos" with memory capacities ranging from slightly less than 32k/2k/16MHz (Flash/RAM/CPUClock) ("Uno") to 512k/96k/84MHz ("Due".)  In addition, there are "mostly compatible" boards that expand that range down to less than 8k/512/8MHz ("Gemma", "Digistump") and up to about 1M/256k/120MHz (TI "EK-TM4C1294XL Launchpad"), and "somewhat compatible" boards with 4G/1G/400MHz (Intel "Edison")

Whether these are sufficient for "full fledged robotics" depends on what you consider that to mean.  Edison is probably the only contender if you wanted to include computer vision, for example, and it probably doesn't do that very well. ("What did you expect at ONLY 1 core at 400MHz?!")

The small Arduinos probably do not support your "very large libraries", either.  For example, while the "Arduino Language" is technically C++, support for the C++ STL is not included due to limitations of the small CPUs used and their run-time environment.

32k of program memory (on the popular Uno) is sufficient for "thousands of lines of code", but I'd think robotics would tend to run toward much more than that.  The small amount of RAM available on most of the flash-based microcontrollers also tends to be a serious limitation when you start looking at standard data-intensive algorithms.  32k/2k disappears quite quickly if you start implementing an extensive user interface, networking, or graphics.  I would say that an Uno-class Arduino is suitable for implementing COMPONENTS of robotics systems (motor drivers, sensor management, etc), but probably not a whole robot.

A good example of large robotics-like software that runs on Arduino-class hardware can probably be found in the 3D Printer space.  "Marlin" firmware runs on an Arduino Mega or equivalent (256k/8k/16MHz) (with RAMPS shield), and there are alternative driver packages that run on smaller and larger arduino-like hardware.  Marlin is about 280k lines of code, according to cloc.

Most Arduino hardware does NOT have expandable memory.  The AVR cpus cannot run code except from their internal Flash, and few of the other boards have any sort of memory bus that could be used for expansion.


How to write IF/Else using a threshold range of values

To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.

To test if a value is between two numbers, you could use the && AND operator to see if both conditions are met.  For example:

if (sensor > loLimit && sensor < hiLimit) {
    digitalWrite(2, HIGH);
} else {
    digitalWrite(2, LOW);
}

Here's a shorter way to write that:

digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.

Another approach is to test if abs(sensor-midLimit) < halfGap, where midLimit is (loLimit+hiLimit)/2 and halfGap is (hiLimit-loLimit)/2.  Turn on the light if abs(sensor-midLimit) < halfGap, else turn it off.


Stacking 3 of the same shields on top of each other and instructing them in sync

The shield actually uses SPI.

So you will need to trace the chip select and make sure that each shield uses a different arduino pin.


Do I need Kalman Filter after I read DMP data on MPU6050?

The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.

You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.

If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.


How to connect Android phone to Arduino?

You bet it's possible. I used a pretty cheap bluetooth module that I got from Amazon, and wrote an app using the information on the official Android Developers page to connect to the Arduino. There are many guides online telling you how to hook up a module to the pins of the duino.

You can probably get a cheaper module if you look on eBay and don't care how long it takes to arrive, and I think there's at least one app on the Play store for controlling an Arduino if you can make it work for your purpose.

USB connections are probably possible, though I haven't done any of that.


It seems that the offending line is:

while ( (TIFR0 & TOV0) == 0 )

TOV0 by itself equals 0, so the above loop will never end.

You should use:

 while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.


Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!

The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

  22.5.4   Address Match Unit

  The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address
  Register (TWAR). If the TWI General  Call Recognition Enable (TWGCE)
  bit in  the TWAR is written to one, all  incoming address bits will
  also be compared against the General Call address. Upon  an address
  match, the  Control Unit is informed, allowing correct action to be
  taken. The TWI may or may not acknowledge its address,  depending on
  settings in the TWCR. The Address Match  unit is able to compare
  addresses even when the AVR  MCU is in sleep mode, enabling the MCU to
  wake up if addressed by a Master. Reference, pp. 213

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.

Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note AVR154. The code for this app-note can be found on github. This could be modified to allow multiple slave addresses.

Cheers!


In the bluetooth loop you use:

delay(20000);
while (0);

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).

Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.

I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.

And why there are two }} at the end?


How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins?

Add this to your code at the beginning of set void setup():

//********** CHANGE PIN FUNCTION  TO GPIO **********
//GPIO 1 (TX) swap the pin to a GPIO.
pinMode(1, FUNCTION_3);
//GPIO 3 (RX) swap the pin to a GPIO.
pinMode(3, FUNCTION_3);
//**************************************************

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.

To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set void setup():

//********** CHANGE PIN FUNCTION  TO TX/RX **********
//GPIO 1 (TX) swap the pin to a TX.
pinMode(1, FUNCTION_0);
//GPIO 3 (RX) swap the pin to a RX.
pinMode(3, FUNCTION_0);
//***************************************************

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.


That should be possible. Your best option is SDR (Software Defined Radio). It uses a standard PC or even a Raspberry Pi in combination with a DVB-T tv receiver as the radio.

A great starting point would be GNU Radio and its hardware section


What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:

1) study your code to understand how it debounces one input;

2) isolate those parameters / variables used to debounce that specific input;

3) group those parameters / variables into a struct and pass a pointer to that struct to your code;

4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;

5) use that code on as many inputs as you wish.

that's the general approach you take to coding any task.

hope it helps.


Accessing digital pins from the Atmega 16u2 on the Uno

No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.


The writeTo functions

The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.

Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.

The Bitwise ops

These don't set the number of bits we are reading per se, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.

(((int)buffer[0]) << 8 ) | buffer[1];

Whats happening here is that buffer[0] is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original buffer[0] are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator |, which will turn on any bits that were set in buffer[1] in the result. Since the bottom 8-bits were 0's from the shift, this just copies buffer[1] in exactly.

The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.


Does Arduino Uno R3 require cooling in a closure?

The only times I had an AVR run hot was when I applied reverse power to it. You'll be fine without a fan for the Arduino board itself, as long as you don't run power hungry peripherals from it.

Probably the only thing you really need to check (apart from absolute maximum ratings: 40mA max per IO pin and 200mA max for the whole microcontroller) is the on board voltage regulator (usually three pin device with a heat sink soldered down to the PCB) if you power it from a voltage > 7V or so.


You have to call timer.run() inside loop function.

The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.


ESP8266 Wifi.setOutputPower - original/default value?

I was looking for the same answer. I found this link: https://gitlab.com/painlessMesh/painlessMesh/issues/51

Someone dug deeper into the code and found it's set to the max value on init


Remote temperature and humidity sensor with long battery life

I made a Temperature and humidity sensor - battery powered in 2013. It is powered from 3 x AA batteries, and lasted, as I recall, until a couple of months ago before I changed the batteries. That is, almost two years.

It logs to an SD card every 15 minutes. You could change that interval of course, it would probably not last as long logging every minute.

I certainly wouldn't attempt it with a pre-made board, because of the drain by the power LEDs, the USB chip, the voltage regulator, etc.

I measured 6 µA consumption when asleep.

Schematic

(RH-click and "View Image" to see a larger version)

The schematic is deliberately presented as "blocks" of parts of the circuit. To understand it from scratch, make up individual parts, test them and get the code working to your satisfaction. For example, the clock or the temperature sensor.

Some of the parts (like the clock) are already available as pre-assembled boards, if you prefer to reduce soldering.

You could manage without the 7-segment LED readout, however I found it useful for confirming it is working "in the field". The readout LEDs can be purchased cheaply from eBay for around $US 3. Search for MAX7219 8-Digit LED Display Module 7-Segment or similar.

Example output

Example of measuring temperature and humidity every minute:

You can see from the graph that I left the room at 9:30 pm, and the temperature slowly dropped until 6:30 am the next morning. The zig-zag effect is the central heating turning on and off.

Construction details

See the linked page for construction notes, schematic, and code.

Power saving details at Power saving techniques for microprocessors.

Estimated life at logging once a minute

If my calculations are correct, logging every minute might reduce battery life to 7 months (these things are best tested of course), but that is because the consumption is much higher when you power up the SD card. It would probably be best to take 15 readings, and then write to the card every 15 minutes. The extra time writing would be minimal, and that would keep the need to power up the card low.

The 7-segment LEDs

To clarify, those 8 LEDs are not normally on. The battery wouldn't last long if they were! If you press the switch it gives an immediate reading through the LEDs, and also tells you how many writes to disk it has done, and how many write errors it has had. This confirms all is operating properly.

The "busy" LED is there to warn you to not remove the SD card while it is writing to it.

Radio communication

To transmit information you could use a NRF24L01 transceiver module. You get those for a couple of dollars on eBay. Example:

Underneath:

You would need another one at the other end to receive (you would need two of whatever radio you chose).

I did a solar powered project using a couple of those. The NRF24L01 uses about 0.9 µA in power-down mode, so that is pretty minimal.

It also uses SPI, so the connections would be very similar to the SD card connector.

I suggest if you are going to attempt this to first get confident with a normal Uno, get the code tested, make sure you have the sleeping/waking going OK, then move it to a low-power board. There are places like Evil Mad Scientist that make "bare" boards, with a prototyping area, which you can use to put things like your temperature sensor on.


Send packet of multiple sensors data to Bluetooth module

There are many ways to transmit binary data over a byte-stream based interface like Serial (which is used by common bluetooth modules like the HC-05/HC-06). I will only describe one here.
First we need to define a start byte, which marks the start of a new packet. That can be any arbitrary value, for example 0xFF. It is also possible to use a specific byte sequence as start marker. This start byte/sequence is what we send first when transmitting a packet.
Then we want to transmit the size of the following data. With small to normal packet sizes a single byte is enough here (giving room for up to 255 bytes).
Sometimes you might want to compute a CRC hash value to check for data corruption. That could also be send here. But unless you have a system, which really is loosing/corrupting data, you don't need it. I suggest you first try it without and check, if corrupted data is really a thing for your setup.
And then we are sending the actual data. How exactly you are doing this depends on how the data is stored in your code. Though you will use Serial.write() in some way. If you want a more specific answer in this regard, you need to include your code, so that we can see how you are storing your sensor data.
On the receiving side you would then wait for the start marker, read the size byte and then read bytes until you have received as many, as the size byte said. As you have multiple sensors, you could send the sensor data of each sensor in it's own packet. The data could then be formatted like: 1 byte sensor ID, X byte sensor data.


I THINK the problem might be the client.println() statement.  I believe REST messages should be terminated with a \r\n and I think println just does \n.  So if you change it to client.println("\r") it should start working on every message.

Also you might want to consider moving creating the message into a function to reduce the amount of code you have.


avrdude: stk500_getsync(): not in sync: resp=0x00

It's hard to tell from your pictures, but are all the header pins soldered to the boards? If not, they need to be: there's no chance that the proper electrical connections will be made reliably if they're just inserted loosely into the holes.


For the 74HC595 in combination with the Arduino, the best way to check is to use the default example by Arduino:

ShiftOut

With the ShiftOut you can shift the bits into the IC which will make the correct LEDs light up (or not).

Probably you can lit up a LED when passing a HIGH, but you will know very easily by trying the example and check some values/for loops to make them dynamically lighting.

Probably after playing with the example, it will give you much more insight than describing the details here.

Update:

Try first with 00000000 and 11111111 and 8 leds, so you know if 0 will be OFF and 1 will be ON.
Than try with eg 10101010 and 8 leds ... than you know if the first or the last will be on or off.
pulseIn is unrelated
The operators >> and << are so called bit shift operators. Like 1 << 3 gives 8, the binary value 0000001 is shifted 3 bits left resulting in 00001000 which has value 8.
~ is the not operator -> which reverses bits.
The shiftOut function can be used to send data to the 74HC595N.
And to be honest, how does it work ... does it really matter for now? First see what the result is, how to use it. Later you can get into details. Start simple first.