Take a look at this example.

#include <Wire.h>

const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;

void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);

}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)

  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/


Upload sketch via Bluetooth using HC-06 module

Use a BJT/FET.

For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.

Just bring the digital pin HIGH to reset your arduino.


HC-05 Bluetooth Module - INQ-Command doesn't work

I did a factory reset of the device. That resolved the issue

AT+ORGL
AT+RESET

Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.

If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN must remain high.


I don't know the user's function parameters,

A common way for dealing with this issue is to pass a generic pointer to
arbitrary data. See below.

  return type

It makes little sense to allow for arbitrary return types, as your
library would have no way of knowing what to do with the returned value.

  and number of functions that will be added.

Either you allocate the callback array statically with a fixed size, or
you use dynamic allocation. In the first case, the array size could be
decided by the user if it is a template parameter. In the second case,
you risk memory fragmentation unless all the callbacks are registered
once and for all at program startup, which is a common scenario anyway.

About the generic pointer technique

This is a very common way of defining callbacks in C: a callback
contains both a function and a void * pointer to arbitrary data, which
will be given as a parameter to the function. It is up to the user to
decide if and how he will use this pointer: he could completely ignore
it, like he could make it point to the root of a complex data tree.

Here is a simple example:

// A callback contains both a function and a pointer to arbitrary data
// that will be passed as argument to the function.
struct Callback {
    Callback(void (*f)(void *) = 0, void *d = 0)
        : function(f), data(d) {}
    void (*function)(void *);
    void *data;
};

Callback callbacks[3];

// This callback expects an int.
void print_int(void *data)
{
    int parameter = * (int *) data;
    Serial.println(parameter);
}

// This one expects a C string.
void print_string(void *data)
{
    char * parameter = (char *) data;
    Serial.println(parameter);
}

void setup()
{
    Serial.begin(9600);

    // Register callbacks.
    static int seventeen = 17;
    static int forty_two = 42;
    static char hello[] = "Hello, World!";
    callbacks[0] = Callback(print_int, &seventeen);
    callbacks[1] = Callback(print_int, &forty_two);
    callbacks[2] = Callback(print_string, hello);
}

void loop()
{
    // Test all the callbacks.
    for (size_t i = 0; i < 3; i++)
        callbacks[i].function(callbacks[i].data);
    delay(500);
}

Notice that the two callback functions take different types of
parameters, only disguised into the same generic pointer. Notice also
that print_int is used in two different callbacks with different data.
In this example, the data does not change, but this need not be the
case: both the callbacks and the rest of the user code could change the
data pointed to by the generic pointers. Again, it is up to the user to
decide how he will use this facility to communicate between his
callbacks and the rest of his code.


IR Remote code not activating ON/OFF states

Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.

#include <IRremote.h>

int RECV_PIN = 3;
int green = 11;
int blue = 12;
int red = 13;

#define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
#define code2  16615543
#define code3  16599223

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    Serial.println(results.value, HEX);
    unsigned int getting = results.value;
    Serial.println(getting);
    switch (getting) {
      case code1:
        digitalWrite(red, HIGH);
        digitalWrite(blue, LOW);
        digitalWrite(green, LOW);
        break;
      case code2:
        digitalWrite(red, LOW);
        digitalWrite(blue, HIGH);
        digitalWrite(green, LOW);
        break;
      case code3:
        digitalWrite(red, LOW);
        digitalWrite(blue, LOW);
        digitalWrite(green, HIGH);
        break;
      default:
        Serial.println("Enter ;");
    }
    irrecv.resume(); //receive the next value
  }
  delay(100);
}


Programing other Atmel ARM chips using Arduino

Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.

It is fairly involved setup. In short; within each platform there are the following files:

boards.txt, defines the individual boards using the similar processor.
platform.txt, defines the compiler arguments
programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder.
I have not found an complete tutorial on the matter. However, their

Arduino IDE 1.5 3rd party Hardware specification

An overview of the platform architecture proposed for Arduino 1.5

are a great place to start.

I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.


The lifespan of the LCD and the electronics is just like any electronics part. When it is bad quality it will last a few years, when it is good quality it is more than 10 years.

A LCD watch from the 1970s might still work today. That is a few decades.

The backlight might get dim. That depends on the quality of the led and how bright it is set. The cheapest leds have only 50% brightness left after a few months. I suppose they didn't put the cheapest led in that display. I expect it to be okay for many years. Don't set it to the highest brightness. A resistor for the backlight of 220 Ω is common, you could start with 470 Ω and see if that is bright enough.

I see sometimes that the backlight display is directly connected to 5V, without resistor. If you have done that, then you have reduced its lifespan.

There are a few weak parts: The potentiometer for the contrast, the large capacitors on the Arduino board (if there are any), and the power supply.

If the display is more or less at the same room temperature, you could replace the potentiometer with a single resistor of 100Ω to 10kΩ from the LCD contrast pin to GND.


Relay + Arduino uses too much power for battery to handle. Which solution is best?

The TP4056 is a battery charger, not a voltage regulator. It cannot be used to supply power to a device like an Arduino. It is designed for charging the Lithium Ion battery from a 5V (e.g., USB) source.
By trying to use it as a power supply you're asking for trouble. It thinks it's trying to charge a battery (from a 3.7V nominal source) and will be doing things like:

Running constant current making the voltage fluctuate wildly as current demands change
Running constant voltage with limited current causing starving of power
Shutting off when it thinks it sees the non-existent battery being fully charged.

The TP4056 should be connected to a 5V USB power source and to the battery for charging it. The battery should be then through a (very) low-dropout regulator (ideally a switching regulator with zero dropout bypass ability) to power the Arduino at 3.3V.
Alternatively, if you don't need a (reasonably) precise 3.3V then you can power the Arduino directly from the battery.


How to insert into table in database after every 5 minutes using Real time clock module

int mint = util::getMinute();

if (util::getMinute() - mint >= 5)

