ATmega 2560 with Arduino bootloader running issue

The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.

Solution:- Connect 10K pull-down on RX pin resolved this problem.


Is the used clock for the Baudrate generator adjustable on an arduino due?

The clock of the transmitter and receiver have to be matched.

In theory, the worst case error tolerable is 1/2 bit per byte.  For the 10 bit byte (1 start, 8 data, 1 stop) that leads to a +/- 5% clock error tolerance that you will find reported.  Note that this actually depends on the specific UART implementation, either chip or internal.  There are various methods of sampling that make some UART's better than others.  It is common to sample in the middle, but some chips have methods to improve noise rejection.

For the receiver side, do not rely on what the terminal program is showing you.  Few applications would manipulate the clock directly; they commonly just call an API with an enumerator for the speed.  You need to know exactly what hardware the receiver side has and its clock.

In practice, the theoretical limit is not going to work.  At high data rates, the noise on the cable will eat away at that safe margin.  More common recommendations will say +/- 1% which allows for noise on the edges of the bit transitions.

The noise on the signal is important at these data rates.  You indicate you are using TXD/RXD which is just logic level.  You cannot connect logic level any significant distance.  If the two are directly next to each other with excellent attention to wiring, you might have a chance.  Adding transceivers will help your chances significantly.

Also, note that changing to 7 bits helps.  Do you need 8 bit data?

So in summary:
- The receiver is more important than the transmitter, but they both have to match.  If you can't find a match of clocks to 1%, you will have data errors.
- At these speeds, the cabling and connection is critical.

This article at Maxim is a good starter Maxim "Determining Clock Accuracy Requirements for UART Communications.


You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).

Try the following:

float x=10; float y=50; float z;

void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

void loop() {
  // put your main code here, to run repeatedly:
}

Update

What even is easier and also works (thanks to Ruslan and Juraj):

float x=10; float y=50; float z=x*y;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}


ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)

The crash report is printed to 'standard output' by __wrap_system_restart_local in core_esp8266_postmortem.c in esp8266 Arduino core.

The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by Serial.setDebugOutput(true);.

At compile time the initial debug output is controled by -DDEBUG_ESP_PORT=, for example -DDEBUG_ESP_PORT=Serial1. The Tools menu "Debug port" sets the DEBUG_ESP_PORT define. The crash report is not controlled by "Debug level" setting.


ESP8266-01S Stopped responding after second launch

You need to re-flash your AI Thinker firmware. AT+IPR kills certain versions of the firmware.

Install the latest version of the firmware and use AT+UART_DEF=9600,8,1,0,0 and AT+UART=9600,8,1,0,0. (The former sets the default baud rate, the latter the current baud rate).

You can read more here.


What kind of data type can be use store a binary bit-stream which is more than 64-bits?

There is no builtin data type that can store 78 bits. However, it depends a bit what you want to store. Like the following cases:

If the 78 bits are one 'entity' (e.g. one really big value), you can store it as an array of bytes (10 bytes of 8 bits = 80 bits, leaving 2 bits unused)
If the 78 bits can be split up in smaller parts, you can:

Create a structure or class to contain the sub elements into fields (instance variables), using for each sub type a normal type (e.g. signed/unsigned 8, 16 or 32 bits).
Create bit fields to save some memory if there are small items and memory space is an issue.
Or a combination of the above

If you have many of these items and you want to save space (thus the 2 unused bits of each 80 bits), you can create a big array that contains many items, and use bit operations to get each item. E.g. the first element will be in the first 10 bytes, where the last 2 bits are not part of the element. The second item will use the remaining 2 bits and the following 78 - 2 = 76 bits, etc. This saves only 2/80 * 100% = 2.5% so only use this when really needed.


First of all, you must test if the device that you are trying to access, actually exists. The device file may change when you replug the Arduino. The easiest way to accomplish that is to find the device name in the error message, in this case /dev/ttyACM1. Then check two things:

Does the device file exist in  the /dev tree? ls -l /dev/ttyACM*
Is the Arduino IDE configured to use the correct device? Check under Tools => Serial Port.

Maybe another application is using the device. When working on Linux, you can verify this with the following commands:

$ lsof /dev/ttyUSB0
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
avrdude 7356   jippie    3u   CHR  188,0      0t0 266450197 /dev/ttyUSB0

or

€ fuser /dev/ttyUSB0
/dev/ttyUSB0:         7356

Where of course you have to replace /dev/ttyUSB0 with the device file as mentioned in the error message. In case of this question /dev/ttyACM1, but do notice that the number can change when you unplug the board for a moment and then replug it.

In both results, the 7356 is the PID of the process that is locking the device. In my example I was reading flash from the command line, so the output for your specific situation will be different. To identify the process, you can use:

$ ps -fp 7356
UID      PID  PPID  C STIME TTY          TIME CMD
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

or a more portable command:

$ ps -ef | grep 7356
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i


How to operate under linux an USB to I2C adapter based on the FTDI FT232R?

I wrote a simple python script which implements the protocol for single byte transmissions (R/W).

If there is interest/requests, I can extend it.

code below:

#!/usr/bin/python
#
# Copyright (c) 2016, Igor Stoppa <igor.stoppa@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#

'''
Simple script for driving the USB-to-I2C adapter based on the FTDI FT232R.
References:
Adapter:      http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm
Chip:         http://www.ftdichip.com/Products/ICs/FT232R.htm
I2C protocol: http://www.robot-electronics.co.uk/i2c-tutorial
'''

def parse_args():
    '''
    Process command line options.
    '''
    import argparse

    def auto_int(x):
        return int(x, 0)

    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--address', type=auto_int,
                        help='The 7bit address of the slave.')
    parser.add_argument('-p', '--port', default="/dev/ttyUSB0",
                        help="Serial port provided by the adapter. "
                             "Must have sufficient rights to open it R/W.")
    subparsers = parser.add_subparsers(dest='subcommand')
    #  subparser for write
    parser_write = subparsers.add_parser('write')
    parser_write.add_argument('-r', '--register', type=auto_int,
                              required=True,
                              help='Hex id of the target register - 1byte.')
    parser_write.add_argument('data', nargs = '*', type=auto_int,
                              help='Device dependent amount of data.')
    #  subparser for read
    parser_read = subparsers.add_parser('read')
    parser_read.add_argument('-r', '--register', type=auto_int, required=True,
                             help='Hex id of the target register - 1byte.')
    parser_read.add_argument('data', type=auto_int,
                             help='Device dependent amount of data.')
    return parser.parse_args()

def get_serial(port):
    '''
    Open the port with the adapter parameters.
    '''
    try:
        import serial
        ser = serial.Serial(port=port,
                            baudrate=19200,
                            parity=serial.PARITY_NONE,
                            stopbits=serial.STOPBITS_TWO,
                            bytesize=serial.EIGHTBITS,
                            timeout=0.500,
                           )
    except OSError as e:
        import sys
        print  e
        sys.exit("Could not open " + port)
    return ser

def write(ser, addr, reg, data):
    '''
    Use the adapter-specific protocol for writing out data.
    '''
    I2C_AD1 = 0x55  # R/W one or more bytes for 7bits addresses.
    ser.write(chr(I2C_AD1) + chr(addr) + chr(reg) + chr(len(data)) +
              "".join([chr(i) for i in data]))
    # Read the retval. Leaving it in the buffer of the PIC will cause
    # read mismatches in following read operations.
    if ser.read() is 0:
        import sys
        sys.exit("Failure writing.")

