(1) A simple method
BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.
Next best in this context is my "better" method in 2. below.
BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.
You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.
Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.

If the current is ever higher than the rated maximum then battery destruction may occur.

If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.

Worst case a badly treated battery can turn into a flaming inferno in seconds.
A usably OK result can be gained by:
(1) Calculate Imax = same mA as battery mAh capacity.
LOWER is OK. Higher is not.
eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.
(2) Connect a ONE OHM resistor in USB to battery line.
(3) Connect discharged LiPo battery to USB port via 1 Ohm.
(4) Measure voltage across the resistor.  The voltage will be 0.001 Volt for every mA that flows. eg
1000 mA gives 1.000 Volt
789 mA gives 0.789 V.
1234 mA gives 1.234 V. etc.
If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.
(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.
BE SURE that the voltage that you read with the Arduino matches what a quality meter says.
When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.
Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).
For 10 bit ADC = 1024 counts total (0-1023) then
for 5V reference 4.1V count = 4.1/5 x 1023
= 838 counts.
Using 830 counts to start with is safer.
When battery is at the upper charge limit,  and before removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.
Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.
The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.
._______________________________
(2) A better method:
LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term "LiPO" from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,
LiPo batteries have 4 main charge areas.

Under about 2V = dangerously dead. Discard

2V to about 3V = under voltage - charge very slowly

3V to 4.2V = charge at CC  = Constant Current.

On reaching 4.2V charge at CV = Constant Voltage until current reduces "automatically" (under battery chemistry control)  to about 1/4 x max rate.

Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.
Max voltage MUST NOT exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.
The battery mAh rating is known as "C".
If C = 1200 then a cahrage rate of 1200 mA = C/1,
a charge rate of 300 mA = C/4,
a charge rate of 12 mA = C/100 etc
An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is

Determine max charge rate = C  = Imax = same mA as battery has mAh capacity.

If Vbattery is < 3V, charge at C/20 or less until Vbattery reaches 3V.
If Vbattery never reaches 3V it is dead.

When V_battery = >= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)

Finished!.

Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.

A more usual method that is only slightly harder is.

Monitor charge current.

Charge as above until Vbat = 4.2V.

While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.

When  Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.

Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.

.______________________________
Battery University:
Charging Lithium Ion & LiPo
Increasing lifetime
Index
.______________________
Q&A

Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.

Read the above material and the battery university pages.
4.1 V ABSOLUTE MAXIMUM is what I recommended.

Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the average voltage across the discharge cycle.

When fully charged they are at about 4.2 V (or 4.1 V if you take my advice - which you should :-).

As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.

So 4.1 V ABSOLUTE MAXIMUM is good
MEASURED WHILE CHARGING and
AT the battery terminals or very close to them.
ie no long leads or resistors or connectors.
If using an Arduino to measure battery voltage,  connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.
So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.


You should use

if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of

if (ledPin4 == HIGH && (button_press_9()))


Your code does not work because in fact error statement reads the value of temperature and humidity sensor.
You set the humidity and temperature variables to 0. If statement compares this variables to 70, before actually reading sensor data.
I haven't tested but this should work.
#include <SimpleDHT.h>

int pinDHT11 = 2;
SimpleDHT11 dht11;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
}

void loop()
{
    // start working...
    Serial.println("=================================");
    Serial.println("Sample DHT11...");

    // read without samples.
    byte temperature = 0;
    byte humidity = 0;

    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL))
        != SimpleDHTErrSuccess)
    {
        Serial.print("Read DHT11 failed, err=");
        Serial.println(err);
        delay(1000);
        return;
    }

    Serial.print("Sample OK: ");
    Serial.print((int)temperature);
    Serial.print(" *C, ");
    Serial.print((int)humidity);
    Serial.println(" H");

    if (humidity > 70 )
    {
        Serial.println("Humidity is above 70%");
        digitalWrite(9, HIGH);
    }
    else
    {
        Serial.println("Humidity is below 70%");
    }
    // DHT11 sampling rate is 1HZ.
    delay(1500);
}


Arduino GSM shield GSM_READY not ready ever

You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement

What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "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."