{

Well, if mint is util::getMinute() then surely util::getMinute() - mint will always be 0.

I think you meant mint to be static, or a variable in the global scope.


Simultaneous input output in arduino mega

No, it is not. The ADC in the MCU is only capable of sampling a single analog channel at a time.

If you require sampling more than one channel at a time then you will need to use one or more external ADCs that are capable of sampling multiple channels, or multiple ADCs each dedicated to a single channel.


How do I use an ATMega 328 (not P) chip with an Arduino board?

So I found the solution:

Here is the link to the method that worked for me. I think the reason my previous method didn't work was because of fuses for the clock as mentioned by Majenko in the comments.


Sending textual and nontextual data simultaneously across a serial port

The idea that sundry terminal programs can cleanly deal with binary data intended for your LCD simulator doesn't seem realistic.  Instead, look for a method to suppress the binary data when the Arduino isn't talking to an LCD simulator.

For example, during startup the Arduino could send some fixed text and a number to the host, and if the simulator is running, it would reply to the Arduino with some other fixed text and the 9's complement of the number.  If the Arduino doesn't get such a reply within a couple of seconds, it turns off LCD-simulation data transmission.


I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

yes, unless your code writes to the registers involved.


RF24 communication between Leonardo and Micro not responding

Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF


You can use a single resistor on the common pin if you want. The problem is that lighting up multiple segments at the same time will substantially reduce the brightness of each one. You could work around that by lighting each segment one at a time in very quick succession though.

It should be possible to control the display directly from the IO pins by setting them LOW. In this configuration, they will be sinking current (rather than sourcing it). It depends on the specification of the display and on what resistor you use though.

Basically, try to keep the current below 20mA and it should be OK (assuming you're using a standard 5V Arduino). For example, if each segment has a forward voltage drop of 2V, you would want to use a resistor of around 180 Ohm.

Controlling the display directly from a shift register is probably not possible, although once again it depends on its specification. Shift registers usually aren't designed to sink enough current so you'll need something like a transistor on each output.


Absolutely. I'll use the Arduino UNO and the ESP8266-01 WiFi module as an example:

The ESP8266 works with 3.3V and not 5V, so you need to connect the 3v3 pin on the Arduino to the VCC and CH_PD pins on the ESP8266.
Connect the GND pin on the Uno to the GND pin on the ESP.
Connect the RESET pin on the Uno to GND. Grounding the RESET pin
effectively causes your Arduino to work as a dumb USB to serial
connector (which is what we want to talk to the ESP8266).
Connect the CH_PD pin on the ESP8266 to the 3.3V line
Connect the RXD pin on the Arduino Uno to the RX pin of the ESP8266.
Connect the TXD pin on your Arduino Uno to the TX pin of the
ESP8266.

Normally, when you want two things to communicate over serial, you'd connect the TX pin of one to the RX of the other (send --> receive). In this case, however, the Arduino isn't talking to the ESP8266; the computer is talking to the ESP8266 via the Arduino.


Interrupt every second on ATTiny84 (and sleep the rest)

Is there any way to wake up after a precise amount of time in the
  POWER_DOWN or STAND_BY modes?

I'm afraid not. You will have to use a timer. Since the ATtiny84 does
not have an asynchronous timer, you will have to keep your timer
clocked. This means the clkIO clock domain has to stay
active. Now, take a look at the table “Active Clock Domains and Wake-up
Sources in Different Sleep Modes”, on page 33 of the ATtiny84
datasheet. It shown that “Idle” is the only sleep mode
that keeps this clock domain active.

  Even with the SLEEP_MODE_IDLE, I could only get the current draw
  down to around (~1.2mA).

There are ways to bring this down. First, there is a collection of
functions named power_*_disable() in the avr-libc. You can use
these to power down every single peripheral except the one timer that
you will be using.

Most importantly, you can save power by reducing the clock speed. Since
these devices have extremely little leakage current, the current draw is
roughly proportional to the clock frequency. You can then achieve huge
power savings by drastically reducing that frequency. Obviously, your
processing power will also suffer, but this may not be an issue for a
simple binary clock.

I think the best option for you is to clock your ATtiny84 off a
32.768 kHz watch crystal. See the section
6.2.4 – Low-Frequency Crystal Oscillator in the datasheet.
These crystals can be very accurate, as they are specifically designed
for time keeping. And the frequency is so low that the current draw from
the MCU will likely be negligible compared to whatever other components
are in your clock.

Edit: answering the question in the comment.

  Wouldn't waking from idle still use the watchdog timer though? Or is
  there a way to wake up based on the 32.768 kHz crystal?

As the watchdog timer is way too inaccurate, it is of no use to you.
Instead, you would use either Timer 0 or Timer 1, and configure it to
deliver an interrupt every 32,768 CPU cycles. This interrupt will
be your 1 Hz wakeup source.

You can do this with either timer, in either CTC or fast PWM mode. You
have to configure the prescaler and the TOP value such that

prescaler_factor × (TOP + 1) = 32,768

Then, enable the relevant interrupt, and define the corresponding ISR
that will advance your clock by one second.


Arduino Due randomly slows down, serial communications stops

The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.

Here is the typical manifestation of heap fragmentation in an Arduino sketch.

Solution:

Remove as many Strings as possible and replace them with char[]
Use a StaticJsonBuffer instead of a DynamicJsonBuffer

If you remove all the Strings and use a StaticJsonBuffer, your program will run without any heap. No heap, no fragmentation! Not only it will be more reliable, it will also be smaller and faster.

If you must use String, then call String::reserve() to make sure the size is the same at each iteration. Indeed, repeated allocation of the same size doesn't increase fragmentation.


Connecting two analog multiplexers (CD4051b)

Each CD4052B multiplexes 8 input to one output, and you need three digial pins to control it.  You have the six analogue input pins available and those pins can also serve as digital outputs, so you should be able to use  them to do what you need.

I would do as follows:

Assign three of your spare pins to be digital outputs.  Use these three to address both CD4052Bs together -- so both devices will receive the same addressing.

Connect the output of one CD4052B to the fourth analogue pin, and the output of the second CD4052B to the fifth analogue pin.  These will be your inputs.

On both CD4052Bs, tie the INHIBIT pin low, so they are permanently on.  (If you want to be able to switch them off, for some reason, you an use your sixth pin to control the INHIBIT line on both devices.)

Now when you want to read from sensor 1, you set 000 on the address lines (A, B and C) and read from the first input.  At the same time you'll have sensor 9 on the second input.

It would be well worth reading the data sheet


Why are commands executing on their own?

Trying to write a proper answer...

According to your description, it looks like you are victim of inductive
noise pickup. The circuit [MCU → Arduino ground pin → foot pedal →
Arduino digital input pin → MCU] is a loop that can pick up magnetic
flux. If this flux varies, either because the magnetic field varies
(ambient electromagnetic noise) or because the geometry of the circuit
changes (you move the wires), this will induce an electromagnetic force
that can make your Arduino read LOW even when the button is not
pressed.

There are two things you can try to overcome this effect:

Replace the weak internal pullup of the Arduino by a much stronger
external pullup. Something around 1 kΩ should make it quite hard for
the noise to pull the signal low.
Connect the pedal to the Arduino board using a twisted pair of wires,
like the ones found in telephone or network cables. This kind of
cable does a good job at minimizing inductive pickup.


The answer was simply that 6-pin are not designed for uploading sketches. Instead use the micro-USB port to upload sketches.


Understanding datasheet of a HCHO gas sensor

First, you need to be communicating by UART, not I2C.  That means using Serial or some similar object (On ESP32 you can define your own on whatever pins you want).  However, the datasheet omits one vital piece of information: the baud rate it communicates at - so you will have to guess that and try various different standard baud rates until you find the one that works.

Then you have to send the "Give me the data" instruction.  The module then responds with the data.

For example (untested):

HardwareSerial mySerial(1);

#define PIN_RX 21
#define PIN_TX 22

void setup() {
    Serial.begin(115200);
    mySerial.begin(9600, SERIAL_8N1, PIN_RX, PIN_TX); // This is the one you need to guess since the DS omits it...
}

void setup() {

    // Once a second send the request to get the data

    static uint32_t ts = millis();
    if (millis() - ts > 1000) { // Once a second
        ts = millis();
        // "Give me the data"
        mySerial.print("\x42\x4d\x01\x00\x00\x00\x90");
    }

    // When 10 or more bytes have arrived then assume that they are correctly
    // framed and print them.  Really it should read one byte at a time and
    // look for the correct start sequence of 0x42 0x4d 0x08 and read only
    // from there, but this will server for demonstration purposes.

    if (mySerial.available() >= 10) { // We expect 10 bytes returned
        uint8_t packet[10];
        mySerial.readBytes(packet, 10);
        Serial.print("ID:   ");
        Serial.println(packet[3]);
        Serial.print("UNIT: ");
        Serial.println(packet[4]);
        Serial.print("VH:   ");
        Serial.println(packet[5]);
        Serial.print("DHH:  ");
        Serial.println(packet[6]);
        Serial.print("DLL:  ");
        Serial.println(packet[7]);
        Serial.print("LRCH: ");
        Serial.println(packet[8]);
        Serial.print("LRCL:   ");
        Serial.println(packet[9]);
    }
}


Download Device Class Definition for Human Interface Devices (HID)

https://www.usb.org/sites/default/files/documents/hid1_11.pdf

See section 6.2.1 HID Descriptor

bCountryCode 0x09 German

also see section E.4 (page 67)

E.4 HID Descriptor (Keyboard)
Part            Offset/Size  Description                                         Sample
                (Bytes)                                                          Value
----------------------------------------------------------------------------------------
bLength           0/1        Size of this descriptor in bytes.                    0x09
bDescriptorType   1/1        HID descriptor type (assigned by USB).               0x21
bcdHID            2/2        HID Class Specification release number
                             in binarycoded decimal—for example, 2.10 is 0x210).  0x101
bCountryCode      4/1        Hardware target country.                             0x00
bNumDescriptors   5/1        Number of HID class descriptors to follow.           0x01
bDescriptorType   6/1        Report descriptor type.                              0x22
wDescriptorLength 7/2        Total length of Report descriptor.                   0x3F


How do I use interrupt service routines inside libraries and classes?

Nick Gammon's answer is good for one Timer - but now you want two!

OK, then you can take advantage of the Timer Library's context parameter. What's that? If you take a look at the header for every(), you'll see as well as passing in the function to call, you can also pass in another value (called context) to pass back to that function when it fires*. So instead of you remembering just one copy of instance, get each Timer to remember it for you.

  *If you can't see the context parameter in Timer.h, then make sure you're using the v2.1 branch, not master.

So:

Get rid of _instance everywhere.
Change:
static void _callbackGlue();
to
static void _callbackGlue(void *context);
Change:
void Blink::_callbackGlue()
{
_instance->_callback();
}
to
void Blink::_callbackGlue(void *context)
{
((Blink *)context)->_callback();
}
Change:
_blink_event = _blink_timer->every(_duration, _callbackGlue);
to
_blink_event = _blink_timer->every(_duration, _callbackGlue, this);

Note that I've submitted these changes as a Pull Request on your GitHub repo.

Incidentally:

You don't need _blink_timer to be a pointer. Get rid of the *, get rid of the line with new Timer() in it, and replace all your _blink_timer-> with _blink_timer.


not able to figure out what is wrong with my nodemcu code

Your echoPin Is defined as 3. GPIO3 of the NodeMCU is also the “RX” pin needed for serial communication to the host. This might explain why you don’t see any output. You should change it to a different pin (for example pin 5 / D1 is a safe choice).

Each pin on the NodeMCU has a “GPIO” number (which is just the pin number as defined by the ESP8266 architecture) and a corresponding “Dx” designation (which is usually marked on the NodeMCU board).

Which GPIO pin corresponds to which which “D” pin is shown in pinout diagrams, like the one here. Scroll to the NodeMCU 12-E pinout.

Some of the safest pins to use are:

Pin 5 (D1)
Pin 4 (D2)
Pin 12 (D6)
Pin 13 (D7)
Pin 14 (D5)

Some of the other pins could also be used, but have some restrictions, as you can see on the page I linked to.

Note that pins 12-14 are used for SPI and pins 4 and 5 are (normally) used for (software) I2C. If you want to control hardware that uses these protocols, these are the default pins it uses.


Moving a character around an LCD screen - is there a better way?

You could encapsulate the logic of detecting a button release into its
own function:

// Return the button that was just released, or btnNONE.
int releasedButton()
{
    static int last_button = btnNONE;
    int previous_button = last_button;
    last_button = read_LCD_buttons();
    if (last_button == btnNONE)
        return previous_button;
    else
        return btnNONE;
}

Then the logic in the loo gets simplified:

void loop()
{
    switch (releasedButton()) {
        ...
    }
}


You can add source code to the sketch in the Arduino IDE. When adding a new source code file make sure the extension is uppercase .S

Files with .S extension will be compiled as Assembly.

There is an Arduino IDE for the mac but if you want to use an external editor you have many options.

The simplest is to switch on File>Preferences>External Editor in the Arduino IDE. This makes the IDE work in "read-only/auto-reload" mode allowing edit in a different code editor but compile and upload (without reopening the code) in the Arduino IDE.

There are also the File>Preferences Verbose Compile and Verbose Upload options in the Arduino IDE. These options will show you the commands used to compile, link and upload. You will see that the IDE runs other programs, outside of the IDE, such as avrdude and g++. Therefore a small script file can be created to call the same commands from a different IDE if the external editor doesn't have a facility to run external commands.

The verbose output will show where the tools and sources for build and upload are located. Normally for Uno (avr) they are below [IDE Folder]\hardware\arduino.


What would be the Western / American equivalent of the Troyka Shield and modules?

This probably has no complete, general solution.

The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables.  Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.

There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer.  Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.

The modules are going to be the most problematic part.  They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits.  So for most of these, you'll probably have no problem finding a substitute, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.

You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.

Do beware however, that there are some really bad tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.


Correct way of having loop end when required?

As pointed out by Ignacio Vazquez-Abrams and jsotola, you need to use a
state machine, like the one from the Blink Without Delay
Arduino tutorial. Yours would be slightly more complicated because you
need a way to turn it on and off, and because you use different on and
off periods. Here is an example code that abstract the blinking logic
into three functions:

update_led() takes care of the blinking, and it has to be called
quite often in order to achieve a smooth blinking
start_blinking() and stop_blinking(), as their names suggest, are
used to turn the blinking state machine on and off.

const uint32_t ON_TIME  = 3000;
const uint32_t OFF_TIME = 5000;

bool led_blinking;     // are we blinking the LED?
bool led_on;           // is the LED currently on?
uint32_t last_toggle;  // last time it toggled while blinking

void update_led() {
    if (!led_blinking) return;
    uint32_t now = millis();
    if (led_on && now - last_toggle >= ON_TIME) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now;
    }
    if (!led_on && now - last_toggle >= OFF_TIME) {
        digitalWrite(ledPin, HIGH);
        led_on = true;
        last_toggle = now;
    }
}