def read(ser, addr, reg, data):
    '''
    Use the adapter-specific protocol for reading in data.
    '''
    I2C_AD1 = 0x55  # R/W one or more bytes for 7bits addresses.
    ser.write(chr(I2C_AD1) + chr(addr + 1) + chr(reg) + chr(data))
    return " ".join(['0x' + format(ord(i), '02x') for i in ser.read(data)])

if __name__ == "__main__":
    args = parse_args()
    ser = get_serial(port=args.port)
    if args.subcommand == 'write':
        write(ser=ser, addr=args.address, reg=args.register, data=args.data)
    if args.subcommand == 'read':
        print read(ser=ser, addr=args.address, reg=args.register,
                   data=args.data)


yellow LED not turning off in traffic light simulation

Your program runs in a tight loop - an extremely tight one which does all but nothing in any state but 1 or 2.  However what happens in these states is interesting.

Essentially what you have is

Quickly check for input - which won't be detected unless the bottom is being held down at this precise narrow slice of time between long delays
Turn on an LED, apparently from your comment the yellow one
Change the LEDs but recycle so quickly that this fact is generally invisible.

The result of this is that instead of a brief pulse of yellow, you will be seeing near constant yellow, because that is the only part of your loop which takes any time.

Probably what you want to do is to advance the state when you are done with your brief yellow flash.  But it's not possible to say what you should advance the state to, since it's unclear how you want this light to work.  If it is purely timer-based, then you don't need any input at all; while if the button is supposed to do something but a timer should also be used, then you have a more complicated problem.

Essentially, before you can write any code you must write in words or diagrams a comprehensive set of "rules" for what the system is supposed to do.


Why can't I see the serial plot with the following code for arduino?

The serial plotter requires just numbers and nothing else.

It can't understand the data in the format:

sensorValue=49

It just expects:

49

Remove the line

Serial.print("sensorValue=");

and it will start working.


External (pin change) interrupt and power consumption

You must not leave CMOS inputs floating. This will increase power consumption, and as a worst result may damage the device. Use an external pull-up if you feel that the internal pull-up passes too much current.


You are recursively calling connectWifi() and therefore your setup function results in an infinite loop.
You must not implement loops and for processes, which take some time, you should set and ask a flag.
Btw. why don't you use the official ESP WiFi library?


On/off button for Arduino Mega for 5V input pin- hardware based auto on/off arduino(PUSHBUTTON NOT AS INTERRUPT)

Your question is very badly written, and a lot of infos are missing. In any case, from what I understood from your comments, you want a button that works this way:

The arduino is not powered up
You press the button; the arduino turns on, and starts the operations.
You press the button; the arduino shuts down.
You press the button; the arduino turns on, and resumes the operations from where it was.

I'm not sure about the last point, so first of all I'll give you some hints about the first three points.

You can modify the circuit in a way similar to this:

simulate this circuit – Schematic created using CircuitLab

(I named the two arduino pins as A and B because it is not important which pins you use, just two separate pins).

The diodes can be any diode (e.g. 1N4148). The PMOS and NMOS are not critical, provided that they can fully turn on with a 4-5V gate voltage and that the PMOS can bear the current you need.

When the arduino is shut down, the NMOS is off, and so is the PMOS. When you press the button, the voltage on the NMOS gate becomes about 4.5V, so it turns on. the PMOS turns on too, and so the arduino sees some power. At the very first moment, it has to pull pin B to 5V. This way even when the button is not pressed anymore, the board will be powered. When the user presses the button, the arduino can sense it through pin A. This way it can go into shutdown mode. Here is a sort of base for handling this behavior. Please note that I'm using the Bounce2 library, since I particularly like it when dealing with buttons (it automagically handles bounces and also give more info about the edges).

#include <Bounce2.h>

const byte pinA = the pin A number;
const byte pinB = the pin B number;

Bounce pinA_debounced = Bounce();

void shutdown() {
    // Turn off the board
    digitalWrite(pinB, LOW);
    // Farewell, cruel world!
    while(1); // wait for a power off
}

void setup() {
    // Turn on the board
    pinMode(pinB,OUTPUT);
    digitalWrite(pinB, HIGH);

    // Initializate the debounced pin
    pinA_debounced.attach(pinA, INPUT_PULLUP);

    // Other setup instructions
}

void loop() {
    // Update the Bounce instance :
    pinA_debounced.update();

    if (pinA_debounced.rose())
        shutdown();

    // Other loop instructions
}

If you want to save your data in order to resume it, well, this highly depends on your actual code. You will have to identify what is your "current status", then save it to EEPROM.

Here is, for instance, a program which outputs on serial one sequential number (from 0 to 254, then restart from 0) every second. When you shut it down, it will start again from the last one:

#include <Bounce2.h>

const byte pinA = the pin A number;
const byte pinB = the pin B number;

const byte valueAddress = 0x10; // Any value is fine for this
// as long as it is in the available EEPROM

Bounce pinA_debounced = Bounce();
byte value;
unsigned long lastMillis;

void shutdown() {
    // Save status BEFORE turning down the power
    EEPROM.update(valueAddress, value);

    // Turn off the board
    digitalWrite(pinB, LOW);
    // Farewell, cruel world!
    while(1); // wait for a power off
}

void setup() {
    // Turn on the board
    pinMode(pinB,OUTPUT);
    digitalWrite(pinB, HIGH);

    // Initializate the debounced pin
    pinA_debounced.attach(pinA, INPUT_PULLUP);

    // Restore the current value from EEPROM
    value = EEPROM.read(valueAddress);
    Serial.begin(9600);
    lastMillis = millis() - 1000;
}

void loop() {
    // Update the Bounce instance :
    pinA_debounced.update();

    if (pinA_debounced.rose())
        shutdown();

    if ((millis() - lastMillis) >= 1000)
    {
        lastMillis += 1000;
        Serial.println(value);
        value++;
    }
}


Can I program a factory fresh Atmega328P through UART pins without burning a bootloader?

No, the ATmega's ISP does not operate over the UART pins but only the ISP pins.

To program it via a UART, you need to first load a bootloader, unless your chip was pre-programmed by the vendor, something some offer as a value-added service (or even as an essential stock item, with an Arduino type bootloader)


Basically you would like to make a slot loading game system?
You're going to do some research yourself. But I'll do some thinking for you.

Your SD-card should have the compiled HEX code, probably along with some kind of checksum? You should check what your PC sends when you're uploading a program (along with the HEX program).
You're going to need 2 AVR microcontrollers and probably some soldering stuff.
Program the "master" Arduino to read the HEX from the SD card. Then make it add the checksum/things you saw your PC sent along. The master Arduino should reset the other ("slave") arduino before sending, just like the PC does, this is done in hardware, and you'll have to wire into the reset button.

I'm not sure if this would work at all. It just sounds like the only possible way.

Alternatively the parallax propellor has a possibility for self-modifying code, along with VGA graphics. This might be a better shot, it's architecture fits better to your project. And I believe there are some similiar projects with the propellor, though I'm not sure about the SD-card.


Arduino buzzer code sequence not triggering

The problem was with the buzzer, somehow was a faulty buzzer, I've managed to replace it and the problem was solved.
Thanks everybody for your time trying to help me!


What values are the Atmel MCUs EEPROMs preloaded with?


Having problems with I2C - Slave is receiving "b ~ ,,,"

In the slave code.  receiveEvent takes a number of bytes as a parameter, presumably you are supposed to read this many bytes, can you call read with that number?  Even if you did you are reading to a char pointer, which will cause issues unless read is allocating the memory, which you should then be releasing.  Basically you have a couple of issues here and you need to look at them.