(META: This question has been answered in the comment section of the question itself. (And I'm also unable to comment to say that he should answer his own question...) That's why I'm putting this answer here.)

You might want to look into the basics of SPI, the clock will only oscillate when there is an actual data transaction in progress. (This will prevent desynchronisation by a bit. And will make both sides know when data is being send. Often along with a SS)
You can check this by continiously sending something in your code and then probe the clock pin with an ossciloscope.

You might want to accept this as an answer, so that nobody it's clear this question is already answered.


What is the equivalent of this old SPI code using the current SPI library?

The default is:

Mode 0
MSBFIRST

Not sure on the default speed. But:

setClockDivider() sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.

setClockDivider(2) would be the same as using F_CPU/2 as a speed.


You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff".  I don't know what the "stuff" is, but I can see and decode your data easily enough.

I suspect you transmitted the data using .println(...).  That will send an ASCII representation of the data.

So to take the line: -196.88<CR><LF>, if we find the ASCII values and represent them as hexadecimal we have:

  2D,31,39,36,2E,38,38,D,A

Which I am sure you can find in one of those lines - maybe this one:

  0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,2D,31,39,36,2E,38,38,D,A,3B

So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.


How to fix: Invalid conversion from 'const char*' to 'char*' [-fpermissive]

This begin() method expects a modifiable character array as its first argument. That's what you should provide:

char ssid[]           = "YOUR_SSID";      // this is changed
const char* password  = "YOUR_PASSWORD";  // this is fine
[...]
WiFi.begin(ssid, password);


Adafruit Flora V2 use onboard and external NeoPixels

The #define is just letting you use a nice name for the numeric value of the pin.  If you want to use two different pins, you use two different names.

So you might define them at the beginning something like:

#define BOARDLED 8
#define STRIPLED 6

Then you create a NeoPixel object that uses that pin.  In your case, you'll do this twice.

Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

And then you call the one you want to set/modify/show/etc.

strip.show();
flora_led.show();


Can't upload any code to my Arduino board

You basically have 2 questions here.

1: Why is my Uno not uploading code.

2: How does back EMF effect a microcontroller. We'll address 2 first

When a relay module is activated, it energizes a coil to close a switch. This coil is an inductor, which is an energy storage device. When the signal to the relay tells it to turn off, your trying to de-energize the coil. Whereas before you let current run through the coil to establish a magnetic field, now you cut the current supply and let the magnetic field die out.
The problem this creates is back EMF. As Faraday's law will tell us, a change in a magnetic field causes a voltage (an EMF) in a coil. When we were charging the circuit, this was the voltage applied to the coil. When we discharge the inductor, this voltage is back EMF, and is in the opposite direction as charging voltage.

How does this affect your arduino? Well, it can be anything ranging from harmless to catastrophic. It may simply reset your arduino (as one I was working with did on a past project [where an occiliscope showed back EMF spikes in excess of -30V]) or it might straight-up burn the ATMega328p that acts as the Uno's brain. Or it might take out the voltage regulator, or cause a host of other problems.

The simplest fix for back EMF is to put a diode in parallel with the relay with cathode to your positive terminal and anode to your negetive terminal. This creates a short for the relay's coil to discharge through. Some better solutions (especially for sensitive digital equiptment) involve entirely isolating the relay's power supply form the rest of your circuit with an optoisolator.

Problem 1: Assuming that these problems were related to the use of a relay without the proper safeguards, you might try a few things to verify your chip is still alive. If  you have a second arduino you might try using it to build an ISP, which will allow you to both reburn the bootloader and upload sketches independently of the uno's onboard usb com port programmer. If that works but the onboard programmer still does not, you may need to reflash the programmer (which I've read can also be done with an ISP, though I've never tried it.)

Hope that helps!


Mac shortcut for next window - IDE 1.8.7 problem

In MacOS 10.14 and Arduino IDE 1.6.12, cmd` cycles through 5+ IDE windows properly, for me.

Update:

  When you upgrade to Arduino 1.8.7,

I won't be. I've tried a couple of its point releases and have given up on it because its launch performance is so p...-poor. Maybe 1.9 will finally fix it.

Sloeber/Eclipse is my serious code-crunching IDE. I keep the A-IDE around for reference and for quick knock-off experiments because it's quick to launch.

Update 2:

The OP asked me to note that he

  found that  Cmd ⌘   Shift   `  cycles
  through all windows (maybe in reverse).

Update 3:

  In older IDE the reverse cycling with Shift doesn't work?

It works in both directions for me (shifted/unshifted).


Integrating an analog signal using Arduino Due

I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:

FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a ; otherwise it doesn't know where one statement finishes and the next one begins.

area(1) = 0;
(and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.

I think you meant to be using arrays of float values.  Arrays are denoted by [ and ] not ( and ).  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are zero based (i.e., they start at index 0 not index 1).

For example, area could be defined as:

float area[1024]; // 1024 floating point values in an array
// ...
area[0] = 0;

Next:

Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace (...) with [...] for indices to arrays, it still makes no sense.  You're calculating a single value (FreqIn3 = FreqIn1 - FreqIn2) then using that as an array (FreqIn3[n]) which makes absolutely no sense to me at all.  Then you're using another value t which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (t[2]).  Which is it - arrays or single values? And how do you increment an entire array?

Now the incrementing:

for (n = 1; n = t; t++)

n starts at the value 1.  While n is assigned the value t, increment t.  Now, does that sound logical?  And what is t? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so t will never equal 0 and consequently the result of assigning t to n will never be 0, so the loop will never end.

I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.


I looked into the source of the AccelStepper library here, which may be your library or one similar to it. The function runSpeedToPosition() does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to millis()), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.

Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:

void PatternToBeLooped_For_Cycle1()
{
  int count = 0;
  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
}

Note: With this change the function PatternToBeLooped_For_Cycle1() blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the millis() function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.


serial communication between several arduinos to pc

Not directly, no.  A PC's serial port - either a "real" one or a USB one, can only communicate with one device.

The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port.  Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.

Another option, one that is more widely used when you want to communicate with a lot of slave devices from one master device is to use a multidrop network.  RS-485 is the most popular of these.  It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.

RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.

You can read more about RS-485 here: https://en.wikipedia.org/wiki/RS-485


Host a webserver on esp32d that has a hyperlink that triggers an ardiuno song through a buzzer

This is a partial answer. I assume you already know how to build a Web
server on you ESP32, and how to react to client requests. If not, there
are tutorials available on the Internet. Here I will specifically
discuss the issue of the hyperlink.
You wrote:
Click Here To Trigger The Rick Roll!/a>

Not only the closing tag is incorrect (it should be ), but such a
link is likely not what you want. The semantics of an hyperlink is “go
fetch that resource and display it here, replacing the current page”.
Unless you do have a displayable resource (Web page, image...) on your
server actually named “trigger”, you do not want an hyperlink. You want
a clickable item that may look like an hyperlink and, when clicked,
triggers a request to the server, but without replacing the current
page.
So I would start by replacing the link by a generic container:

Click Here To Trigger The Rick Roll!

Then, style it like a link. I don't quite like the underlining, but you
can add it if you wish:
#trigger {
  color: blue;
  cursor: pointer;
}

Then, within a


would it be acceptable to use a resistor to decrease the voltage

I don't see any big problem with using a voltage divider for chip select.

  What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's

At 3.3V you can only run at 13 MHz or less (so in practice, 8 MHz, unless you want to do a lot of fiddling around). This may or may not matter to you. At a lower voltage it uses less power which can be a plus, and you don't need to worry about level converters.

  and just using a hex converter on SDA/SCL for the I2C communication to the master?

Do you mean a level converter?


Compilation error when trying to give pointer to a function to another function

Pointer to a member function is a painful corner of C++ until C++11. This is why when you try to pass an instance method pointer to Wire.onReceive (without the static keyword), you will get an error similar to:

error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&PiCom::onReceiveCallback'

Well, you can't argue with the C++ ISO standard... changing the function to a static one (with external linkage, as they say) is indeed a workaround, as you have found out.
For this workaround to compile properly you just need to omit the static keyword from your definition (where it is implemented), and leave your declaration (in the header file) as is:

PiCom.h:

...
static void onReceiveCallback(int numbytes);
...

PiCom.cpp:

void PiCom::onReceiveCallback(int numbytes)
{
    ...
}

By doing this you can pass it to Wire.onReceive without any problem, from the PiCom constructor, as follows:

PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    ...
    Wire.onReceive(&PiCom::onReceiveCallback);
    ...
}


My page about Arduino Uno output to VGA monitor has a lot of theory on it, including a sketch that produces colour bars like this:

Code

To produce a single colour is slightly simpler, this sketch did it for me:

/*
 VGA colour video generation

 Author:   Nick Gammon
 Date:     22nd April 2012
 Version:  1.0

 Connections:

 D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
 D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
 D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
 D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
 D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

 Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

*/

#include <TimerHelpers.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>

const byte hSyncPin = 3;     // <------- HSYNC

const byte redPin = 4;       // <------- Red pixel data
const byte greenPin = 5;     // <------- Green pixel data
const byte bluePin = 6;      // <------- Blue pixel data

const byte vSyncPin = 10;    // <------- VSYNC

const int horizontalBytes = 60;  // 480 pixels wide
const int verticalPixels = 480;  // 480 pixels high

// Timer 1 - Vertical sync

// output    OC1B   pin 16  (D10) <------- VSYNC

//   Period: 16.64 ms (60 Hz)
//      1/60 * 1e6 = 16666.66 µs
//   Pulse for 64 µs  (2 x HSync width of 32 µs)
//    Sync pulse: 2 lines
//    Back porch: 33 lines
//    Active video: 480 lines
//    Front porch: 10 lines
//       Total: 525 lines

// Timer 2 - Horizontal sync

// output    OC2B   pin 5  (D3)   <------- HSYNC

//   Period: 32 µs (31.25 kHz)
//      (1/60) / 525 * 1e6 = 31.74 µs
//   Pulse for 4 µs (96 times 39.68 ns)
//    Sync pulse: 96 pixels
//    Back porch: 48 pixels
//    Active video: 640 pixels
//    Front porch: 16 pixels
//       Total: 800 pixels

// Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
//  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

// However in practice, it we can only pump out pixels at 375 ns each because it
//  takes 6 clock cycles to read one in from RAM and send it out the port.

const byte verticalBackPorchLines = 35;  // includes sync pulse?
const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

volatile int vLine;
volatile byte backPorchLinesToGo;

#define nop asm volatile ("nop\n\t")

// ISR: Vsync pulse
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

// ISR: Hsync pulse ... this interrupt merely wakes us up
EMPTY_INTERRUPT  (TIMER2_OVF_vect)

void setup()
  {

  // disable Timer 0
  TIMSK0 = 0;  // no interrupts on Timer 0
  OCR0A = 0;   // and turn it off
  OCR0B = 0;

  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
  OCR1B = 0;    // 64 / 64 µs = 1 (less one)
  TIFR1 = bit (TOV1);   // clear overflow flag
  TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
  TIFR2 = bit (TOV2);   // clear overflow flag
  TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

  // prepare to sleep between horizontal sync pulses
  set_sleep_mode (SLEEP_MODE_IDLE);

  // pins for outputting the colour information
  pinMode (redPin, OUTPUT);
  pinMode (greenPin, OUTPUT);
  pinMode (bluePin, OUTPUT);

}  // end of setup

// draw a single scan line
void doOneScanLine ()
  {

  // after vsync we do the back porch
  if (backPorchLinesToGo)
    {
    backPorchLinesToGo--;
    return;
    }  // end still doing back porch

  // if all lines done, do the front porch
  if (vLine >= verticalPixels)
    return;

  PORTD = bit (5) | bit (6);  // cyan (green + blue)
  delayMicroseconds (27);     // one scan line

  PORTD = 0;  // back to black
  // finished this line
  vLine++;

  }  // end of doOneScanLine

void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

As @ChrisStratton suggested, the hardware timers are a big help.

Wiring

I wired it up like this:

TimerHelpers library

The TimerHelpers.h library is described on my timers page, a copy is below:

/*
 Timer Helpers library.

Devised and written by Nick Gammon.
Date: 21 March 2012
Version: 1.0

Licence: Released for public use.

See: http://www.gammon.com.au/forum/?id=11504

 Example:

 // set up Timer 1
 TCNT1 = 0;         // reset counter
 OCR1A =  999;       // compare A register value (1000 * clock speed)

 // Mode 4: CTC, top = OCR1A
 Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

 TIFR1 |= bit (OCF1A);    // clear interrupt flag
 TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

*/

#ifndef _TimerHelpers_h
#define _TimerHelpers_h

#include <Arduino.h>

/* ---------------------------------------------------------------
 Timer 0 setup
 --------------------------------------------------------------- */

namespace Timer0
{
  // TCCR0A, TCCR0B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
  { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM02) },  // 4: Reserved
  { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
  {               bit (WGM01), bit (WGM02) },  // 6: Reserved
  { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

  };  // end of Timer0::Modes

  // Activation
  // Note: T0 is pin 6, Arduino port: D4
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 12, Arduino port: D6
    TOGGLE_A_ON_COMPARE  = bit (COM0A0),
    CLEAR_A_ON_COMPARE   = bit (COM0A1),
    SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

    // pin 11, Arduino port: D5
    TOGGLE_B_ON_COMPARE  = bit (COM0B0),
    CLEAR_B_ON_COMPARE   = bit (COM0B1),
    SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR0A = 0;
  TCCR0B = 0;

  TCCR0A |= (Modes [mode] [0]) | port;
  TCCR0B |= (Modes [mode] [1]) | clock;
  }  // end of Timer0::setMode

}  // end of namespace Timer0

/* ---------------------------------------------------------------
 Timer 1 setup
 --------------------------------------------------------------- */