void start_blinking() {
    digitalWrite(ledPin, HIGH);
    led_blinking = true;
    led_on = true;
    last_toggle = millis();
}

void stop_blinking() {
    digitalWrite(ledPin, LOW);
    led_blinking = false;
    led_on = false;
}

You then have to call these functions from loop() as follows:

void loop() {
    // Keep the LED blinking if necessary.
    update_led();
    ...
    if (request.indexOf("/LED=ON") != -1)  {
        start_blinking();
    }
    if (request.indexOf("/LED=OFF") != -1)  {
        stop_blinking();
    }
    ...
}

Edit, in response to jsotola’s comments:

When answering the question, I was initially tempted to make a
BlinkingLed class, with the functions as its public interface and the
variables private. I resisted the temptation on the grounds that, given
the apparent OP’s level of C++ knowledge, that could end up being well
over his head. Instead, I used documentation as an informal way of
separating the public from the private: you are only supposed to use
what is documented, i.e. the functions. You don't “take a shortcut in
your program and clear led_blinking directly”.

You could, of course, make the led_blinking variable part of the
public interface. That could even be a nice simplification, as you don't
need the start/stop function anymore. But then you loose control over
the initial phase of the blinking pattern. That may not be an issue, but
if you want the LED to turn on as soon as you set led_blinking to
true, then you have to do something like

void update_led() {
    uint32_t now = millis();
    if (!led_blinking) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now - OFF_TIME;  // fix initial phase
        return;
    }
    ...
}

Note that the subtraction can overflow, but that's not as issue because
it follows the rules of modular arithmetics.

I actually kind of like this option, with all the logic in a single
function. This way the variables led_on and last_toggle can be made
static local to the function, which provides true encapsulation without
a class. However, from a pedagogic point of view, I think my initial
proposal is easier to understand.


Why is this IIR Filter unstable on the Arduino Due?

The precision of a float is about 7 significant digits. The
constant term of B in your transfer function (0.00000376) has only 3
significant digits.
Your transfer function has a pole at z = 1. It is thus not really
stable, but only marginally stable. Any parasite DC component in
the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of
the filter on the Arduino, but rather to the filter design. Where did
you get that transfer function from?

Edit: I looked at the filter you are trying to make. It turns out it
is very sensitive to the precision of the coefficients of A(z). If you
try to add these coefficients, they almost cancel out: their sum is
about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer
function, which is their ratio, is 1. By rounding the coefficients to
four decimal places, you made the cancellation exact, and the transfer
function infinite.