In the Master code. sendTime doesn't look right.  I would expect you to have to send a certain number of bytes using the Write function.  You are just sending 32 chars, the fact you are sending signed char's rather than unsigned char's shouldn't be an issue (but its technically incorrect).

I don't really understand what you are trying to achieve in the rest of loop, annotation would help :)

OK, If you take this as a new version for the slave you should be able to see it working.  It might not be 100%, but you should get something.  (I haven't even compiled this code, so you might have to sort out a few bugs)

#include <Wire.h>

#define MaxTimeBufferSize (33)
#define MaxReadSize  (MaxTimeBufferSize - 1)
char timeBuffer[MaxTimeBufferSize];

void setup()
{
  Serial.begin(9600);  // Init first so you can see any issues during setup.
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
}

// Assumes the bytes are actually printable ASCII characters.
void receiveEvent(int bytes)
{
  const int bytesToRead = (bytes < MaxReadSize) ? bytes : MaxReadSize;
  for (int index = 0; index < bytesToRead; ++index)
  {
     timeBuffer[index] = Wire.read(); //read one character from the I2C
  }
  timeBuffer[bytesToRead] = 0; // Null terminate the bytes (so they will print as a string)
}

void loop()
{
  if (timeBuffer[0])  // Only print the buffer if there is new data
  {
    Serial.println(timeBuffer); // The buffer is NULL terminated.
    timeBuffer[0] = 0;  // Stop the buffer  printing again.
  }
  delay(1000);
}


Cannot write to HID USB device (Arduino, V-USB, HidSharp)

Found the error.
While the HidSharp was sending output reports, the device driver expected feature reports.
Changing the line

0xb2, 0x02, 0x01,              //   FEATURE (Data,Var,Abs,Buf)

to

0x92, 0x02, 0x01,              //   OUTPUT (Data,Var,Abs,Buf)

resolved the issue.


What is the relationship of an Arduino .ino file to main.cpp?

The Arduino uses the gcc compiler. That compiler wants a normal main function of course. Arduino has put a layer on top of that with setup and loop.

The hidden main function for basic Arduino boards is in main.cpp (click on it to see it).
You see that init is called, and setup and loop and a few other things.

To learn how to use setup and loop, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.

The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.

When you know how to use setup and loop, try the Blink Without Delay example. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.


How about

char array[5] = "T 20";
int num = atoi(array+2);

This obviously assumes that all your strings are of the same format "A NN". If not, you can try parsing it using strtok(). See this excellent answer.


LCD shows wrong value from MQ-135 sensor and the txt is stuck on screen

You made a mistake in the line:
else(co2lvl<=1600);

Because of the semicolon (;) it will not do anything for that condition. But instead the following lines will be executed always.
The following is a slight refactoring making your code more clear, removing also duplicated code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define sensor A0
int gas, co2lvl;

void setup()
{
  pinMode(sensor,INPUT);
  Serial.begin(9600);
  lcd.begin(20,4);
  lcd.clear();
}

void loop()
{
  co2lvl=gas-255;
  co2lvl=map(co2lvl, 0,1024,400,5000);
  Serial.print(co2lvl);
  Serial.print("ppm");
  Serial.println();
  delay(200);

  lcd.setCursor(0,0);
  lcd.print("CO2 PRESENT IN THE AIR");
  lcd.setCursor(0,1);
  lcd.print(analogRead(co2lvl));

  if      (co2lvl <=  300) { show(6, "EXCELLENT"); }
  else if (co2lvl <=  700) { show(4, "GOOD"     ); }
  else if (co2lvl <=  900) { show(5, "FAIR"     ); }
  else if (co2lvl <= 1100) { show(5, "MEDIOCRE" ); }
  else if (co2lvl <= 1600) { show(5, "BAD"      ); }
}

void show(int position, char* text)
{
  lcd.setCursor(position, 1);
  lcd.print(text);
}


Can I use an accelerometer to measure the velocity of a car in a curve?

I found out the answer to the question in the following article SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments
According to the article

When a vehicle makes a turn, it experiences a centripetal force, which
is related to its speed, angular speed and turning radius. Thus, by
utilizing the accelerometer and the gyroscope, we can derive the
tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.
The equation to measure the tangential velocity is:
v = Rω (1),
Where v is the tangential speed, R the radius of the curve and ω the angular speed.
As the centripetal acceleration is given by a = ω²R (2), reformulating (2) and substituting in (1), it is obtained:
v = a/ω (3).
Both a and ω are given by the accelerometer and the gyroscope respectively.


Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g.
This means you have a signal averaging at "338" when read using Arduino's analogRead() function, with spikes in either direction when acceleration changes.

You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:

int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  }
  else if (num_random == 0) {
    num_xaxis -= 200;
  }
  else if (num_random < 100) {
    num_xaxis += 1;
  }
  else if (num_random > 155) {
    num_xaxis += 1;
  }
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  }
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;
  }
  Serial.println(num_xaxis);
  delay(10);
}

Explanation: First, the value for 0g is determined from the voltage difference.
A random value is generated, ranging from 0 to 255.
If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added.
If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.

The serial commands only serve to let you watch the result in Arduino IDE's serial plotter.
If you need the spike to occur less frequently, adjust the delay(), or let the counter run to higher numbers.
If the CPU-blocking delay() command is an issue in your project, you could run the randomization code using a timer and an interrupt.

Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155).


Arduino UNO - Fluctuation of inputs and outputs

You seem to be experiencing cross-talk between the analog channels. This
happens because all the channels are funneled by an analog multiplexer
into the same sample-and-hold capacitor. If the source resistance is too
high, then the capacitor does not have enough time to charge to
the voltage of every channel.

Here is what the datasheet of the ATmega328P says about the
issue:

  The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less. [...] The user is recommended to
  only use low impedance sources with slowly varying signals, since this
  minimizes the required charge transfer to the S/H capacitor.

The problem can be mitigated by reducing the source impedance using a
capacitor at every pot wiper, or by giving more time to the
sample-and-hold circuit: make many dummy readings before the one reading
you want to keep. The proper solution would of course be to replace the
pots with 10 kΩ pots.


The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop

...
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask) {
  if (numloops++ == maxloops)
    return 0;
  width++;
}

// convert the reading to microseconds. The loop has been determined
// to be 20 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 21 + 16);

The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the this example . It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.

Where for signals over IR the typical library to use is shirriff/Arduino-IRremote library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by

#define USECPERTICK 50  // microseconds per clock interrupt tick

in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams.

Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.

microtherion/Arduino-IRremote fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own mpflaga/Arduino-IRremote fork, that adds several other features.

So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.

polls on a Timer event (e.g. 50uS)
captures the micros() on a PinChangeInterrupt
uses Input Capture Interrupts to grab the exact time


Do I need to use the PWM pins in order to control brushless motors Arduino Uno?

No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.