namespace Timer1
{
  // TCCR1A, TCCR1B
  const byte Modes [16] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFFFF
  { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
  {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
  { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
  { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
  {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
  { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
  { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
  {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
  { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
  { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
  { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
  {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
  { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

  };  // end of Timer1::Modes

  // Activation
  // Note: T1 is pin 11, Arduino port: D5
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 15, Arduino port: D9
    TOGGLE_A_ON_COMPARE  = bit (COM1A0),
    CLEAR_A_ON_COMPARE   = bit (COM1A1),
    SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

    // pin 16, Arduino port: D10
    TOGGLE_B_ON_COMPARE  = bit (COM1B0),
    CLEAR_B_ON_COMPARE   = bit (COM1B1),
    SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 15)  // sanity check
    return;

  // reset existing flags
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A |= (Modes [mode] [0]) | port;
  TCCR1B |= (Modes [mode] [1]) | clock;
  }  // end of Timer1::setMode

}  // end of namespace Timer1

/* ---------------------------------------------------------------
 Timer 2 setup
 --------------------------------------------------------------- */

namespace Timer2
{
  // TCCR2A, TCCR2B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
  { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM22) },  // 4: Reserved
  { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
  {               bit (WGM21), bit (WGM22) },  // 6: Reserved
  { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

  };  // end of Timer2::Modes

  // Activation
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 17, Arduino port: D11
    TOGGLE_A_ON_COMPARE  = bit (COM2A0),
    CLEAR_A_ON_COMPARE   = bit (COM2A1),
    SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

    // pin 5, Arduino port: D3
    TOGGLE_B_ON_COMPARE  = bit (COM2B0),
    CLEAR_B_ON_COMPARE   = bit (COM2B1),
    SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR2A = 0;
  TCCR2B = 0;
  TimerHelpers.h
  TCCR2A |= (Modes [mode] [0]) | port;
  TCCR2B |= (Modes [mode] [1]) | clock;
  }  // end of Timer2::setMode

}  // end of namespace Timer2

#endif

References

Timers
Interrupts
Arduino Uno output to VGA monitor


Opening .h and .cpp files from folders other than the sketch folder

I don't recommend this

A) Because the arduino editor is pretty bad for serious coding

B) Because you will need to have a header guard on all library code that doesn't have one already (even in .cpp's)

But, if you really have to, the only way I can think of is to make a symbolic link to the library file in the sketch directory. It works, but the file gets compiled twice, so you need those header guards on everything.


Function pointer call results in InstrFetchProhibited (ESP32)

I found the issue. After moving SubscriptionHandler handlers[] = ... out of the setup()-method, the function calls work. Perhaps handlers gets overwritten after leaving the setupfunction scope. Could anyone validate my suspected reason?


Please , explain about MAX30100 using for Arduino to read ADC in format (0-1023)

This device does most of the low-level processing for you. The measurements and processing to compute pulse rate and oxygenation are done on the board. You need an I2C library (the 'wire' library is one), and a MAX30100 library (there appear to be a few of them).
Here is a link to the MAX30100 datasheet which has all of the low-level detail you might ever want to know about how this chip does what it does.
There is at least one tutorial for this device; I found this one that seems to make sense to me as I read it (and I have never used this device). It tells you which MAX30100 library the author used (there are a few) and provides some sample code.
If it were me, I'd follow the tutorial (the one I linked or some other one)
to get something working quickly, and use that knowledge to get your own project going. If you have questions about the device itself, you can find answers in the data sheet.


You have a misconception about the interfaces involved. Actually we have 2 different interfaces here: Bluetooth and Serial (UART). The HC-05 is a Bluetooth Serial bridge.

The Bluetooth interface has a fixed concept of master and slave. Every connection needs to have only 1 single master. This concept applies only to the communication between HC-05 and the smartphone. It has nothing to do with the MCU itself, because the MCU does not do any Bluetooth communication.

The second interface is the Serial (UART) interface between the HC-05 and the MCU. For this interface there is no concept of master/slave, because it is not needed. Either of them can send independently on their corresponding TX pin and can receive on their RX pin.

These are two totally independent and different communication interfaces. The HC-05 just forwards data between the interfaces.


WiFi connection times out if credentials retrieved via serial terminal

The answer was quite simple but of the kind you need some time get find out. The issue was a hiding carriage return.

passw.trim();

Did the trick. String.trim() removes the \r and thus the password gets accepted.


how can I stop my Arduino code after 1 second?

You can use different ways:
Use setup only
Instead of putting code in the loop function,  put it in setup, which is only executed once (use a for loop to send around 1 second.
millis() excluding setup
It is better to use the millis function and compare it against the start of sending; when 1 second is reached, don't send anything or use an infinite while loop.
Use something like:
unsigned long time_start;

void setup()
{
    // Your normal code

    time_start = millis();
}

void setup()
{
    if (millis() - time_start >= 1000)
    {
        while(1) {};
    }

    // your normal code (which should not take many ms,
    // otherwise the above code is not reached.

millis() including saetup (Thanks to Edgar Bonnet):
 void loop()
 {
     if (millis() >= 1000)
     {
        while(1) {};
     }
 }

This will stop exactly after 1 s  after startup (excluding the setup). It will start counting after millis start counting, which is before the setup function.
Actually, in none of the above the Arduino 'stops', it just is doing endlessly nothing (well internally endlessly checking against the true condition which never changes).


Why doesn't Serial.read() read multiple character?

if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there".  Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there two dogs there?".

If you want to read two bytes one approach is to wait until they are available:

  if (Serial.available() >= 2) {


Can an Arduino emulate a USB mass storage device?

The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947


New Microcontroller - programmer is not responding -

I managed to fix the problem by downloading the latest version of the Arduino IDE from their website and works fine now.

I use Linux mint 18 and installed Arduino via apt and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.


Write to file in SD card in wave shield V3

No, you cannot.  The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card.  The only control you have is IO pins that emulate pressing the buttons on an MP3 player.


#include <Arduino.h>

void setup()
 {
  pinMode(13, OUTPUT);
 }
void loop()
{
 digitalWrite(13, HIGH);
 delay(1000);
 digitalWrite(13, LOW);
 delay(1000);
}

The problem with your code is that the delay function works in milliseconds and not seconds . 1sec = 1000ms .


ESP8266 working as station while in AP mode

WiFi.begin() is a function of the ESP8266WiFiSTAClass. It changes the WiFi mode for you to STA or AP+STA based on the current mode.

begin functions are in ESP8266WiFiSTA

enableSTA function is in class ESP8266WiFiGeneric


When a microcontroller or a computer is powered on, it always does something. A program on a computer will return and the OS will run again. On a microcontroller there is no OS to return to, so every microcontroller program has an infinite loop.

The void loop() function of the Arduino framework is such an infinite loop. If you want your LM35 temperature code to be only run once, you can put it into the void setup() function, which is run once before going to loop(). When the loop() function is empty, the Arduino will do nothing after it returned from setup().

Otherwise, if you want to put your code into loop() for whatever reason, you can insert an infinite loop whereever you want it:

while(true);

This loops forever and does nothing. Your temperature code will only be executed on the next reset or power on.


Optocouplers for Arduino DCC decoder - Explain?

That specific chip (the 6N137) uses a more efficient IC detector rather than a simple transistor junction.  It also has an "enable" pin that allows it to be turned on or off.  Consequently it needs a power supply to run it. That all means extra pins.

This design allows for higher speed communication (it's a 10Mbaud chip) with less leakage when compared to a traditional design.

The pin VE (pin 7) needs to be pulled up to make the chip work (the job of R2) and the output is pulled high (it's open drain) by R3.

The optocoupler will be on with one polarity and off with the other. It's as simple as that. The diode D1 protects the LED in the optocoupler from the reverse voltages.


I guess you're seeing some big numbers starting with FFFF...?

What you are seeing is not big numbers - it's misrepresented numbers.

You have an int. That's not a "16-bit number", it's a 15-bit number plus a sign bit.

When you print it the variable is promoted to a long and the sign bit is extended.

That long is then further mapped (cast) into an unsigned long to print it as hexadeximal (there is no negative in the hexadecimal representation on Arduino), and that extended sign bit is seen as a string of F.

For example, the value 0xABCD stored in an int is:

 1 010 1011 1100 1101

I broke off the first bit because that is the sign bit in a signed integer.  The actual decimal value of that is -21555.

Now when that gets cast to a long the sign extension copies the leading sign bit to all the other 16 bits to the left of it, resulting in:

1 111 1111 1111 1111 1010 1011 1100 1101

Because of the way that twos complement works, that string of bits still represents -21555 in decimal.

However, cast it to unsigned long for printing as HEX and you can see how you would end up with some big numbers.  It would give you:

FFFFABCD

So you can see that a 16 bit signed value can end up being printed as 8 hex digits, and all because of the way the print() function in the Arduino API works.

When working with unsigned values you really should be working with an unsigned variable - especially if those unsigned values (0 - 65535) fall outside the range of the signed variable type (-32768 - 32767).  Switch to using uint16_t and you will be able to both store and represent the values correctly.

You might find it useful playing around with this site to learn how different variable types represent and store the data within them as binary.


Simple Speed question - Mapping PWM values

The analogWrite() function takes a value that is between 0 (fully off) and 255 (fully on).

Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

(150 / 255) * 100 = 58.8% on time
(240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive.  Let's call this value "i".  You want an output value, let's call it "o".

The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula.  0-9 is i, remember:

o = i × 10 + 150

If i is 0 then o = 0 × 10 + 150 = 0 + 150 = 150.

If i is 9 then o = 9 × 10 + 150 = 90 + 150 = 240.

As Ignacio mentions, the Arduino API has a map function which is meant to be used for this kind of thing;

o = map(i, 0, 9, 150, 240);

However: the map() function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.


How to measure ultrasonic sensor without pulsein method?

Rather than give you the straight answer in code form, consider this approach. If you learn how the unit works, you will be better prepared to answer questions presented to you.

The background of an ultrasonic distance measuring device is that it sends out a signal, in the form of sound you cannot hear. The device then listens for any echoes (bounce-back) of that pulse within a certain time period. This time period represents the distance range that the device can register. If the electronics are of poor quality, the minimum distance will be larger than if the device was of higher quality, as the amount of time for the pulse to bounce from a close-in object is going to be very short. The electronics have to be very fast to read such a short period of time.

There are libraries for ultrasonic devices such as the one you note, but that's the "easy way" to use it. If you perform appropriate searches, you will find there are references how to use direct timing for this device, which will satisfy the requirement you have been given.

I could perform the search and provide you a link, but that's half the work. Consider to use terms including your device identifier along with code and timing and you may find useful links. It is also very possible that you will find someone's pre-written code using the timing method.


Arduino Uno powers off when circuit plugged in to +5V and GND pins

and have the ... ISet(+resistor) and ground pins connected to the respective pins on the arduino.

What pin on the Arduino?

The ISet resistor should go to +5 V - don't connect it to an Arduino pin (unless you mean the +5 V Arduino pin). See diagram:

I had a 7-segment display working fine on an Arduino via the USB, see photo:

More details here: Interfacing LED displays with the MAX7219 driver


Bluetooth shield/module for file transfer?

I would use an HC-05 (or HC-06 - there seems to be little difference) - You will need to do your own file transfer protocol - for small images, zmodem or xmodem (usual file-over-serial) are probably completely overly complex. You would also need your own app for the phone.

Alternatively, you could use a network (ethernet or wifi) addon on your arduino - I think I read the Arduino Yun has built in ethernet and wifi.http://arduino.cc/en/Tutorial/WebServer has a webserver, this could be adapted to accept uploaded files. You can then use a webbrowser on your phone (or indeed anywhere else!) to send the files. If you want to send from outside your local network, you may need to set up port forwarding on your router (google: port forward) - the port you want to forwards is 80.


Can't able to detect Square wave from 74HC14

The only issue in your code is due to the delay in the pin control. You can solve it this way:

void loop()
{
    static int last_button_state = LOW;
    static unsigned int push_count;
    static unsigned long last_press_time;
    static bool kPinPressed = false;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if(last_button_state == LOW && button_state == HIGH)
    {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        kPinPressed = true;
    }

    if ((kPinPressed) && ((now - last_press_time) >= 20))
    {
        digitalWrite(kPin, LOW);
        kPinPressed = false;
    }

    ...
}

So you turn on the output, then after 20ms you turn it off.

There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?

And most important... What is the time scale? Is it really 10ms/div?


Bizarre transistor behavior and voltage with DC motor in simple circuit

According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.

See link for more details:

  Common Base Configuration   –   has Voltage Gain but no Current Gain.
  Common Emitter Configuration   –   has both Current and Voltage Gain.
  Common Collector Configuration   –   has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.


Arduino port grayed out for Fake Board with CH340

Simplest possible thing would be that you do not have CH340g driver installed and you should try installing it first; These boards use CH340 for usb to serial and they need the driver to be installed; Please give it a try by getting the driver from the following link http://www.wch.cn/download/CH341SER_EXE.html or any other reliable source if there is any problem with the link;

If the board is not recognized even after that, it could be a bad USB port or a bad USB cable or even a board with the CH340 chip dead;


Could I Connect many Arduino Nano boards together?

I want to know if I could connect many Arduino Nano boards together...

Yes, you can read about it here at arduino.cc. Where is says: "...it can be helpful to set up two (or more!) Arduino ... boards to share information with each other..."

  ... i want to know if there is any problem in Communication between
  them using I2C ...

This feature, according to the above link, is expected to work.  (Can you explain the type of problems you are avoiding?)

  ...could [i2c communication] affect processing speed on every board ...

Most likely it will.  Most Arduino platforms do not run operating systems.  So your program is all that is running.  If your program is busy sampling sensors, it will be difficult (not impossible) to concurrently handle i2c communications.


getting started with programming Arduino board in C/embedded c

Not an exhaustive answer, but one step would be to realize what the Arduino IDE does behind the scenes before it gives your source code to avr-gcc.

From https://github.com/arduino/arduino/wiki/build-process#pre-processing

  The Arduino environment performs a few transformations to your sketch
  before passing it to the avr-gcc compiler:

  All .ino files in the sketch folder (shown in the IDE as tabs with no    extension) are concatenated together, starting with the
  file that    matches the folder name followed by the others in
  alphabetical order,    and the .cpp extension is added to the
  filename.
  If not already    present, #include <Arduino.h> is added to the sketch. This header    file (found in the core folder for the
  currently selected board)    includes all the definitions needed for
  the standard Arduino core.
  Prototypes are generated for all function definitions in .ino files    that don't already have prototypes. In some rare cases
  prototype    generation may fail for some functions. To work around
  this, you can    provide your own prototypes for these functions.
  #line directives are added to make warning or error messages reflect the original sketch layout.

  No pre-processing is done to files in a sketch with any extension
  other than .ino. Additionally, .h files in the sketch are not
  automatically #included from the main sketch file. Further, if you
  want to call functions defined in a .c file from a .cpp file (like
  one generated from your sketch), you'll need to wrap its declarations
  in an extern "C" {} block that is defined only inside of C++ files.

This is handy to know if you are trying to port Arduino sketches to pure avr-gcc.

You'll also want to have the header files that define all the various registers specific to the ATMega328p that is the heart of several of the Arduino boards. They can be downloaded as part of Atmel Studio 7, which also includes avr-gcc and the various other toolchain utilities and scripts necessary.

You'll also want the processor's reference manual or datasheet. At this time, the data sheet is available at https://www.microchip.com/wwwproducts/en/ATmega328P in the "Documents" tab. This will lay out everything you ever need to know about how to use the processor, set up peripherals, rules for the order of commands, names of all the registers, etc.


Serial communication from Arduino to ESP8266 NodeMCU works, but from NodeMCU to Arduino isn't working

The problem may stem from Arudino boards being 5v logic pins while ESP boards are 3.3v logic pins.  3.3v high might not be enough for Arduino to see the data.


Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560?

The problem you have is that once the watchdog is turned on it is very hard to turn it off again. There are certain procedures you have to go through to ensure it's turned off.

The default bootloader doesn't turn the bootloader off, and a reset doesn't turn it off either. The watchdog then fires whilst the bootloader is still waiting for communication from the PC thus making it reboot before your sketch has had a chance to run. Hence the change needed in the bootooader.

The only way to clear the watchdog is to remove the power. However as soon as your sketch runs and turns the watchdog back on you are then back at square one.

So you need to upload a new sketch to stop that happening, but that is tricky, since the watchdog keeps resetting and interrupting the bootloader. So what do you do? Well, there's a specific sequence you need to do.

Unplug the mega
Compile the new sketch
Hold the reset button on the mega
Plug in the mega
Press upload
As soon as avrdude starts release the reset button.

That way you have a chance of the bootloader running without your sketch having run first and enabled the watchdog. The bootloader runs just the once when the computer is tryung to upload the sketch, and with luck that will happen instead of your sketch running.


Yes there are lots.  You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226.
This might be useful:
http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS


What programming practices should be adopted while coding sketches for Arduino?

Paul covered the most important points. This answer is intended to be a
complement to his.

First, you should keep in mind the general rules, which are more
important than the more specific ones. The general rule for saving RAM
is: be aware of what you are storing, and do not store anything you do
not really need. The general rule for saving flash is: be aware of what
you are doing, and do not do anything you do not really need.

Now, a few specific tips:

Use the const qualifier for declaring constants (e.g.
const int ledPin = 13;). The compiler will optimize-out the storage of
the constant and use immediate addressing instead.

Use PROGMEM for arrays of constants.

Whenever possible, use static memory (globals and static locals)
rather than heap allocation (malloc() and new). This will prevent
memory fragmentation and make the memory usage more predictable (only
the stack holds dynamic memory): you know at compile time, rather than
run time, whether you are low in RAM.

For the same reason, prefer C strings (char *) over String objects.

Use the C99 types int8_t and uint8_t whenever 8 bits are enough for
your integer variables.

Use the static qualifier for functions that will be used only in the
same source file, especially for functions that are called only from one
place. This gives the compiler more optimization opportunities.

If you need to optimize,
use avr-nm to know what is
consuming your precious RAM.


How to convert string to byte array on arduino

Well, the C string is already byte array.

If you mean Arduino's String class, then it has c_str() method.

Both needs reinterpret cast to const byte pointer:

byte const* byteArray = reinterpret_cast<byte const*>(yourString.c_str());


I want 2 output pins to working alternately

You can set pin 10 to run in “inverted PWM” mode, and leave
pin 9 in the default non-inverted mode. Pin 9 is the “OC1A”
pin of the AVR microcontroller (output compare of Timer 1,
channel A), whereas pin 10 is OC1B (channel B of the same
timer). Inverting the PWM mode of channel B is a matter of changing
a single bit in one of the control registers of Timer 1:
TCCR1A |= _BV(COM1B0);

You can do this once in setup(), the setting should persist. Then just
analogWrite() the same value to both pins. For some background on how
all this works, see the datasheet of the ATmega328P
microcontroller (the MCU at the hearth of your Uno),
especially section 16 “16-bit Timer/Counter1 with PWM” and table
16-3 “Compare Output Mode, Phase Correct and Phase and Frequency Correct
PWM”.


The nastiest part in what you describe is likely to be the debouncing on the button, rather than the serial communication.

One easy way out is to use some form of bounceless implementation, like an optical coupler. Another is to use HW debouncing, like the MAX 6816 family.

Then you can use a loop where you alternate between serial communications and checks for the status of the buttons.

Or you can rely on interrupts for the buttons, but it's more complex and might be overkill.


ATTiny85, how to fix overwritten clock pins?

Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.


Which Barcode Scanner to be used with arduino in India

Most barcode scanners behave just like a regular keyboard.

Try getting one with a PS2 port. You can pretty easily interface a PS2 keyboard to an Arduino. There are already libraries for it.


Can the servo pulse width range be changed?

The Servo Attach method has two forms,

servo.attach(pin)
servo.attach(pin, min, max)

In the latter form, you can specify values for the min and max microseconds that servo.write() will use to represent 0° and 180° respectively.

Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.

Also, as explained in my answer to question  “Change Servo Speed With RedBearLabs BLE Shield”, you can issue servo.write(value) calls with value in microseconds instead of in degrees, which may allow more precise control.


Download https://github.com/BoolLi/RC522_RFID_NFC_Utilities/archive/master.zip
Copy the folder RC522_RFID_Utilities from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.
If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522_RFID_NFC_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522_RFID_NFC_Utilities library, as is customary, you can do this:

Create a folder named examples in {sketchbook folder}/libraries/RC522_RFID_NFC_Utilities
Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the examples folder you created.
Restart the Arduino IDE if it's running.

The example sketches will now be accessible via File > Examples > RC522_RFID_NFC_Utilities.


The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in this article, not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.

Here's my updated schematics


Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in power down sleep mode. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.

A pin change interrupt could be used instead.

For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.

Cheers!


Reusing LED from RC helicopter controller

Yes, you can. For convenience, cut a bit shorter the lead on the side of the package where the flat part is so that you can identify the leads easier.


How useful could the Arduino Yun be in computer vision in a robotics project?

It probably has enough memory and speed to run basic object recognition software, but I there's a better solution, and that's to do your image capture and your object recognition with another device, and use the Arduino to act on the incoming data in some way. That would give you enough juice to do object tracking or searching. I plan to do this for my copter gimbal hopefully to be able to track objects on the ground, like criminals running from the cops for example.

This product will work great for that. Since you need a camera anyway, I think this is a pretty good deal... http://petapixel.com/2013/09/01/pixy-low-cost-camera-recognizes-follows-objects-color/

Can be purchased here: http://www.adafruit.com/products/1906

AdaFruit has tutorials to help you get started.  (Computer-vision doesn't exist as a tag right now and I can't create it, but I tried, sorry)


Node.js cannot recognize characters from the serial port

If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the 'ņ' character is removed from the string. But Serial.println() sends "\r\n" as line ending. That means, that your string is "c\r", which is not equal to "c".

By using the trim() method of the String type, you can remove all white space from start and end of the string, including line ending characters like '\r'.


Are you trying to use the same function for different arrays at different times, or are you trying to use a function that handles four different arrays at the same time?

If the former, you'd write something like

void myfunc( T *arr, size_t size ) // where T is the type of the array
{
  for ( size_t i = 0; i < size; i++ )
    arr[i] = some_new_value();
}

then call it for each array:

T arr1[N];  // where T is int, float, double, whatever
T arr2[M];
T arr3[O];
T arr4[P];

myFunc( arr1, N );
myFunc( arr2, M );
myFunc( arr3, O );
myFunc( arr4, P );

This assumes all the arrays have the same base type (e.g., they're all arrays of int).

If you want a function to work on four arrays simultaneously, you'd write it as

void myFunc( T *a1, size_t a1_size,
             T *a2, size_t a2_size,
             T *a3, size_t a3_size,
             T *a4, size_t a4_size )
{
  // code for handling each array
}

While I wrote it such that all the arrays have the same type, it doesn't have to be this way.  Each array can be a different type (a1 can be int, a2 can be double, etc.).


The "sign" of the INA219 shows the direction of flow of the current. Current isn't either "positive" or "negative", it has a direction. The sign is just used to represent that direction.

It's like a car. It has a speed. That speed could be in the forward direction, or the reverse direction.  It could be going 5 miles per hour forwards, or 5 miles per hour backwards. Either way, it's 5 miles per hour. However the backwards direction could be represented as "minus 5 miles per hour". It doesn't mean that you're doing a negative speed (there is no such thing), but that your speed is in a "negative direction".

This "speed" and "direction" are combined together to create "velocity", which is "speed relative to some arbitrarily chosen 'normal' direction and speed".

At this point the "velocity" can be represented as a 2D vector, with forward velocity in the + direction, and reverse velocity in the - direction.

But that's all a bit of a digression. All it means is that the "-" is meaningless if you don't care about the direction of current flow. If all you care about is the quantity of current you can discard the "-" completely.  The simplest way is:

current = abs(current);


Firstly you need to write a more reliable serial reading routine on the Arduino. As it stands your routine is lucky you even get what you do. You need to write a routine that doesn't care about time, but instead cares about the terminating character of the line you are receiving.

Here is an article I wrote all about it.

Secondly, you cannot communicate reliably using SoftwareSerial at 115200 baud.  While the Arduino is capable of receiving a byte at that baud rate using bit banging, there typically isn't enough time between successive bytes to allow the Arduino to store what it has just received, and so it starts receiving partway through the next byte, corrupting both it and the following byte. That's the cause of the corruption you are seeing.

You should either slow down the baud rate (9600 is a good choice), or send the data one byte at a time and add a delay between each byte (somewhat hacky...).


How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?

I've had the same problem, but couldn't fix it with the "Upload using programmer".
Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.

This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.

After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.


What is the best way to power the ESP32 from a battery?

Since it is a freezer (operating temperature unknown) I am assuming it is connected to the mains why not do the same with the electronics. This will save you a lot work and time and when you find out it will not work in a  Faraday cage as stated by timemage.  Leave the sensor wire long enough to mount the electronics outside just in case. Also consider packaging, it will be cold, possibly below the operating range of some of the components requiring you to keep them warm (above minimum temperature). I would assume your freezer like ours has moisture concerns as ice will form when opened then removed by a defrost cycle. You will also have to protect for that. Then there is the operating temperature range of the batteries, are they capable of operating at your freezer temperatures. I would suggest you redefine your problem before starting the design, this process saves me a lot of grief.


No, it's certainly not possible to directly sample at 500Msps on an Arduino using an external ADC.  Simple maths:

The Arduino can perform 16 million instructions (best case) per second
The ADC performs 500 million samples per second.
500 / 16 = 31.25

Therefore the ADC would be generating 31.25 samples for every clock of the Arduino, so unless you can build in a time compressor (maybe with a flux capacitor too), it just ain't gonna do it.

So you will have to think creatively instead.  A possible solution would involve:

A high speed flash or pipelined ADC, ideally with parallel output.
A large chunk of memory to act as a buffer.
A high speed clock source to set the timing (500MHz?).
Glue logic and counters to take one sample, store it in the buffer, and increment the buffer address.
More glue logic and interfacing to allow the Arduino access to the buffer memory and to control the operation of the sampling system.

This, to me, sounds like a job for an FPGA, and at 500MHz, quite a fast FPGA.  You should investigate some of the FPGA development boards from Xilinx and Altera.


The Arduino IDE does keyword coloration according to a very crude system. It simply scans for all the keywords.txt files included with:

Arduino IDE
Libraries bundled with the Arduino IDE
Libraries you have installed to the libraries subfolder of your sketchbook
Libraries bundled with the hardware package of the currently selected board - Hardware package of the currently selected board (recent IDE versions only)

There are several types of keyword identifiers that determine which color is used. The reason those letters are colored in your IDE is because some library you have installed just happens to have added them to its keywords.txt file.
The Arduino IDE makes no attempt to determine whether you have included those libraries and so coloration doesn't necessarily mean they are "reserved". If you have not included the library that defines a specific keyword then the coloration of that keyword is meaningless.

For more information on keywords.txt see:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords


Start/Stop/Reset the melody using buttons

Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.


What are the correct pins for TWAI (CAN) on ESP32?

I looked for information about it in the documentation, but I couldn't
find it.

Well, some of their documentation says:

The TWAI controller’s interface consists of 4 signal lines known as
TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed
through the GPIO Matrix to the ESP32’s GPIO pads.

And that sort of seems to be backed up by their examples that make use of TWAI_GENERAL_CONFIG_DEFAULT to generate a structure with the arguments filling fields that use gpoi_num_t.
There is documentation to the GPIO Matrix generally in the ESP32 technical reference.  It is described there as follows:

The ESP32 chip features 34 physical GPIO pads. Each pad can be used as
a general-purpose I/O, or be connected to an internal peripheral
signal. The IO_MUX, RTC IO_MUX and the GPIO matrix are responsible for
routing signals from the peripherals to GPIO pads. Together these
systems provide highly configurable I/O.

(My emphasis in the above).
And also there is a table (Table 25) in Appendix 2 of the ESP32 datasheet for the GPIO matrix.
Many of the small chips, like the PIC16F series ones, have no internal routing for peripherals, except for deciding which of one or two special functions to use rather than GPIO and ADC channels.  Most of the of the ATTiny and ATMega series AVR chips that are not in the 0- and 1- series don't.  The 1- and 0- series an a few of the older series parts (e.g. ATTiny841) give you a fixed number (usually two) pre-determined destinations to chose from for some peripherals.
This sort of thing gets more flexible as you get into larger chips, but the having that "matrix" feature that lets choose more freely is comparatively rare.  Some of the Cypress "PSoC" labeled chips have this sort of feature.


What you're talking about is often called a Hash or a Map or sometimes both together as a HashMap.

Unfortunately it's a facility that isn't supported in the Arduino C++ language

There are map objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.

The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date.  Instead you store the date inside the array along with the data - assuming you really need to know the date.

A good concept to get to grips with for this is the struct.  This is a custom data type which you define and can store a number of other different data types within itself.  You can then make an array or linked list out of those new data types.

For instance, you may have:

typedef struct {
    int year;
    byte month;
    byte day;
    float gain;
    float cost;
} Data;

You can then create variables of type "Data" and assign values to the items within it:

Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;

Or assign them directly at creation time:

Data myEntry = {2015, 11, 7, 100.23, 78.0};

If you wanted to store 100 days' worth of data you could use an array:

Data myArray[100];

Then you access each slice:

myArray[0].year = 2015;
... etc ...

I mentioned above "assuming you really need to know the date".  Most of the time with this kind of method you really don't need to store the date.  If you have one entry per day and you know when you started gathering data then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data.  Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is today you can count backwards from today to work out what date each entry is.


How to measure voltage with Arduino analog input

You can connect digital pin to analog input directly. That's not very interesting though, since you'll only see two values from the analog input (at least theoretically).

The digital pin gives out 0 or 5 Volts. The analog pin expects 0 to 5 Volts input. The only thing that matters to the analog input is the voltage with respect to ground. That can be between 0 to 5 volts (returned as 0...1023 by analogRead function).

  Just connect them directly - it is not a short circuit, is it?

No, it's not a short circuit. In general, connecting anything to an input is not a short circuit. Connecting output to another output is potentially a short circuit.

  Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?

This makes no difference compared to connecting them directly, unless the resistor value is very high (should be hundreds of kOhms or even MOhms to see a difference, I suppose), because almost no current flows to the input.

  Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

This makes no other difference than that the resistor loads, i.e. draws current from, the digital output. If the resistor value is too small, then the digital output is unable to supply enough current so the 5 V voltage could become less than 5 V, or you could even burn the chip.


Can't display the two float values correctly from pyserial on Arduino's LCD

I don't understand why you read the bytes this way. Your original version was reading only the bytes of the first float into xdata and -1 into ydata. (read returns -1 if no data is available, it doesn't wait.) Now when two bytes are read with readBytes, first two bytes of the first float are written one into xdata[0] and second into ydata[0].

read first float with readBytes(xdata, 4) and the the second with readBytes(ydata, 4)


Arduino uses pins 0 and 1 for Serial. Use other pins in your sketch


Using LDR and RGB Led to get R,G,B values

Your are probably doing the white calibration with some clear liquid,
like water. The LDR is then lit directly by the LEDs, and is getting too
much light. It's resistance is then very low compared to the pull-down
resistor in series with it. You end up measuring something very close to
5 V.

You should try to reduce the amount of light hitting the LDR. A neutral
density filter (the kind used in photography) would be ideal.
Alternatively, you could increase the distance between the LEDs and the
LDR, and put some translucent paper in between. You could also add a
diaphragm (a small hole). Then, you can also lower the resistance of the
pull-down in order to get lower voltage readings, but beware not to draw
too much current.

A comment about the instructable you linked to: owing to the highly
non-linear characteristic of the readings you get, it is quite likely
that you get unequal RGB vales from a neutral grey. Some kind of
linearization (estimating actual light fluxes) would be needed if you
want neutral greys to be measured as neutral greys.


The strip and the Arduino need to share the same ground connection. They are communicating through voltage and voltage is always a difference between two points. The power supply sets the supply voltage as the difference between + and ground. The chips in the strip will then try to measure the voltage on the data line relative to their ground. When the grounds are not connected, the Arduinos output pin is floating somewhere else, depending on external factors. By connecting the grounds, both devices (Arduino and strip) use the same ground value to measure voltages. Only this enables communication between the devices.


In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.


I've been working on a project and I get an error compiling for board arduino uno. kindly help

#include <LcdKeypad.h>

#include <LiquidCrystal.h>

#include <Wire.h> // For I2C
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
LcdKeypad lcd(0x3f, 2, 1, 0, 4, 5, 6, 7); // 0x27 is the default I2C bus address of the backpack-see article

#define echoPin 3 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 2 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

void setup() {
  lcd.begin (16, 2); // 16 x 2 LCD module
  lcd.setBackLightOn(3); // BL, BL_POL
  lcd.setBacklight(HIGH);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58, 2; //Calculate the distance (in cm) based on the speed of sound.
  lcd.home ();
  lcd.print("The Water Level is");
  lcd.setCursor (0, 1);
  lcd.print(distance);
  lcd.print("cm");
  Serial.println(distance);
  brightness = map(distance, 1, 100, 0, 255);
  analogWrite(led, brightness);
  delay(1000);
}


Adding to the counter only ONCE while R2 =<200

You can set a flag to indicate that R2 is or has been above 200 since it last was low, much as follows.

// before loop() ...
byte Rhi = true;  // at outset, say that R2 has been high
...

// in loop() ...
  if (R2 > 200)          // Has R2 gone high?
    Rhi = true;
  if (Rhi && R2 <= 200){ // Has R2 gone low from high?
    Rhi = false;
    ++counter;
    Serial.print("counter: ");
    Serial.println(counter);
  }
  ...


Try  lowering the rpm in the code. I had a similar issue with anything over about 18rpm using certain libraries with certain stepper motors.


How to convert char array to String in arduino?

you can use a cast to __FlashStringHelper to invoke the right constructor of the String class. It is the constructor which copies the char array from PROGMEM. __FlashStringHelper is intended as return type for the F() macro.

const char charArray[] PROGMEM = "Some text";

void setup() {

  Serial.begin(115200);

  String s((const __FlashStringHelper*) charArray);

  Serial.println(s);
}

void loop() {
}


How to store values from a sensor inside an empty array?

int i=0;
  int  dist [i] = {
    calculateDistance()      };

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.

You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

Maybe more like this:

 int  dist [180];

  for (i=0;i<180;i++){
    dist [i] = calculateDistance ();
    if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }

Also, this is wrong in your code:

for (i=0;i=180;i++){

You need to test for < 180 here. Your for loop will assign 180 to i and then check to see if it is non-zero, which will always be true.


Automate capturing photograph on ESP32-CAM

Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera
The project has different things, but definetelly doing what you asked, captures photo by external event, command...


The “firmware” is whatever program a microcontroller runs. On an
Arduino, it is typically the program you write and upload into the
microcontroller's flash memory.

If by “firmware” you mean the core library (the source code of
pinMode(), digitalRead() and so on), it is here:

https://github.com/arduino/ArduinoCore-avr

If by “firmware” you mean the bootloader (the small program that runs at
reset and will accept the upload of your firmware), is is here:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/optiboot

Note that this is valid for the AVR-based Arduinos.
The cores and bootloaders used in other architectures are stored is
separate repositories, e.g.

https://github.com/arduino/ArduinoCore-sam


Accelstepper - how to switch from fullstep to halfstep in loop?

The documentation notes a setCurrentPosition() function.

void AccelStepper::setCurrentPosition ( long position )

  Resets the current position of the motor, so that wherever the motor happens
  to be right now is considered to be the new 0 position. Useful for
  setting a zero position on a stepper after an initial hardware
  positioning move. Has the side effect of setting the current motor
  speed to 0.

  Parameters

  position The position in steps of wherever the motor happens to be right now.

Use the currentPosition() function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.


Az Delivery ESP32 DevKitC V2 PIN names/number

ESP32 boards don't use "names" for their IO pins. There is a direct 1:1 mapping between the internal "GPIO" number and the pin number.
To do something with pin G21 on the board you use pin number 21. To do something with pin G14 you use pin number 14.
By all accounts that board differs from other ESP32 devkits in that the LED is on GPIO1 rather than the normal GPIO0 that all the other boards use. I suspect that this is the source of your confusion.


There is an extensive guide written by SparkFun explaining how to work with Arduino Pro Micro: Pro Micro & Fio V3 Hookup Guide.

There are specific drivers for the board, so make sure you have them installed. There are also board files for the IDE, which allow you to select the Pro Micro in Arduino software.


Internet connectivity for the Arduino Due using AtmelStudio?

Well, your best bet is to import the arduino libraries in your Atmel Studio project. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.

Though, the Sam 3X features an hardware ethernet that is not wired, unlike the MBed LPC1768… Sadly that's the ethernet PHY component you saw, but won't be able to actually use…


My guess is, that you're wasting too much time within the drawing-part.

What is the value for delay? I guess you have a number too low chosen here. And you should really set this new time after you have updated the display by display.display();.

Your webserver doesn't respond because he's not called often enough inside this code.


If you were trying to wire your bus in parasitic mode, here is what I am using:

OneWire Bus in parasitic mode:

+------------+     +5v            +---------+     +---------+
|    MCU     |      |             | DS18b20 |     | DS18b20 |
|            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
| Strong-    |      |             +-o--o--o-+     +-o--o--o-+
| Pullup   > o------o               |  |  |         |  |  |
|            |      |               +--|--+         +--|--+
|            |      |               |  |            |  |
|    Data <> o------o---------------|--o------------|--o------ - - -
|            |                      |               |
+------------+                      V               V

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.


Why doesn't this debounce function work?

This probably won't answer your question completely, but here are some notes from me:

buttonState = current ;  //read value again now that bouncing is over

This won't read the value again, it just copies current into buttonValue.

What you wanted is:

buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

You have multiple issues with your debounce call:

lastTimeDebounce is never used by your code, so it is always zero.
lastButtonState will be always buttonVal making the debounce function useless.

Some other tips:

Don't use the same names for parameters as for global variables:

boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)

The global variable BUTTON will be shadowed by int BUTTON, essentially overriding it.
Don't use global variables (unless you have a very good reason)

EDIT

I would strongly recommend writing a function that debounces only one pin.

Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).

EDIT2:

Here is a debounce function that should work:

const uint8_t PIN = 13;

/*
 * Returns debounced value for `PIN`
 */
boolean debounce(void)
{
    // Current state of the pin
    boolean currentState;
    // Last state of the pin, initial value is zero
    static boolean lastCurrentState = 0;
    // Timer
    static unsigned long debounceTimer = millis();
    // Debounced value, initial value is zero
    static boolean debouncedValue = 0;

    // We first read the current state of the pin
    currentState = digitalRead(PIN);

    // Then we look if the state has changed
    if (currentState != lastCurrentState) {
        // If it has, we need to reset the debounce timer
        debounceTimer = millis();
    }

    // Then we check if the timer has expired
    if ((millis() - 50) > debounceTimer) {
        // The timer expired so we update the value
        debouncedValue = currentState;
    }

    // Save the latest state
    lastCurrentState = currentState;

    // We always return a debounced value:
    return debouncedValue;
}

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.


Can I power ESP8266 with more than 3.5 V?

The datasheet usually is definitive on the allowable range of voltages.

Look in Section 5.1: Electrical Characteristics.

Working Voltage Value:

Min: 2.5 V
Typical: 3.3 V
Max: 3.6 V

If you have to feed in signals that could go higher than 3.3 V in normal operation, you need to either clamp it with Zener diodes, or use a voltage divider.

If you are asking about powering the chip with more than 3.3 V, don't. You can get away with a 3.3 V linear regulator and 2 capacitors so that you are powering it with no more than designed supply voltage.


ESP8266 library: 2 requests received instead of 1

Browsers automaticaly request /favicon.ico for sites. Add this to  section of your HTML to eliminate the 'favicon' request:

<link rel="icon" href="data:;base64,iVBORw0KGgo=">

client.println("HTTP/1.1 200 OK\r\n" "Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("");
client.println("<link rel='icon' href='data:;base64,iVBORw0KGgo='>");
client.println("");
client.println("Hello World!");
client.println("");

based on this SO answer, instead of pointing to a server, the icon is encoded in the href parameter as base64 string


ESP8266 upload data to google cloud platform

Your biggest problem is that you are trying to use a website URL as a FQDN. That's not going to work.

When you connect to a remote machine you connect to the name (myname.appspot.com) which gets translated into an IP address for you to open a connection to.

When you use a web browser it parses the URL to extract the protocol (http) and the FQDN (myname.appspot.com) and uses the protocol to determine the port (and what language to speak) to connect to, then look up the IP address from the FQDN.

You need to drop the http:// from your FQDN which is causing it to break (there is no host called http://myname.appspot.com).  The fact that you are connecting to port 80 and speaking the HTTP language implies that you are using HTTP.

To put it into more layman's terms: if you "need to call Fred to talk about going to the pub" you first look up fred's number in the phone book then call that number. Then only once he has answered do you talk about going to the pub. What you don't do is try and find the number to call by looking in the phone book under "talk about going to the pub with Fred". It won't be there.

If you are programming your ESP8266 directly you should consider using the much simpler bundled ESP8266HTTPClient.h library.


Communication with ESP, HTTP requests or WebSocket?

This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (GET) or as part of the body (POST).

  Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.

Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.


Arduino Nano v3: is it possible to PCM + AltSoftSerial?

It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.

A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.

Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?

The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.

A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.

The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.


What happens if I power the Arduino with both the USB and external power voltage simultaneously?

I am a novice user of Arduino. I am not sure whether I can connect both USB and external supply through power adaptor to Arduino simultaneously. Would this burn the controller?

Lets study the schematic of Arduino UNO R3

The input from the power supply plug (PWRIN, the power jack) goes through a diode D1 (to prevent reverse polarity), and feeds a NCP1117 regulator that down converts it to the 5v supply that feeds the 5v parts.

The alternative supply comes from the USB plug (USBVCC). The relevant circuit is shown below

The USB power lines goes through a P-mosfet (T1) that operates as a switch and then goes to the +5V node (that is the +5v regulator output as shown in the first schematic).

The mosfet is controlled by an LMV358 operational amplifier (OPAMP) that operates as a comparator.
The negative input of the opamp is tied to 3.3V and the positive one fed through a voltage divider with half the Vin supply level.

When Vin >6.6V then the + input of the opamp become higher than the - input and the opamp turns the mosfet off.
When Vin <6.6V then the + input of the opamp become lower than the - input and the opamp turns the mosfet on.

Note that Vin is after the input diode so it's about 0.6V lower than the external connected power supply level. So when there is power supply connected to the power input that is higher than 6.6V+0.6V (where 0.6V is the diode D1 voltage drop), then the USB supply line is cutoff (because the mosfet turns off) and the power is provided from the power plug. Connecting or disconnecting the USB supply in this case will not make a difference, so you can have both power supplies connected simultaneously, only when the power input drops below the specified level (about 6.6V+0.6V=7.2V), the USB will start powering the board.


So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

}

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

}


Use normal TFT Shield with SD as a Nextion Display

No, you can't.
Nextion displays contain their own microcontroller with their own closed-source firmware on them.  You need that firmware to have a clue what is in Nextion files, and only Nextion have that firmware.
While it may be possible to reverse engineer Nextion display data and write your own software to interpret it, it would be a huge job with little to no real-world benefit.


counting ADC samples ( using a light sensor)

There are 2 common light sensor types.  The photo diode and the photo resistor.  The first produces small amounts of current and operates fast.  The second changes resistance and operates (very) slowly.

There is a good stack exchange response here for how to use a photo diode.  Often the photo diode output is small and additional hardware is used to amplify the signal.  As discussed in this stack exchange response.

The photo resistor or cadmium sulphide cell or Light Dependent Resistor is much easier to interface with an Arduino.  However, the response time is very slow.  On the order of hundreds of milliseconds to seconds.  This is acceptable when controlling street lights.  But is not acceptable in applications requiring fast light detectors such as those used for communication.

Before going on, verify which device you are using in your design.

Generally, Arduinos contain a 10 bit ADC.  This results in values from 0 to 210−1 or 0 to 1023.  Should you consistently get a reading at or near the limits of the ADC check your hardware.  Do this by measuring the voltage at the input of the ADC pin used.  Do this under varying conditions to verify the hardware is operating as expected.

A good software design uses hysteresis to convert an analog value to a logical 1 or 0.  Here is a stack exchange response about using hysteresis with Arduinos.


Buy a genuine arduino board or a sainsmart board?

Buying an official board can be a good choice for a couple of main reasons. First of all, you're guaranteed a good quality board which conforms to the official schematic, and is definitely compatible with any relevant official software and hardware. If the board turns out to be faulty when you get it, you'll be able to get it replaced. Additionally, buying official boards means some of the money you spend goes towards funding future Arduino projects.

As you've no doubt seen, cloned (i.e. unofficial) boards based on Arduino are often much cheaper. Nonetheless, many of the boards are very good. Functionally, you might not see any difference whatsoever from the official/genuine boards. Some of them actually have some additional features which you might find useful depending on your project, such as switching the IO pins between 3.3v and 5v.

However, not all cloned boards are worth using. Some of them may have lower quality components. It's even possible that they weren't designed/constructed correctly in the first place. This could lead to a range of problems, from incompatibilities through to outright failure of the hardware. Given the geographic location of some of the manufacturers/sellers, you may not have any way to get a refund if something goes wrong.

If you choose to use a clone, look for a brand which other people have had success with. Also do your best to ensure the board uses the correct microcontroller (e.g. the Atmega328 for boards based on the Uno).

Ultimately, the decision is up to you. There's no 'right' answer necessarily.


Getting the "Device has problem: 0x0a: CM_PROB_FAILED_START." error code 10 while installing device driver for Arduino Uno

Error code 10 mean Bad Environment.  I would guess that you are using the wrong driver, probably 64 bit on a 32 bit OS, etc.

This does not look like a Arduino fault, it looks like a windows Driver fault, so unlplug the board, reboot the PC logon as admin and download the latest drivers for you device and see if that fixes it.  You might be able to get better help on a Windows admin forum I think.


Dynamic allocation/ Pointer to Pointer to update an Array containing parameter

You may try something like this:

const char* topicArry[2] = {NULL, groupTopic};
const char** const pDeviceTopic = &topicArry[0];
#define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.

deviceTopic = msgTopic;

you are actually writing into topicArry[0].