Just write the transfer function with more decimal places in the
coefficients and it should work:

H(z) = 3.75592×10−6 (1 + 3 z−1 + 3 z−2 + z−3)
         ÷ (1 − 2.9371759 z−1 + 2.8763097 z−2 − 0.9391038 z−3)


How to connect more than 10 sensors to Arduino uno r3

You can easily increase number of I/O pins using an expander, e.g. PCF8574.
The expander can be connect using your SCL/SDA pins located next to GND/AREF pins. (Here you can find detailed photo: http://forum.arduino.cc/index.php?topic=84190.0) You can connect up to 8 such expanders to extend the number of your digital pins to 64. Once you connect it, here is a code snippet of how to use it:

#include <PCF8574.h> //library available at: https://github.com/skywodd/pcf8574_arduino_library

void setup() {
  PCF8574 sensors;
  sensors.begin(0x20); //0x20 means that you connected A0, A1, A2 pins of PCF8574 to the ground
  sensors.pinMode(0, INPUT_PULLUP);
  sensors.pinMode(1, INPUT_PULLUP);
/*...*/
}
void loop() {

  byte sensorValue = sensors.digitalRead(0); //reads digital value of 1st sensor connected to pin 0 of PCF8574 expander
  /*...*/
}

You can read more with this tutorial (note: they are using wire interface, so the code will differ. Choose the one you prefer).


A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.


Cant find Sdl and Sca pins in lcd display

You will need an I2C adapter board like this to interface your LCD 1602 via I2C.


You need to "split" your library.

Placing full functions inside a header file (.h) is bad form and causes the exact problem you are seeing. Every time you include the header file you create an entirely new copy of the function. This can only work if the functions are static, which means that they exist, and are contained entirely within, the function in which the header is included in. All outside access to them is completely cut off and they become "local" to the file. That means you can have multiple copies of them in one program. However that is wasteful of space since you are duplicating your code.

Instead you need to have the code itself in a .cpp file, which gets compiled separately and then linked with your sketch at the end of compilation, and just pointers to the functions you have written in your .h file.

Utilities.h:

extern void myFunction();

Utilities.cpp:

void myFunction() {
    blah blah
}

The .h file just contains a prototype for the functions which tells the compiler that "This function is defined elsewhere. Find it later on when you link."

It's only the .h file that is included in libraries and sketches, etc, so only the prototype that is duplicated between files. The .cpp is compiled separately and thus only compiled the once, so you don't get the code duplicated.

One caveat with this is that your sketch must include the library you have written so that the IDE knows to look for .cpp files within it to compile. And you must use #include <Utilities.h> for it to be able to work that out. Using a full path rather than just <Utilities.h> means that you break all portability and the IDE may not know to look for .cpp files in there, or even where to actually find it when compiling.  Note as well that the IDE needs to be restarted after creating a new library, which is why it may not be able to find it in your experiments.


And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.

nothing magic about going in "pure c".


Problem reading an EEPROM chip using the I2C protocol

You need to pass the address as two bytes, one by one.

Do not do:

Wire.write(address);

Rather, do:

Wire.write((uint8_t)(address >> 8)); // MSB
Wire.write((uint8_t)(address & 0xFF)); // LSB


Cannot read from 2 I2C slaves consecutively

I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.

And don't forget the "volatile" keyword for your semaphore.


Difference between Arduino.cc and Arduino.org

The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.

Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.

Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.


Arduino loading variables from an SD card

Yes, it is possible, but is it practical?

There's basically two ways of doing it:

Load the entire bitmap into RAM for displaying multiple times
Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.

So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash.  That means that your screen updates could be really slow, which would seriously impact the playability of your game.

All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen.  Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way.  If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.

A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.


Response from ESP8266 is returning unknown characters

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
...
esp8266.println(command);

I suspect this is just a typo because it shouldn't compile.  But you are adding all the HTTP headers to commando not command.

Usually the ? means that the character is unprintable.  So to help diagnose the issue display the integer value for each character that is returned.  Something LIKE this (I've never used a String before so length() might not be right)

Serial.print("Request response: ");
Serial.println(response);
for (int index = 0; index < response.length(); ++index)
{
   Serial.print (response[index]);
   Serial.print (" ");
}

If you want to program the ESP directly then have a look at these guides, they should give you the general idea.  Its usually as easy as programming an UNO once you are setup.

http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
https://www.hackster.io/harshmangukiya/how-to-program-esp8266-with-arduino-uno-efb05f


How to call 5 different functions in a loop based on serial input?

This answer isn't going to give you the code to solve your problem, it is just ideas that you can look at and see what suits you best.

You should be able to find an example on how to read from a serial connection, I'm sure there is at least one example in the IDE.

You need to work out how to encode your data, having it in nice human friendly format (like you have above) is great if you are processing it on a PC but on a processor that is slow and have very limited memory using A,B,C... as the function names might be more practical.  It will be smaller to store and quicker to compare.

You want to store the input so it can be read back later.  There are a number of ways you can do this but they all need a non-volatile storage medium.  You could use an SD card, obviously you'd need an SD reader and the type of reader you get will affect the code you need, but these can be problematic.  You can also use EEPROM chips that, you can get little I2C interfaced modules, they have less space than an SD card, but are generally faster (they also have a shorter lifespan, but don't worry I don't you'll ware one out).  You can also use the EEPROM that is in the Arduino itself (I've never done this).

It is best to build you program up in small parts, get the reading from serial working, then calling functions, then saving and loading.  That way you only have to debug a small bunch of issues at once.  If you wanted you could abstract the storage device away from the code by writing a base class that has virtual save and load functions.  You could then inherit from this class for the EEPROM or the SD card and changing wouldn't affect the rest of the code.

Like I said at the start I appreciate this answer hasn't given you a step by step guide on how to solve your problem, but hopefully it has given you a few pointers on what you could do and you can research the options from there.  Remember when you get stuck on one particular aspect just post a minimal example of what you have tried and explain what you expect it to be doing and people will be more than willing to help.


Remote Controlled Self-Balancing Robot - how to mix control input with IMU input?

The PID get's a set point from you. For a standing still robot this a basically an angle of zero in respect to the gravity direction (which variable you use for the PID depends on your actal implementation, but it always be something derived from the angle to gravity direction). For driving forward, the robot must lean forward. So you set the new angle set point to let's say 2 degrees. The PID will try to hold that value by driving forward constantly, with a speed depending on the set angle.

So, via the remote control you simply change the angle setpoint.


I just add an external 9V power supply to my Arduino Mega. The SD device is power by arduino 5V pinout.


using special symbols from the U8glib library

setFont just tell how display the next drawStr (or similar text output function).

To draw an arbitrary UTF8 char, just use

drawUTF8

C++/Arduino Prototype:

u8g2_uint_t U8g2::drawUTF8(u8g2_uint_t x, u8g2_uint_t y, const char *s)

C Prototype:

u8g2_uint_t u8g2_DrawUTF8(u8g2_t *u8g2, u8g2_uint_t x, u8g2_uint_t y, const char *s);

Description:

Draw a string which is encoded as UTF-8. There are two preconditions for the use of this function:

The C/C++/Arduino compiler must support UTF-8 encoding (this is
default for the gnu compiler, which is also used for most Arduino
boards), and
The code editor/IDE must support and store the C/C++/Arduino code as UTF-8 (true for the Arduino IDE).

If these conditions are met, you can use the character with code value greater than 127 directly in the string (of course the character must exist in the font file, see also setFont).

Advantage: No escape codes are required and the source code is more readable. The glyph can be copied and paste into the editor from a "char set" tool.

Disadvantage: The code is less portable and the strlen function will not return the number of visible characters. Use getUTF8Len instead of strlen.

Arguments:
        u8g2: A pointer to the u8g2 structure.
        x, y: Position of the first character on the display.
        s: UTF-8 encoded text.

Returns: Width of the string.

Note 1: This drawing function depends on the current font mode and drawing color.
Note 2: Use the print function to print the value of a numeric variable.

See also: setFont drawStr print

Example:

u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawUTF8(5, 20, "Snowman: ☃");


How to 'label' module using electric techniques

If you are unable / unwilling to change your interface into a purely digital system whereby a small microcontroller in the sensor module interfaces the sensor with a communication bus, the best method is probably to include a small 1-wire EEPROM with each module.

An ideal one would be the DS2431 which provides 1024 bits (128 bytes) of EEPROM storage using just 1 wire to both communicate and provide power.

Programming in a unique identifier for the module would be a simple enough task, and that unique ID can then be used to work out what the module is.

The DS2431 is pretty cheap too, available at prices around  $1.50 and below (much less for bulk and surface mount).

You can also get bigger versions for storing more data should you want to.


Keyboard.h: No such file or directory - Arduino pro micro (leonardo)

The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

Remove the line #include <Keyboard.h> from your sketch.
Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via sudo apt-get install arduino, you end up with the very outdated IDE version you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:

#if ARDUINO > 10605
#include <Keyboard.h>
#endif

Reference: https://github.com/arduino/Arduino/pull/3304


When I turn on the servo it spins on its own before going to the right position and start the sketch

What happens if you have a sketch such as the following? This uses the loop() function of the Arduino sketch to do one movement each time the loop() function is triggered.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;   // variable to store the servo position
int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pos = 0;            // start off with zero degrees.
  direc = 1;          // start off incrementing the angle by 1
}

void loop() {
  if (direc > 0 && pos > degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = degrees_of_motion;
  }
  if (direc < 0 && pos < - degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = - degrees_of_motion;
  }

  myservo.write(pos);    // tell servo to go to position in variable 'pos'
  pos += direc;          // increment/decrement the position
  delay(servo_speed);    // waits 15ms for the servo to reach the position
}


It was too damn simple...

I just had to add a line inside the else block in the loop function.

digitalWrite(brake1, LOW);

This was happening because the first time the threshold limit was crossed the brake1 pin was left HIGH and was never set to LOW again, which caused a permanent brake in the motor.

I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.


Uploading Error: no programmer has been specified

This issue occurs when using Arduino IDE 1.6.8 or older with Arduino AVR Boards 1.6.12 or 1.6.14. There are two solutions:

Upgrade your Arduino IDE to 1.6.9 or newer by downloading and
installing the appropriate file from
https://www.arduino.cc/en/Main/Software.
Downgrade your Arduino AVR Boards version to 1.6.11 or older(or 1.6.13) via
Tools > Board > Boards Manager...

I submitted a pull request to fix this backwards compatibility issue and it was merged by the Arduino developers so this issue will no longer occur with Arduino AVR Boards 1.6.15 and up. It explains the cause of the issue:
https://github.com/arduino/Arduino/pull/5427


loading custom code onto SparkFun Blynk Board

That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.

Instead you will have to write a new firmware that contains all the code you need to do the entire job.


Arduino Upgrading from 1.0.6 to 1.6, code doesn't work anymore

You should not have added libraries to the Arduino files in the "C:\Program Files (x86)\Arduino" folder in the first place.
That is only for the Arduino program files and standard libraries that are included with the Arduino IDE.

Could you uninstall the Arduino and serial drivers. Remove also the "C:\Program Files (x86)\Arduino" folder, to be sure that absolutely nothing is left behind, because that will interfere with a new version that will be installed. Remove also the hidden "arduino15" folder(s).
Do you know the location of your sketches, it is in the preferences and is often "Documents\Arduino". Go to that folder and go into the "libraries" folder. Remove unused libraries or libraries that have been included in the Arduino files.
Do you have Java installed ? Some Java versions are not compatible with the Java files of the Arduino. If you don't need Java, then uninstall it.

Install the newest Arduino 1.8.3 from Arduino.cc Software.
Use the Library Manager in the Arduino IDE, and search for modbus. Install the "ModbusMaster by Doc Walker" with the Library Manager. The modbus library that will be installed is this one: Github 4-20mA ModbusMaster.

There has been a few changes, for example with PROGMEM. All PROGMEM data must now be 'const'. You might have to make a few adjustments.


displaying a 3 digit clock time on a 4 digit 7 segment display

I tested your first code line and it outputs a right aligned 136 without colon at my display. (Said I have only a colon at the middle and no decimal points)

The 5 at the fist digit (and also the A at your third code line) must have been set somewhere beforehand. The function does not change the unused digit, so it will stay whatever you set it to beforehand (Even from before the last reset of the Arduino. The display doesn't reset with the Arduino). You can set the segments for that digit to zero (or set all segments to zero, to clear the complete display) before you show the decimal number.

About the colon: Here it is important on which position you start the printing of the number. The colon/decimal point bitmask, that you provide the function with, is seen from the starting position, that you provide. The middle colon of a 4 digit display is wired to the second digit. When providing 1 as the starting position, you start with the second digit. Thus the colon bitmask must set the most significant ("first") bit, to enable the middle colon, since it belongs to the first digit, that is processed by the function. Meaning:

position = 0 and bitmask = 0b10000000 --> colon/decimal point at first digit on
position = 0 and bitmask = 0b01000000 --> colon/decimal point at second digit on
position = 0 and bitmask = 0b00100000 --> colon/decimal point at third digit on
position = 1 and bitmask = 0b10000000 --> colon/decimal point at second digit on
position = 1 and bitmask = 0b01000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b10000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b01000000 --> colon/decimal point at fourth digit on

The 0x80 >> 1 is just a different representation of your binary number. 0x80 is the hexadecimal form of the binary 0b10000000. The >> operator shifts the byte to the right, here by one digit. Thus:

0x80 >> 1 = 0b10000000 >> 1 = 0x40 = 0b01000000

So the code, that you found, enables the colon/decimal point at the second digit.

  tell me an easier way to construct a time

Easier it relative. I used such a display in a project to display a time and used two showNumberDecEx() calls; one for the minutes and one for the seconds:

display.showNumberDecEx(seconds, 0x00, true, 2, 2);
display.showNumberDecEx(minutes, 0x40, true, 2, 0);

Having directly minutes and seconds may make it easier for you. About the no-leading-zeros: Since the library always prints left to right, you need to handle that by yourself. But that is rather easy. One if statement to check, if the minutes are greater than 9 or not. Depending on that you set the position to 0 or 1.

display.showNumberDecEx(seconds, 0x00, true, 2, 2);
if(minutes > 9){
    display.showNumberDecEx(minutes, 0x40, false, 2, 0);
} else {
    display.showNumberDecEx(minutes, 0x80, false, 1, 1);
}

You could put that into a function, so that you don't have to write this code multiple times.

Note: For my last code snippet to work, you should first clear the display (or optionally only the first digit), so that no number from before will be displayed there.


radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or
oled.print, But I don't really understand the "sizeof" part, maybe
that is the problem?

Sort of.  There's kind of two interrelated problems.  The major one is that the actual data of a String is not contained with the actual String type itself.  It's allocated on the heap.  What the String class contains is a pointer to it and some numbers for tracking the allocated size and amount used.
So the first problem is you're not reading the memory that actually contains the text inside the string.
sizeof(Show_value) evaluates to the size in bytes of the String class itself, which is the size of a pointer and a couple of integers, about 6 bytes, and not the size of the content of the string.
So you're sending a pointer (a memory address) that the receiver wouldn't know what to do with, and some information about how much was allocated and used and nothing of the String content.
Try:
radio.write(Show_value.c_str(), Show_value.length());

.c_str() gets a pointer to the actual string content itself.  And .length() is the actual size of the used part of the String's allocated area on the heap.
That said, it's better to avoid String where you reasonably can.

Regarding:

Does this also mean I need to replace radio.read(&Show_value, sizeof(Show_value));

It would. Doing that is a bit more complicated since .c_str() yields const char *; String isn't designed to make write-access to its underlying data as easy.
Without hacking your way around String's expectations, that would require using a temporary buffer. Something like:
char buffer[33] = "";  // Note: this will actually fill the entire buffer with '\0', which some find a surprise.
// The idea in the above is to accommodate the maximum RH24L01 packet size 32 bytes plus room for a null terminator.

radio.read(buffer, sizeof buffer - 1);  // We're only making the 32 byte chunk available to the .read() call, and leaving the last byte to it's '\0' value to force null termination in any case.

String s = buffer;

This assuming that you're either filling the packet with bytes, or including the null terminator in the packet, or both.  If you're using a dynamic payload size, rather than initializing the array with = "";, it could be left uninitialized and the received packet size could be used to place the null terminator at the location needed.
You could wrap this in a function if you plan on doing it a lot.  But again, it's probably better if you can just use the array and not work with String.


Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.


Help understanding SoftwareSerial recv() and PCINT

This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

No, in inverse logic (for a UART) the line is held LOW and a rise indicates a start bit. The diagrams you show in your question show that UART communication normally is HIGH with LOW for a start bit.

  It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

The PCINT is only used to identify the falling (or rising in the case of inverse logic) edge of the start bit. From then on it samples at pre-defined periods to read each bit. Accurate timing is needed for that, so assembly code is used to give precise delays (see tunedDelay()). Once the whole 10-bit packet has been received the interrupt handler finishes and control is returned to the main thread again. The PCINT is then free to look for the next start bit.


This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.

Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

Ubuntu Server Setup

avr-gcc: avr-gcc (GCC) 4.9.2
avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

Windows 10 Server Setup

avr-gcc: avr-gcc (GCC) 4.3.3
avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the fork we made to mocoLUFA, it has minor changes, that were very useful to us and our hardware.

Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

What kind of MIDI messages are you trying to send/receive?
Can you share the code you are using?
Are you using Arduino MIDI Library (Last version is v4.3.1)?
If not, are you sure you are using 31.250 bps as baud rate?
Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!


same code snippet without using pin

char equalText[80];

if (equalState){
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
}
else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = server.arg("equal").toInt();

but it does not make much sense to set the value if you already switched the state based on it's previous value


Do I need a resistor to control a servo with a PWM signal?

No, you don't.
Resistors are used to limit and control current (amongst other things) and you don't need to do that when sending a signal from one digital device to another.


What is the purpose of the I/O pin capacitor on the AVR microcontroller?

To make explicit the implicit parasitic capacitance on the pin.


How to receive data via Bluetooth on an Arduino 101?

According to the Arduino Callback LED tutorial, you can use the dedicated library to access the BLE features of the board. All the Curie Libraries are covering the new Arduino/Genuino 101 embedded characteristics .
In your case you must incluse the CurieBLE.h and configure the bluetooth service with Read/Write access.

Have a look to this page for a complete sample.


How can I PWM 4 LEDs from 0 to full brightness using a two axiz resistive joystick?

There's a number of steps you need to go through:

Read the ADC to get the joystick position
Subtract 50% of the full range (512) to get a ±512 value
Note the sign to get the direction
Take the absolute value to get the distance
Subtract a small amount to create a "dead zone" in the centre of the joystick
Map the result to 0-255 for the PWM.

The code might look like (note: untested):
int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead
}

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.

And do the exact same thing for X with different pins.


Reducing the power requirement, compared to an R-Pi, should be straightforward, achieving 29.7106Hz is doable, reducing the size is harder (an R-Pi is quite compact).

Some of the available options depend on your electronics skills, and budget.

I'll assume you want to use off-the-shelf hardware as much as practical, but are okay to wire 'modules' together (size could be a bit smaller than an R-Pi using off-the-shelf parts, but could be significantly reduced by a custom made part).

I'll also assume you want to keep costs under $100. (I apologise if I am wrong, but this seems like a level that many of this community might find interesting :-)

Preamble:

Even at 16MHz, 29.7106Hz represents a count of approximately 538,528, which requires 19 bits. So I would not use a chip with 8 or 16 bit timers. I would make my life easier by using a chip with 32 bit timers.

Further, the code will be manipulating quantities with at-least 19 bits, so I would not use an 8 or 16bit CPU. I would make my life easier by using a 32bit CPU that operates on 32bit quantities in a single operation. This may become very important if you opt for a software-heavy approach.

Initial Approach:

Lets assume our 32 bit processor has a clock of 64MHz.
To generate a clock frequency close to 29.710617284Hz (as good as my calculator will do), load a timer with 2,154,112 (maybe 2,154,111, depending on how the counter triggers).

The more accurate divisor is 2,154,112.094.

That count is within 0.05ppm (parts/million) of 29.710617284Hz at a 64MHz clock.
Also, a count of +/- 1 is a change of less than 0.5ppm. That is about 30x better than the more relaxed requirement, '29.7106', mentioned in your comments.

Using 64MHz to drive the count will enable 4x better accuracy, 0.5ppm, than using a 16MHz clock, 2ppm, when we examine ways to implement this in the 'Options' section below.

Summary so far: if the microcontroller had a very accurate clock (much better than 0.5ppm error), then the problem is solved.

However, the crystals used to drive the microcontroller typically have a frequency stability of 30-50ppm, and may be even worse.

Options to reach 0.5ppm:

1. Replace the MCUs crystal with a much better part.
This will typically require some soldering skill, and the parts I've seen (which are likely to replace the existing crystal) are stable at about 10ppm. That might be a factor of 3-5 better than the factory fitted crystal, so may be worth the effort, however there are better options.

2. Feed the MCU with a higher-stability clock source than a crystal.
Most MCU's can accept an external clock source in place of the crystal. Temperature Compensated Crystal Oscillators (TCXO) cost about $5, and can achieve 0.5ppm (0 to 40C, 2ppm -30C to +85C). So an improvement over an 'ordinary' crystal of 30-100x.

If this is appealing, I'd actually recommend looking at ST Micro's Nucleo boards. They are low-cost (under $12), so not much wasted if it doesn't work, and many of the boards already take an external oscillator, so may be easier to change. (They are 32bit CPU's with 32bit timers, and can run at 64MHz,) I imagine folks can recommend other boards.