In some non critical conditions (ESCs are critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.


Can't get constant reading with load cells

Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.

Making the wires much shorter would likely also help. That would be a good test to see if it helps.

The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.


Can I connect an Arduino GSM Shield directly to a PC?

You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

  Power
  It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.


"invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).


Pin 13 fires relay when powering on... How to disable?

There are three things you can do:

Remove the bootloader entirely and program the board with a hardware programmer (USB-ASP, Another Arduino, etc).
Edit the bootloader source, recompile, and reinstall it to the board using a hardware programmer (as in option 1).
Just don't use pin 13 for the relay.

Of the three options the third one is by far the simplest.


There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.

Adding another periodic task in setup() (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.

The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

I  have filed a bug report, corrected the error, and raised a pull request with the fix in it.  Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2


It would be very useful, but afaik this is not possible, since the Arduino sketch you write communicates to the PC via the serial interface only.

The IDE/Arduino driver can use the USB to write your sketch and use the USB for communicating, but for sketches the USB (as direct medium) is not possible.

The SD card will not show up as a specific drive/map/folder on your PC.

Since you want to read the SD card, write in your sketch code to transmit the file(s) you want to send to the PC, to transfer them by UART, and on the PC write a program that reads the serial port and processes it.


It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.

A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).


Establishing an MQTT connection using Arduino Mega and ESP8266

You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).

Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.


How do I split a number into individual digits?

% 10 returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.

So if you have the number 10250 as an integer you can get at each number with:

10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

So your code could be written as:

num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.


No, this is not possible. The datasheet of the ATmega328P
states it has:

  8-channel 10-bit ADC in TQFP and QFN/MLF package
  6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP
package.


How to split a *char and pass to a function needing uint8_t?

I'm not real clear on exactly what you want to have there, but here are a few ideas that may help:

If you know what character you want, then just get it.  Like if you always want the second character (I think this is what you need):

void someFunc(char *p)
{
  char secondChar = p[1];
  Serial.print(secondChar);
}

If you just want the last character in the string no matter how long, get the length of it and then pull that character:

void someFunc(char *p)
{
  int len = strlen(p);
  char lastChar = p[len-1];
  Serial.print(lastChar);
}

If you want the last digit in the string no matter how long and no matter how many random characters that aren't digits after it:

void someFunc(char *p)
{
  int len = strlen(p);
  char lastDigitChar = 0;
  // Cycle backwards til we get the first digit
  for(int i=len-1; i>=0; i--){
    if(isDigit(p[i]){
      lastDigitChar = p[i];
      break;
    }
  }
  Serial.print(lastDigitChar);
}


How to extract code on one DT-06 board to another board?

Okay. I found a way to extract the binary file (stock firmware) from one DT-06 and flash it to another modified DT-06, by using esptool command
/*To extract firmware */:
esptool.py -p COM4 -b 460800 read_flash 0 0x400000 dt06_backup.bin
/*To flash the backup binary file to another DT-06 */
esptool.py -p com4 write_flash -fm dout 0x00000 dt06_backup.bin


One free pin. Need to display output for the user?

Seems you have I²C on the board you could possibly use an I²C LCD backpack, like from breakouts if you already have an LCD, this means you can have the RTC and display on the I²C bus and probably more things.

Another option seems you mentioned LEDs, you could still use the I²C bus and use an I/O expander and hook LEDs up to that and address them over the I²C. You can use a PCF8575(16 I/O), as there are Arduino libraries. There are breakouts for it. Or you could make your own from another AVR, like one from the ATTiny line, seems there is 5 LEDs.

A I²C bus example:

(source: ermicro.com)

Seems you want to use the PWM, you can use a dot/bar driver IC, such as the LM3914 it takes an analog value and shows it as a point on the strip of LEDs, example below:

The IC can also work down to 3V.

What you will need to do is add a low pass filter to convert the PWM to a smooth analog value. You will add this in place of the input circuitry(D1 & C1) there:

If there is any confusion on the LM3914, there are quite a few tutorials on google.


Unsure how to connect the anode in this circuit

Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors.  You have one per LED group instead of one per LED within a group.  The arrangement you have at the moment means that at best some LEDs will be dim or not light at all, and at worst will result in LEDs burning out.

There should be a resistor in every red, green and blue wire in your diagram.

As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time.  If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.


Light LED when 2 others are disconnected

You want the green LED to be on only when the red and blue LEDs are both off. In other words, you want the voltage on the green LED to be LOW only when the voltages on the red and blue LEDs are both HIGH. That is a logical NAND function.

Your right-hand circuit with the RGB LED won't work because the transistor's collector is connected to the wrong place - it's shorting out the battery! Another problem is that the Arduino can only switch to Ground or +5V, so it can't replace a 'floating' switch.

You need a configuration that produces a logical NAND function. Your left-hand circuit is doing it, but won't work with a common anode RGB LED. So swap the transistor to a PNP  type, and add a couple of resistors to switch it on when either input goes low, like this:-


digital input pins on arduino nano with standard firmata and pyfirmata are always 'None'

"None" indicates that there is no data to be found by read() because the incoming serial stream has never been serviced.  Launch an Iterator to start a new Python thread that services the serial port in the background.
it = pyfirmata.util.Iterator(board)
it.start()


How do I know when the connections is ready between Arduino and QSerialPort

I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port.  That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude.  The timeout of that signal is configured in the bootloader, and is usually something like 1 second.

The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.


No, you cannot.  The LM35 is rated for an absolute maximum junction temperature of 150°C.  Any higher than that and you will damage it.

For temperatures above that you are better using a thermocouple.


Why is there a third connection to the host in this 3 wire current output sensor diagram?

The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.

All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

simulate this circuit – Schematic created using CircuitLab

In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good.  RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does).  D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.


Arduino/DuinOS vs Normal C/ARM Programming

My understanding is that the Arduino language is cross-compiled into C-compatible binary,

There is no "Arduino language". Programs are written in C++ or C, and the IDE mangles them in certain ways in order to ease development by beginners (and on occasion frustrate development by veterans).

  and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip,

No. The uploading of the compiled code is done using a separate program, usually AVRDUDE or bossac, and the code is uploaded into flash. Data can be optionally uploaded into EEPROM via the same program, but this is not required.

  which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

Not by default. If you want to use DuinOS then you will need to download, compile, and upload it yourself.

  My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

Nope. Any system can be run without an OS.


Connect Arduino to Socket IO Webserver via Esp8266

Using the ESP8266 in general

The easiest, most flexible, and most efficient way is to program the ESP8266 directly.
If it is possible, have it replace the Arduino entirely. To do this, it is best to get an ESP8266 development board that breaks out all IO pins and has a USB interface for easy programming. Programming these development boards is just like programming an Arduino: plug in the USB connection and hit upload in the Arduino IDE. One of my favourites is the WeMos D1 mini (around $3.50 from China).
The ESP8266 is a very powerful microcontroller on its own: it has a 32-bit processor that runs 10 times faster than an Arduino Uno, it has up to 4MB of flash memory (vs 32KB on the Uno), 160KB of RAM (vs 2KB on the Uno). It has 11 digital IO pins, an analog input, support for I²C, SPI, PWM, etc., just like an Arduino. If you use AT commands, you don't use its full potential.

Your specific situation

Given that you already bought an ESP-01 + adapter that only gives you access to the UART, connecting the sensor to the ESP directly is probably not possible.
In this case, you can do one of three things:

1) Program the ESP8266 directly:
Write a program that just reads a number from the serial port, and sends it to the server over WiFi.
This is the easiest, because you can use all features of the ESP8266, and you don't have to change the program that you wrote for the Arduino (it should just measure the sensor value, and send it to the ESP8266 over the serial port, this is exactly the same as sending it to the serial monitor on your computer).

2) Don't program the ESP8266, but use an AT commands library on the Arduino. (For example WiFiEsp)
The downside is that you have to make significant changes to your Arduino sketch, and that you cannot use all of the functions and resources of the ESP.

3) Control the ESP8266 using AT commands yourself, without any libraries.
This is very cumbersome, and is a complete waste of time, IMHO.

Practical

Programming the ESP8266 directly
To program the ESP8266 directly (both with an Arduino and stand-alone), you need a USB-to-Serial converter. You can either use something like an FT232 (3.3V) or an Arduino. How to program it is covered here. If you use an Arduino as USB-to-Serial adapter, the right connections are TX-TX, RX-RX.

Using AT commands or an AT commands library
If your Arduino has a hardware UART that is not used for programming the Arduino (e.g. Arduino Mega, Arduino Leonardo, Arduino Due, ...), you can use this UART for communicating with the ESP8266. The right connections are TX-RX, RX-TX. You can use any baud rate that's supported by both devices (9600 - 921600).
If your Arduino doesn't have an extra hardware UART, you'll have to use the UART on pins 0 and 1, that's used for programming, and you'll have to disconnect the ESP8266 every time you upload new firmware to the Arduino.
Alternatively, you can use SoftwareSerial. Keep in mind that this is far from an optimal solution, as it uses a lot of resources, it is very slow, and data might get corrupted if you spend a lot of time in interrupts on the Arduino.
To use the ESP8266 with SoftwareSerial, you need to lower the baud rate to 9600 baud. To do this, first upload an empty sketch (bare minimum) to the Arduino to make sure that the hardware UART is not used. Then connect the ESP8266 to pins 0 and 1: TX-TX, RX-RX.
Open the Serial Monitor from the Arduino IDE, and select the baud rate that the ESP8266 is currently operating at. (This is probably 115200, but it could be something else.) Select "Both NL + CR" as the line ending, and send "AT" (without the quotes) to verify that it is working. If everything works, it should answer with "OK". If it doesn't, check your hardware, or try a different baud rate. Finally, send "AT+UART_DEF=9600,8,1,0,0" to set the baud rate to 9600 baud. Then change the baud rate of the serial monitor to 9600 as well. Send "AT" again to verify that it is working.
Now you can connect the ESP8266 to the SoftwareSerial pins, using a baud rate of 9600 baud.

Edit: The WebSocket protocol is not supported using AT commands, so you have no other choice but to program the ESP8266 directly.


Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag bool a_flag in this if(lcdScroll==LOW) clause and checking if(a_flag) in the highest scope of the loop() section. This is where you print("test");.

In respect to your code this will look like:

bool a_flag=false;
void loop() {
  // some irrelevant stuff
  if ( newSwitchState != oldSwitchState) {
    // some stuff
    if ( lcdScroll == LOW ){
      // stuff you would handle here
      a_flag=true;
    }
    else {
      // stuff you would handle here
      a_flag=false;
    }
  }
  if (a_flag) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}

Beside this general solution you could simply do the following in your specific case:

loop(){

  // your actual code

  if (lcdScroll) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}


How can I tell which pins I will have left available by looking at a shield?

If you look in the 'Tutorials' section of this page you can see the pins used. All of the buttons come through in one analogue input and you'll need a further 7 digital I/O pins. So 8 in total which would leave 5 analogue and 4 digital (I think) pins on an Uno.

As for how to tell which ones, does it matter in advance? I would just map the I/O in the sketch to suit. If you need to plan that far in advance though, it seems that J5 in this schematic shows which pins travel through the shield (i.e. are available to use in conjunction with the shield). Also J6 shows the 5 remaining analogue pins.


avr-libc lacks strtoull() that I would normally use for such a conversion. You will have to do it manually.

Fortunately it's quite simple - just start with y=0 and, for each character in the string, multiply y by 10 then add the numeric value of the character in the string:

String x = "68976543210";
unsigned long long y = 0;

for (int i = 0; i < x.length(); i++) {
    char c = x.charAt(i);
   if (c < '0' || c > '9') break;
   y *= 10;
   y += (c - '0');
}

Note that the Arduino Print API has no method for printing a 64-bit integer.


Running out of pins in a 4x7-segment display clock

The basic idea is this:

First, connect segment A of each display together, and all the segment Bs together, and all the segment Cs and so on.  Each "group" is driven by one pin on the Arduino.  For this you will need seven pins.

Your displays will have either a common anode or common cathode - perhaps you have that connected straight to +5v or straight to ground currently.  Instead, you connect the "common" pin from each display to a spare pin on your Arduino - so using another four pins.

Remember the resistors too.

Now, you can light up any segment on any display, by setting the appropriate segment pin and the appropriate common pin to the right values.

Make sense?


Powering Arduino and LED strips from one adapter

Powering an Arduino and LED strips is no different to powering your TV, satellite receiver, DVD player, etc all from one socket in the wall.

Connect all the grounds (-) together, and connect all the powers (+) together.

All you need to worry about is that the total current draw of all the devices combined doesn't exceed the amount of current that the power supply can provide (oh, and that they all operate at the same voltage, of course).


Error: invalid application of 'sizeof' to incomplete type 'int []' when trying to compute the size of an array in a library

The reason is that in your sketch you import only the header file (which is good). However, there it is an array (int[]), not the initialized array.

For that you would need to include the cpp but that is bad practice (if even possible).

So instead, create a new (constant) variable, and assign it.

(more or less pseudo code, due to lack of a compiler):

Lib.h:

class Lib {
  public:
    static int arr[];
    static int arr_length;
};

Lib.cpp:

#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};
int Lib::arr_length = sizeof(Lib::arr);

Sketch:

#include <Lib.h>

void setup() {
  Lib::arr_length;
}

void loop() {}

See also the comment of LukasFun below. It is also possible to set the size of the array in the header file.

My advice though is keeping all assignments in the implementation (cpp) file. The header file is for defining items, the implementation file for initializing/assigning. But it works too, to initialize items in the header file.


How can I configure Arduino after programming it (for post upload wifi configuration)?

I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface.  I've been dealing with the same question myself and this might be a workable solution.  The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.

Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield.  You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.


No, there is nothing you can do.

Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.


Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.

Serial.println(R"(\no esca\pe ch\ara\cters)");


How do I use lambda functions in Arduino?

std::function is not supported by the Arduino environment.
(Edit: as mentioned by KIIV in a comment, it's supported on ARM
targets, but not on AVR.) You can, however, pass a non-capturing lambda
to a function that expects a plain function pointer. For example, given
T reduce(const T initial, T (*acc)(T, T)) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }
    return value;
}

You can call it as
int sum = test.reduce(42, [](int acc, int value){ return acc + value; });

If you want your lambda to capture something, it would seem you are out
of luck...


Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis


Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.


GPS Short distance calculations, accuracy limitations for 1-30 meter distance

Take a look into Differential GPS, 10cm accuracy

Differential Global Positioning Systems (DGPS) are enhancements to the Global Positioning System (GPS) which provide improved location accuracy, in the range of operations of each system, from the 15-meter nominal GPS accuracy to about 10 cm in case of the best implementations.
Each DGPS uses a network of fixed ground-based reference stations to broadcast the difference between the positions indicated by the GPS satellite system and known fixed positions. These stations broadcast the difference between the measured satellite pseudoranges and actual (internally computed) pseudoranges, and receiver stations may correct their pseudoranges by the same amount. The digital correction signal is typically broadcast locally over ground-based transmitters of shorter range.
The United States Coast Guard (USCG) and the Canadian Coast Guard (CCG) each run DGPS systems in the United States and Canada on longwave radio frequencies between 285 kHz and 325 kHz near major waterways and harbors. The USCG's DGPS system has been named NDGPS (Nationwide DGPS) and is now jointly administered by the Coast Guard and the U.S. Department of Transportation’s Federal Highway Administration. It consists of broadcast sites located throughout the inland and coastal portions of the United States including Alaska, Hawaii and Puerto Rico.[1] Other countries have their own DGPS system.