3. 'Discipline' the square-wave counter with an external high-quality clock
The idea is to use a very accurate external clock, and adjust the square-wave count to get high-accuracy than the existing MCU crystal. While counting the MCU clock for the square wave, use a second counter to count the number of MCU clock cycles a known, high-quality, external timing source event takes. The external clock source could be a TCXO, an Oven Controlled Oscillator (OCXO), which can achieve 0.001ppm) or GPS.

Program code could estimate the error of the MCU clock vs higher-quality clock, and adjust the square-wave count within each square-wave cycle. This may keep the square-wave within 0.5ppm using one or more +1 or -1 adjustment of the counter. This approach has the advantage that the only electronics is connecting the high-quality timing source to a pin on the microcontroller. The rest is (carefully written) software.

Edit:
To be clear, this option 3 can use an unmodified, off-the-shelf, MCU development board. The original crystal is unchanged; there is no need to modify it to replace its crystal.

So it could use a small, e.g. Arduino-Nano size, microcontroller running at a reasonable rate (e.g. 64MHz) connected to a TCXO (or even OCXO), and get close to 0.5ppm error.


ESP32 not seen by a network analyzer application in server mode

In Client mode the ESP is using the WIFI capability. But why it can
  not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

  why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.


Can Bus to receive and transmit on the same mcu