https://en.wikipedia.org/wiki/Differential_GPS


Arduino Uno outputs 8V when pin is set to HIGH

You have a badly calibrated multimeter.

Try it on something where you know what the voltage should be, such as a 9V battery and see what it reads.


I see you are new to Arduino, so let's start:
1) if you say it works you might be using an circuit like this:

which is not all bad but you might find trouble. I explain:

1. When you set pinMode(pin,INPUT); you tell arduino to enable a high-impedance state on that pin: it's equivalent to 100Mohm resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings.
That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).

2. So you end up with something like this:

I would personally put the resistor and the GND wire between the button and the digital pin wire.
I hope I was useful! If you need/want more documentation check those two links out:

https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section

https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.


Why do I get "invalid operands of types 'const char*'" error?

Your first code took a String object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to String objects.

Your new code doesn't have any String objects at all - and you're not allowed to add strings to strings (both lowercase).

It will work if you change your new code to:

lcd.print(String("0")+hours+":"+minutes);

That turns the original string "0" into a String object, and then adds more strings to it.


Use analogRead to measure the voltage on the battery. You might have to use the internal 1.1V reference to get a good reading.

Don't write any blocking code and the processes won't interfere with each other. That means no long for or while loops waiting for something to complete and absolutely no delay.


You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).

#define buttonUPpin = 2;
#define LedPin = 3;
int UpinStatus = LOW;

void setup()
{
    Serial.begin(9600);
    pinMode(buttonUPpin, INPUT_PULLUP);
    pinMode(LedPin, OUTPUT);
    // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

}

void loop()
{
    UpinStatus=digitalRead(buttonUPpin);
    if(LOW==UpinStatus)
    {
       Serial.print('A');
       digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
    }
}


Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.


Limitations of connecting to many Arduinos via Ethernet?

With a lot of devices on the ethernet, you may want to consider a private wire that is dedicated to those devices.  That is, a second ethernet port or a VLAN off a capable switch.

As the number of devices increases, and the number of simultaneous talkers increases, you will start getting contention.  Chances are a modern switch can handle this to some extent, but you were not clear on how much traffic you are planning on sending, or how often each device talks, or if it is centrally coordinated (aka "polled") or just speaking whenever.


How to handle low temperatures using Arduino Uno?

Your Arduino does not have to be in the fridge, just the sensor. You can always choose waterproof sensor like this one to use with the arduino. Then you can always store your arduino outside the fridge. Same goes for the heater. Try to keep the arduino at room temperatures to avoid decreasing its life unnecessarily.

As for an actual answer to the temperature ranges, here is a good answer


How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?

Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.


TinyGPS++ Question about gps.encode(ss.read())

From http://arduiniana.org/libraries/tinygpsplus/
Validity, Update status, and Age
You can examine an object’s value at any time, but unless TinyGPS++ has recently been fed from the GPS, it should not be considered valid and up-to-date. The isValid() method will tell you whether the object contains any valid data and is safe to query.
Similarly, isUpdated() indicates whether the object’s value has been updated (not necessarily changed) since the last time you queried it.
Lastly, if you want to know how stale an object’s data is, call its age() method, which returns the number of milliseconds since its last update. If this returns a value greater than 1500 or so, it may be a sign of a problem like a lost fix.


I think you have 2 problems:

First about the shown sketch: I don't think, that the Baud rates are good. In your HC-05 code (the sender) you are using BTserial.write('1'); without any delay or other code, thus this will run very fast, so the SoftwareSerial interface is almost completely busy. You sending almost at the maximum speed, that you can get with 38400 baud. On the receiving site you are using 9600 baud, which is significantly slower than 38400 baud. How should the HC-06 transmit all data, that it get's, to the Arduino, when you only use 9600 baud, but the data is coming with 38400 baud? That cannot work. You should configure the HC-05 and HC-06 to use the same baudrate, so that this cannot happen. Or - if you really don't want to - you can restrict the overall speed, that you are sending with, by just sending less data per time unit (sending the data slower, but on the same baudrate as before). This will prevent the HC-06 to get flooded by data. (Also there might be a limit on how fast you can send data over the HC-05, but I haven't tested this). All in all it mostly isn't a good idea, to do communication totally without any speed brake. That can get you into troubles, that you mostly don't want to think of.
Secondly: In your comment you wrote, that you tried to change the baudrate, but that gave you garbled data. Since you didn't describe more, we cannot say much about this. But garbled data is a normal symptom for wrong baudrate. So it seems, that you haven't changed the baudrate successfully. I would suggest, that you again look into this and that you try to change the baudrate successfully. It is possible and there are many tutorials and codes on the web, that show how it is done. (When you again have problems with this, you can ask a question about this specific problem, including all the relevant information)


i found it
it is the
temp = register_array[packet->local_start_address + i]; // get the data
in the ccp file
register_array[packet->local_start_address + i]
its pointing to the wrong location... register_array??
supersized no one has noticed this as long as the simple modbus master for adruino
has been used ?
or i have a bad CPP file ?
i have temp corrected this by replacing with
unsigned char construct_F15()
{
    // function 15 coil information is packed LSB first until the first 8 bits are completed
    unsigned char frameSize = 10;
    unsigned char temp;
    frame[6] = 1;
    frame[7] = packet->local_start_address ^ 0XFFFF;
    return frameSize;
}

works (0 = off / 255 = on)
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 0); // 1 thru 8 = off
modbus_construct(&packets[PACKET2], 1, 15, 1, 8, 255); // 1 thru 8 = on


How to avoid odd naming rules for Arduino when writing a library?

Yep, the Arduino IDE kinda sucks eventually. There is no best practise really, as Arduino *.ino files aren't proper c / c++ anyway. I would hope that people who know how to write C++ classes (as opposed to Arduino) would be able to do it outside the IDE.

My suggestion would be to make the *.ino file a test file. That is, it runs a set of functions to check that the library behaves as desired. It could also include example code, so people who use the library know how to include it in their programs.

All that being said, time to fly Penguin...  Ditch the Arduino IDE and go with embedXcode or some other third party IDE template :P

(I just wanted to put a pic of a penguin)


You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:

// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
    switch (pin) {
        case 9:
            OCR1A = value;
            break;
        case 10:
            OCR1B = value;
            break;
        default:
            // no other pin will work
            break;
    }
}

void setup()
{
    // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;           // undo the configuration done by...
    TCCR1B = 0;           // ...the Arduino core library
    TCNT1  = 0;           // reset timer
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
    ICR1   = 320;         // TOP = 320

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT);
    pinMode(10, OUTPUT);
}

void loop()
{
    // Just an example:
    analogWrite25k( 9, 110);
    analogWrite25k(10, 210);
    for (;;) ;  // infinite loop
}

Writing a value of 0 with analogWrite25k() means the pin will be
always LOW, whereas 320 means always HIGH. The regular analogWrite()
should almost work, but it will interpret 255 the same as 320 (i.e.
always HIGH).

This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.


I2C communication between Arduino Uno and Nodemcu32-s (ESP32)

I'm working on something similar at the moment. Not a complete answer put some thoughts:

Have you considered that the Uno is a 5v board and the ESP32 is 3.3v? You may need a signal level shifter (there are many to chose from) something like Pololu-2595 which is breadboard friendly.