Yes, it is possible.

  CAN is a multi-master serial bus standard for connecting Electronic Control Units [ECUs] also known as nodes. Two or more nodes are required on the CAN network to communicate. The complexity of the node can range from a simple I/O device up to an embedded computer with a CAN interface and sophisticated software.

  -- Wikipedia

You should understand how collision detection works in a multi-master CAN bus and ensure that you implement it (or it is implemented in your chosen CAN library) to allow reliable operation:

  The CAN specifications use the terms "dominant" bits and "recessive" bits where dominant is a logical 0 (actively driven to a voltage by the transmitter) and recessive is a logical 1 (passively returned to a voltage by a resistor). The idle state is represented by the recessive level (Logical 1). If one node transmits a dominant bit and another node transmits a recessive bit then there is a collision and the dominant bit "wins". This means there is no delay to the higher-priority message, and the node transmitting the lower priority message automatically attempts to re-transmit six bit clocks after the end of the dominant message. This makes CAN very suitable as a real time prioritized communications system.

  The exact voltages for a logical 0 or 1 depend on the physical layer used, but the basic principle of CAN requires that each node listens to the data on the CAN network including the transmitting node(s) itself (themselves). If a logical 1 is transmitted by all transmitting nodes at the same time, then a logical 1 is seen by all of the nodes, including both the transmitting node(s) and receiving node(s). If a logical 0 is transmitted by all transmitting node(s) at the same time, then a logical 0 is seen by all nodes. If a logical 0 is being transmitted by one or more nodes, and a logical 1 is being transmitted by one or more nodes, then a logical 0 is seen by all nodes including the node(s) transmitting the logical 1. When a node transmits a logical 1 but sees a logical 0, it realizes that there is a contention and it quits transmitting. By using this process, any node that transmits a logical 1 when another node transmits a logical 0 "drops out" or loses the arbitration. A node that loses arbitration re-queues its message for later transmission and the CAN frame bit-stream continues without error until only one node is left transmitting. This means that the node that transmits the first 1 loses arbitration. Since the 11 (or 29 for CAN 2.0B) bit identifier is transmitted by all nodes at the start of the CAN frame, the node with the lowest identifier transmits more zeros at the start of the frame, and that is the node that wins the arbitration or has the highest priority.

  For example, consider an 11-bit ID CAN network, with two nodes with IDs of 15 (binary representation, 00000001111) and 16 (binary representation, 00000010000). If these two nodes transmit at the same time, each will first transmit the start bit then transmit the first six zeros of their ID with no arbitration decision being made.


Arduino Uno R3 cannot detect GPRS Shield SIM900

After many trials, I found the solution to my problem, thanks to @Majenko for mentioning the jumpers.
I am still stacking the SIM900 module on top of Arduino.
Switching the jumpers from D1 and D0 to D8 and D7 solved the problem (see green square on the pic)
I don't know why it needs to be on D8 and D7 since on board it says TX=0 and RX=1 and vise-versa for Arduino

Then used the below sketch from this tutorial > https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

With this, it displays correct output on serial monitor based on the tutorial and I can confirm that its working as well on my windows form application as it can send sms from the application.


Assuming you have the Pro Micro core, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.


Preforming impedance termination for UART Communication (TX and RX) pins

The relevant parameter is not the length of the link, but its
characteristic impedance. For a twisted pair connection, this is
typically in the order of 100 to 120 Ω. It should be specified in
the datasheet. Your cable is not a twisted pair, but its geometry is
quite close. Just make sure that there is a ground or Vcc line between
the two data wires in order to minimize cross-talk. If you want to
compute that impedance yourself, here is an online
calculator.

Connect the resistor in series with the TX pin, i.e. between the pin and
the data wire. Note that the pin already has an internal output
resistance of about 25 Ω, so you would add no more than 100 Ω
in series.

If you search online about termination resistors, you may learn tat they
are often put between the receive pin and ground, or even at both the
sending and the receiving end. In high frequency applications, the
latter is often the preferred configuration, as it prevents the signal
to be reflected from either end of the link. However, for logic-level
signals, that configuration would attenuate the signal too much. On the
other hand, terminating only at the receiver would put excessive load on
the TX pin. Thus, sender-side termination is your best option. A
resistor in series with TX does not prevent a reflection at the RX end,
but it prevents the reflected signal to be reflected again and cause
oscillations.


Arduino code for thermistor respiratory monitor

The primary reason your code doesn't work is very simple: every time you go around the loop you set

timer = millis();

and if the reading is greater than 200 you set

currentTime = millis();

but those two statements are executed just a few microseconds apart, so the difference between them (in milliseconds) will almost always be zero (it might occasionally be one if you happened to cross a tick boundary, but it will never be more than that).

There are a few other problems with the logic of your code, which I think you'll understand when you look at some code that will work. Try something like this:

enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;
        float breathrate = 60000 / period_respiration;
        Serial.print("Inhaling /tRespirations per minute: ");
        Serial.println(breathrate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

The above code will give you the instantaneous respiratory rate, which probably will jump around a bit more than you would like. You probably want to add some dependency on prior history (hysteresis) to smooth it out a bit. One easy way is to put this through a low-pass filter algorithm to get a moving average value for the respiratory rate. That way the rate goes up when you breathe faster and down when you breathe slower but it doesn't instantaneously jump around on every breath.  Here's what that might look like:

// Global variables
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState = Exhaling;
float breathrate = 0;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;

        if (period_respiration == 0)
            breathrate = 0;
        else
            breathrate = 60000 / period_respiration;

        Serial.print("Inhaling /tResp Rate: ");
        Serial.print(breathrate);

        if (movingAvgRespRate == 0)
            movingAvgRespRate = breathrate;
        else
            movingAvgRespRate = (int) ((0.2 * breathrate) + (0.8 * movingAvgRespRate));

        Serial.print("/tAvg Resp Rate: ");
        Serial.println(movingAvgRespRate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

This code compiles, but I did not happen to be near an arduino with a sensor, so I didn't run it -- there could be issues, but this should be enough to put you on the right track. Good Luck!


atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v

I would suspect that the 328P's fuses were not programmed as defined in the boards.txt This needs to be explicitly done.

uno.bootloader.low_fuses=0xff
uno.bootloader.high_fuses=0xde
uno.bootloader.extended_fuses=0x05
uno.bootloader.path=optiboot
uno.bootloader.file=optiboot_atmega328.hex
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F

if not done. several things can go wrong.

oscillator won't start on external crystal
oscillator will be at wrong speed code
wont start at bootloader


Trying to move servo motor via 3 buttons

You are really overthinking things there. A servo will move to an angle if you just give it the final angle to move to. You don't need to nudge it to the final angle by visiting every angle in between, and you don't need to know what angle it's at currently.

You can simply do:

if (digitalRead(FIRST) == LOW) {
    myservo.write(0);
}

if (digitalRead(SECOND) == LOW) {
    myservo.write(90);
}

if (digitalRead(THIRD) == LOW) {
    myservo.write(180);
}

However if you wanted to slow the movement down, which would entail moving the servo in smaller steps, I would separate out the current angle and positioning from the buttons, which would set a desired angle.  Something more like:

static uint8_t desiredAngle = 0;
static uint8_t currentAngle = 0;
static uint32_t timestamp = millis();

// Choose a new desired angle
if (digitalRead(FIRST) == LOW) {
    desiredAngle = 0;
}

if (digitalRead(SECOND) == LOW) {
    desiredAngle = 90;
}

if (digitalRead(THIRD) == LOW) {
    desiredAngle = 180;
}

// Every 10ms "tick" the servo towards the desired
// angle by 1 degree
if (millis() - timestamp >= 10) {
    timestamp = millis();
    if (desiredAngle > currentAngle) {
        currentAngle++;
        myservo.write(currentAngle);
    } else if (desiredAngle < currentAngle) {
        currentAngle--;
        myservo.write(currentAngle);
    }
}


When should I use a transistor, mosfet, and when should I use a relay?

Transistors (such as Bipolar Junction Transistors (BJT)) are solid state switchers, that is, they don't have any moving parts. Metal-Oxide-Semiconductor Field-Effect Transistors (MOSFET) are also transistors, but are voltage controlled, whereas classical BJTs are current-controlled. Relays are more expensive, but they have moving parts.
BJTs and MOSFETs produce a lot of heat (with high currents). They both have three pins (usually) called the base, collector and emitter (in the case of BJT) or gate, source, drain (in the case of MOSFET). More info here
Relays use a magnet to control the position of a metal switch. They generally take more power than an Arduino pin can deliver, and therefore they are often controlled by a transistor. Relays can usually switch more current than either a transistor or a MOSFET.
There are also Solid State Relays (SSR), which have a triac (a device similar to a transistor) in them. These can't switch as much as a normal relay, but they generally have better ratings than MOSFETs and BJT. example


Why does Keyboard.Print adds random values to url?

You have some unicode characters in your URL. Remove them.

https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                      ^^^^^^^^^^^^


How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?

for length such as this, you should be using protocols that are designed for length, such as:

UART,
CAN,
Ethernet

for UART, you can't of course use a direct connection between the two boards, you need to upgrade the connection and wiring to either rs232 or rs485, using a driver between the arduino pins and the cable.

Though, the simplest solution would be to plug the Arduino on the Raspberry Pi using a lengthy USB cable (or more likely 3 five meters cable), which should work fine as long as you only do serial communication. The USB 2.0 limitation of 5 meters are for "hi-speed" connections, which is not our concern for simple serial data communication.

HTH


Use Adafruit Colorsensor to distinguish between green and red

Based on what I could find, you will have to calibrate the sensor to recognize these colours. First, run the Colourview code. Take down the raw RGB and CLEAR values obtained for an object you consider green and another you consider red. Find out if these values are consistent, each time you power down the sensor and turn it on again. If they aren't, record how much dead zone there is i.e. the maximum difference in readings (between resets) that you get for the same colour. Then using the values you get, try this code:

#include <Wire.h>
#include "Adafruit_TCS34725.h"

#define MAX_OFFSET 50  // the maximum diff you found between readings

typedef struct {  // struct to hold raw color data
   uint16_t red;
   uint16_t green;
   uint16_t blue;
   uint16_t clear;
} Color;

Color my_red = {3344, 3333, 23444, 3333}; //here you enter your minimum recorded values for red in the order of the struct members above
Color my_green = {22222, 4444, 5555, 3333}; //the same for green

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }
}