There's a good ESP32 I2C explanation at Random Nerd Tutorials.


Sometimes boards can glitch depending on wear and tear or on how well they have been manufactured. Personally I always buy boards direct from the Arduino store and  I have never had this issue. One thing that could help is placing a 0.1 uF capacitor between the +5V pin and ground and another between AVcc and ground. There will be some on the PCB already but this can help in some cases. Another thing that can help is pressing the reset buttom just after pressing upload on your PC.
Unfortunately, when out of sync errors occur it can be heavily luck based as to what works and how long it takes. Hopefully one of these tricks will work! But like you say, if other boards are working fine then it could just be bricked


I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its logarithmic perception.


analogRead-ing Potentiometer Values in void setup()

You presumably know that:  The easiest and usual way to read a potentiometer is to connect the "track" between V_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.

The use of analogRead() is valid in setup.

However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

eg

void setup()
{

...
boolean initialised = false ;
...
}

void loop()
{
if (initialised == false) {
// initialise speedo
//  ....
   initialised = true;
}

...

} // end of loop()

}


Schematic: 1 Button and 1 Potentiometer Sketch

I will not write the code for you (as explained in my comment to your duplicate question), though I will point out some problems in your code and give hints how to solve them.
Mainly your program structure isn't correct. The first hint is to not look at real C/C++ code in the first step. Write down step by step, what the program should do. Here I'm doing this for you, as I understand your description:
Initialize everything (setup)
loop
  if button was pressed
    loop 10 times
      take analog reading and add it to the sum
      delay 10ms (for example) to keep the reading regularly spaced
    calculate average by dividing the sum of values through 10
    print average over serial

And from this pseudo code you would start to write the corresponding C/C++ code for the Arduino. For the "Initialize everything" you can reuse your current setup() function (assuming you already have a pulldown resistor on your button pin). What I wrote as "loop" would just be the loop() function. The "if button was pressed" will be a if(digitalRead(button_pin)). The 10 analog readings could be written with a for loop, adding the analog values to a local variable and delaying a bit to make the readings regularly spaced in a specific distance (you can change that to your liking. You could also delay way shorter with delayMicroseconds()).
And now some notes for your original code, that you should keep in mind for writing the new one:

You have the lines (I omitted some lines, that are irrelevant to my point here):
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
      statoPresenteBottone = LOW;
  }

Follow the logic here: We read the button state and save it in a variable. Then we loop while this variable is HIGH. But already in the first iteration of that loop we are setting the variable to LOW. That means the while loop will not loop. It will only run once. Also: If you want to check if the button is still HIGH, you actually need to read it. The variable statoPresenteBottone will not change automatically, when you press or release the button. You need to actually read the button pin with digitalRead(BUTTON). The variable is just a small space in memory, where you store data (like the last read state of the button). It is not connected to any hardware. That has to be done by the software.

You use an array for the analog values, though in this case you don't need that. For calculating the average it is enough to just add up the values and then divide by the number of measurements. The array is just not needed. And when removing the array, the variable counter and the complete array reset code becomes unnecessary and can be removed.

We cannot see your circuit, so please note, that you need a pulldown resistor on the pin, that you connected to the button. Otherwise you would have a floating pin, resulting in a randomly and often rapidly changing pin state. Often the people instead use the internal pullup resistor of the Arduino, by using pinMode(pin, INPUT_PULLUP) and connecting the button to ground instead of Vcc. Though that reverses the logic (LOW then means the button is pressed, HIGH means it is not pressed). It's up to you, want you want to use.

In the comments others pointed out button debouncing. That is an important issue, though for the above pseudocode structure that is not that important I think (this depends on how exactly you want the button to behave). So you should keep debouncing in mind. There are many tutorials about that online. I often suggest using the Bounce2 library, since it already handles the button debouncing for you and is fairly easy to use. Though - as said - I don't think that you really need it in this case.


I found the way:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
RTC_DS1307 RTC;
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);
File main_folder; // initialize folder for saving
File dataFile; // initialize sd file
const int chipSelect = 10; // CS pin on sd card module
int prev_file_indx = 0; // used for file naming
String fileName = "000";
char timestamp[30];

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup ()
{
  Serial.begin (115200);
  mySerial.begin (115200);
  Wire.begin();
  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
      return;
    }

    main_folder = SD.open("/");
    fileName = sd_saver(main_folder);
 // end of setup
    delay(1500);
    dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println(dataFile);
    Serial.println("Writing Headers...");
    dataFile.println("FA,  Zeit");
    dataFile.close(); // close the file
    Serial.println("File closed, Headers written");
  }
 }

void process_data (const char * data)
// here to process incoming serial data after a terminator received
{ delay(500);
    SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
     dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println("Writing to file...");
    dataFile.print (data);
    dataFile.print(",");
    dataFile.println (timestamp);
    Serial.println (data);
    Serial.println (timestamp);
    Serial.println("Done.");
    dataFile.close();
  } else {
    Serial.println("error opening test.txt");
    delay(1000);
  }

}

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of switch

} // end of processIncomingByte

void loop() {
  delay(2000);

  // if serial data available, process it
  while (mySerial.available () > 0)
  processIncomingByte (mySerial.read ());
  mySerial.write(processIncomingByte);
  delay(1000);

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

String sd_saver(File dir){
  while(true){
    // iterate all files to ensure no overwrites
    File entry = dir.openNextFile();
    if (!entry){
      break;
    }
    // naming routine
    String entry_name = entry.name();
    if ((entry_name.substring(4,7)).toInt()>=prev_file_indx){
      prev_file_indx = (entry_name.substring(4,7)).toInt()+1;
      if (prev_file_indx>=100){
        fileName = String(prev_file_indx);
      } else if (prev_file_indx>=10){
        fileName = "0"+String(prev_file_indx);
      } else{
        fileName = "00"+String(prev_file_indx);
      }
    }
    entry.close();
  }
  return fileName;
}


Amps tell you how much current you can draw from the power supply, or "how much it can do".

You can hook up 3Amps power supply to a device that draws 1Amp and it will work ok, still having 2 amps of reserve.

You must pay attention to power supply voltage and keep it in specified range.

Arduino Mega has recommended input voltage of 7-12V, so you must deliver at least 7V. There are plenty of cheap wall power supplies with voltage regulation from 1.5V to 12V.

How much current it will draw depends on your application, but I doubt that you can suck more than 0,5-1A in a typical application.


It sounds like you have not allowed the flex sensor to slide through a sheath attached to the back of the hand.  Consider attaching a sheath to the back of the glove the width of the flex sensor.  It's length should be equal to or greater than the flex sensor when the glove is worn and the hand is fully dorsiflexed.  Anchor only the wired end of the flex sensor to the glove.  If there is still not enough room for the sensor when the hand is fully dorsiflexed, revers the sensor position and anchor the wired end to the back of he hand.  Allow the sensor to travel beyond the cuff of the glove if necessary.


#include  Error with WiFiClientSecureBearSSL.h

You installed the latest git version of the ESP8266WiFi library into your libraries folder and this version is not compatible with the 2.5.2 version of the esp82666 Arduino core.

The ESP8266WiFi library is part of the esp8266 boards package. It should not be installed separately. Delete the library from your libraries folder.


Why there are (escapes) " ---" used in the code? Why can't we use the string normally?

Because escapes are required.
In C " means 'The start or end of a string', but \" means 'A double-quote character'.
There has to be a way to distinguish a double-quote character from a string delimiter so the compiler knows which is which. Without escapes your string would look like:
char json[] = "{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}";

and the compiler would find the end of the string at the second ", and then a load of junk before it finds the end-of-statement ; character. It can't work out what sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}" is supposed to be, since it isn't in the string, but after it.


Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".

Here is its datasheet:

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.

https://github.com/NicoHood/MSGEQ7

Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.

https://www.youtube.com/watch?v=InrQvtUuS2w


Not so tough it is possible just try the bellow code :)

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  CheckPossibility();
  }

 CheckPossibility(){
 int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
      Serial.println("The network you are looking for is available");
      }
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
 // delay(5000);
}