void loop() {
  uint16_t clear, red, green, blue;

  tcs.setInterrupt(false);      // turn on LED

  delay(60);  // takes 50ms to read

  tcs.getRawData(&red, &green, &blue, &clear);

  tcs.setInterrupt(true);  // turn off LED
  if (compare_colour(&my_red, red, green, blue, clear)){
      Serial.println("I see red.");
  }
  else if (compare_colour(&my_green, red, green, blue, clear)){
      Serial.println("I see green.");
  }
}

boolean compare_color(Color * std, uint16_t r, uint16_t g, uint16_t b, uint16_c){
if ((r - std.red <= MAX_OFFSET) && (r - std.red >= 0) &&
      (g - std.green <= MAX_OFFSET) && (g - std.green >= 0) &&
      (b - std.blue <= MAX_OFFSET) && (b - std.blue >= 0) &&
      (c - std.clear <= MAX_OFFSET) && (c - std.clear >= 0))
  {
      return true;
  }
  return false;
}

You can use this code directly after you have gotten the sensor readings for red and green objects.


Control solenoid valve with arduino running on battery

Vin and the barrel jack are the same power input on Uno.

RAW is the label for Vin on Mini Pro.

You can connect the + of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.


LED Blink in assembly with timer1 output compare interrupt not working

I am not set up to test your code right now, perhaps later.  But:
    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

When set to ones, the low order three bits of TCCR1B, select an external clock source at the T1 pin, for clocking on a rising edge.  Probably what's happening is that when you finger is near enough the T1 pin you are capacitively coupling mains frequency to it causing it to tick.
/256 prescaler would have 100 in the lower three bits.
If I manage to get a proper environment up to test your code, I'll look into it a bit more thoroughly.


Is there a working combination of Arduino IDE + Ardublock?

I found that Ardublock project was forked on Github, and the latest release indeed works with up-to-date Arduino IDE.


Arduino program using i2c stops working after printing to OLED a few times

This is wrong in many ways:

String input = Serial.readString();
serialInputBuffer = new char[input.length()];
input.toCharArray(serialInputBuffer, input.length());

What's fatal is that you later don't free the memory allocated with new. Don't use String and new. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.

Use a global buffer like char serialInputBuffer[64]; and use:

int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.


This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)

If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)

In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.

I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.

The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I did get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.


You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state.  Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.

An SDcard is neither necessary, nor a good idea.  If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card.  They will also be simpler to support in software.  Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.

Your main power consumption win however will be sensors.  If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption.  Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened.  Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.


How to make 12V flashing LEDs using an Arduino Uno?

Use a N-channel MOSFET, wire load to drain pin, source to (common) ground, and place a 1 kilo-ohm resistor in series with your arduino pins. Bear in mind that MOSFETs respond to voltage, not milliamps, on the gate - get one that responds well to 5V logic.


You need some way of getting the data from the Arduino to the PC. There's a number of ways of doing it depending on what resources you have available.

Through serial as CSV

This entails printing the data to the serial port in CSV format then using some software on the PC to capture that and save it to a file. That could be as simple as a good terminal emulator that provides "capture to file" or similar, or you could write your own program in your favourite programming language.  This method is essentially free.

To an SD card

Writing the data as a CSV file onto an SD card directly attached to the Arduino can be quite convenient. It means you can then just take the SD card with the data on it and slip it into your computer to import the data as you would with any other file.  It needs an SD card shield or breakout board attaching to the Arduino

Through the network

If your Arduino has a network connection of some form (WiFi shield, Ethernet shield, etc) you could POST the data to a web page running on your PC and store it in a CSV file for later importing. Probably the most expensive option but it does mean you can do things with the data "live" as it comes in.


Disable auto-reset Mega 2560 on serial monitor open using 60 ohm resistor

A 22uF cap between reset and ground does work on my Mega 2560 - opening the serial monitor will not restart the program. However, the Mega is then not downloadable. Therefore, I grounded the cap thru a normally closed relay and connected its control to a digital output. I normally operate with the relay closed. When I want to download a new program I open the relay first. It works great :-)


Can we use UART COMMUNICATION with MCP23017?

I can think of one way.
In theory you could use the GPIO pins of the mcp23017 to control a couple of 2-way multiplexers. With these multiplexers you could split your Rx/Tx pins to more than one serial bus.
May it be obvious that you cannot used the split busses at the same time. So depending on your specific use-case this may or may not be a solution.


Confused between SPI and I2C for SSD1306 OLED

SCK and SCL are the same thing.

Serial ClocK
Serial CLock

They seem to be interchangeable. The fact you have SDA (Serial DAta) as opposed to separate SDI / SDO or MOSI / MISO pins means it's I2C.

Wire it like you would any other I2C device.


How to prevent file overwriting in processing?

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */));

The true is the append mode flag.
Also check if you're using

pw.append(p.toString());
        pw.append("sdf");

https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending


Read gyro output values with other programming languages

If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.


Serial communication between PC and Arduino via RS232 using C++

It because that in your c++ application you haven't explicitly mentioned serial port speed.
Mention the same baudrate which you have used in arduino here(c++).

Assuming that you have used rs232 to ttl converter, as you are getting some output,
Which in other case wouldn't as you would have already burned your mcu.