Buzzing on computer speakers when LEDs are on

If this is the same project you described in this question(readers: "112 WS2811s in series" causing interference), your external speaker may not be filtered very well against energy radiated by nearby un-shielded wiring. Try a pair of headphones in place of the speaker - does it also buzz? If not, the speaker (system) is probably picking up the interference. If so, the pickup is probably within or near the Mac mini.

You could try a few simple solutions (or at least tests that might narrow the problem):

shielded audio cable from the Mac mini to the speaker;
shielding the speaker enclosure and grounding the shield;
shielding the connections to the LED string (obviously shielding the LED string itself is likely to be aesthetically undesirable);
separating the speaker from the LED strip by more distance;
powering the mini from batteries - at least long enough to learn whether the power wiring might be involved.


Difference between print() and println()

An easy way to see the difference is using Serial.print();/Serial.println();.

print();

will print out whatever you input wherever the cursor currently is. For example:

Serial.print("Test");
Serial.print("Words");

This will print:

TestWords_

The underscore marks where the cursor is (and therefore where the next print command will start). In contrast, the code:

Serial.println("Test");
Serial.println("Words");

will print the following:

Test
Words
_

You can also print multiple statements and then follow with println like so (note the space at the end/beginning of the strings):

Serial.print("These ");
Serial.print("Test");
Serial.println(" Words.");

to get the following output:

These Test Words.
_

You can also use println(); to add a newline character in general. If you would print a variable that doesn't return a newline character, println(); can be used for formatting. Example:

int x = 50;
Serial.print(x);
Serial.println();

This will print:

50
_

Finally, you can add in special characters like a tab \t inside your quotes for formatting. Example:

Serial.println("Test\tTest")

This will return:

Test    Test
_


Rotary encoder on Uno and interrupts issue

When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.


Use potentiometer to control motor's speed

Ah, now I see. Your confusion in this case is perfectly understandable. They threw a couple of capacitors into the circuit without explaining why they were added in the first place. In order to understand why capacitors were added you need to go a little deeper into electronics theory, specifically capacitance and inductance, what they are and how they work.

Inductance is, to put it succinctly, resistance (not related to the resistance in resistors, measured in ohms) to change in current by sacrificing or absorbing voltage. If current is 0, then inductance will try to keep it at 0, if at 1A then it will try to keep it at 1A, and so on. Inductance is caused by the magnetic fields generated by electricity flowing through a conductor, and hence every conductor exhibits some measure of inductance. (Coils have much higher inductance though, since the magnetic fields of the loops reinforce each other. And a "core" material such as ferrite or iron intensifies the magnetic field.)

Now, this isn't a large problem if your conductors are short, but as they get longer their inductance can cause power issues. Sudden power demand increases are unable to be accommodated because the supply can't put the increased current through the inductance quickly enough. This is where capacitance comes in.

Capacitance is resistance to change in voltage by sacrificing or absorbing current. When something tries to reduce the voltage either through power consumption or because of high-speed switching, capacitance holds the voltage as close to constant as it can by pulling or dumping electricity out of or into the circuit. Capacitance is caused by charges between two conductors attracting each other through a non-conductive material.

So what happens is that a circuit needs bursts of power to work, and if the wires connecting the supply to the circuit have too much inductance then the circuit will be starved of power. We balance this by placing a capacitance close to the circuit so that it can supply power to the circuit for the short time while the supply is busy overcoming the inductance of the wires.

The servo, being a mechanical device, needs a decent amount of power. We put a bulk capacitor near it on the supply lines to help provide this power. The analog input connected to the potentiometer needs much, much less power, so the inductance there isn't a problem and we forgo the capacitor there.


How to connect this motor driver board to Arduino to drive bidirectional motor?

I guess you have used DC Motor for your earlier cases? Or Step Motor with a logic on the stepper controllers?

Here you have two H Bridges which drives one Step Motor. So as I understand it, you have two PWM Inputs, one for each output channel to the coil windings of the stepper motor. Like an encoder signal you can set the direction with setting one pwm before the other. So the step motor is controlled via unipolar stepping.

For further help you need to say which motor you want to use with this card. But first I would look at the different stepping modes (unipolar and the two bipolar and maybe microstepping).

Greets


Eventually as reported here, it worked using this pinout:

VCC --> 3.3V
GND --> GND
SCK --> A5
SDI --> A4

And this code:

#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");

    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
    dig_H6 = data[31];                                   // Fix 2014/04/06
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;

    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);
}

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.

#include <Wire.h>

#define BME280_ADDRESS 0x76
unsigned long int temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;

void setup()
{
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off
    uint8_t spi3w_en = 0;           //3-wire SPI Disable

    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

    Serial.begin(9600);
    Wire.begin();

    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();                    //
}

void loop()
{
    double temp_act = 0.0, press_act = 0.0;
    signed long int temp_cal;
    unsigned long int press_cal;

    readData();

    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.println(press_act);
    delay(1000);
}
void readTrim()
{
    uint8_t data[32],i=0;                      // Fix 2014/04/06
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }

    Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
    Wire.write(0xA1);                          // Add 2014/04/06
    Wire.endTransmission();                    // Add 2014/04/06
    Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
    data[i] = Wire.read();                     // Add 2014/04/06
    i++;                                       // Add 2014/04/06

    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];

}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();
}

void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}


Make newArray be a pointer to whichever array you wish to work with.  For example:

int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int *newArray = myArray2;

// ... work with selected array, via newArray[] subscripting

Note, you may need to set an array-length variable at the same time as choosing the array.

For example:

int *newArray = myArray2;
int newSize = sizeof(myArray2)/sizeof myArray2[0];

// ... work with selected array

newArray = myArray3;
newSize = sizeof(myArray3)/sizeof myArray3[0];
// ... work with selected array

Alternately, add an array-end marker at the end of each array (eg, a negative number), or more elegantly, make all the arrays the same length.

If you want to make a new copy of the original array, such that modifying the new array won't change the old, use (eg) memcpy().  For example:

int newArray[7];
...
memcpy(newArray, myArray2, sizeof(myArray2));

Note that memcpy()'s size argument is given in bytes.  Also, if you need to declare memcpy() [I don't recall whether it's automatically declared in the Arduino environment], add #include <string.h> up front.


Each will only draw as much current as they normally would from a 5 volt supply. If you had a 5 volt 100 amp supply they still would not draw any more.

The amount of excess current a power supply can deliver doesn't change what the load will take from that supply.

For example, if you had a 5 volt supply with a 1 ohm resistor as a load the current would be 5 amps. 5 volts / 1 ohm = 5 amps. And if you had a 5 volt 10 amp supply the current would still be 5 amps. Same with a 20 amp supply. As long as the voltage is the same, going up in current capacity is safe.

(LEDs are not resistors but with this application it is much the same)

When you do wire up the LED strips make sure you are using thick enough wires.