text:
DC Motor's don't stop immediately
Functionality
I have written this code below for a buggy to continue moving forward until there is an obstacle which is <= 25cm both motors should stop.
Result
both motors stop when there is an obstacle which is <=25cm but the motors happen not to stop immediately when it comes across the obstacle please do find my code below is there something wrong with my code and how can I make it much better.
Code
#define PING_PIN  12  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

//initializing left DC Motor
const int in_1 = 2; // initializing the IN1 to Pin 2
const int in_2 = 3; //initializing the IN2 to Pin 3
const int EnA = 4;  //initializing pin 4 as pwm

////initializing Right DC Motor
const int in_3 =5;  // initializing the IN3 to Pin 5
const int in_4 = 6; // initializing the IN4 to Pin 6
const int EnB = 7;  //initializing pin 7 as pwm

// initialzing Ultrasonic sesor (Front view)
const int trigPin = 8;
const int echoPin = 9;

//For providing logic to L298 IC to choose the direction of the DC motor
void setup()
{
    /// initialize serial communication:
    Serial.begin(9600);
    pinMode(EnA,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_1,OUTPUT);  //Logic pins are also set as output
    pinMode(in_2,OUTPUT);
    pinMode(EnB,OUTPUT);   //we have to set PWM pin as output
    pinMode(in_3,OUTPUT);  //Logic pins are also set as output
    pinMode(in_4,OUTPUT);

    //--------------------------------------------------------------
    // Reading the signal from the sensor: a HIGH pulse
    //-----------------------------------------------------------------
    pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
    pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
    //pinMode(trigPin2, OUTPUT);// set the trig pin to output (Send sound waves)
    //pinMode(echoPin2, INPUT);// set the echo pin to input (recieve sound waves)
}

void loop()
{
    int duration, Distance; // start the scan
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2); // delays are required for a succesful sensor operation.
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); //this delay is required as well!
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //---------------------------------------
    // convert the time into a distance
    //---------------------------------------
    Distance = (duration/2)/29.1;
    Serial.print(Distance);
    Serial.print("cm");
    Serial.println();
    delay(1000);
    if (Distance <= 25)
    {
        //Stopping Right and Left Motors
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,HIGH);
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,HIGH);
    }
    else {
        //Moving both Motors in a Foward motion - IN_1 = LOW , IN_2 = HIGH, IN_3 = LOW , IN_4 = HIGH
        digitalWrite(in_1,HIGH);
        digitalWrite(in_2,LOW);
        analogWrite(EnA,200); // Enablling the Right motor @ speed of 200
        digitalWrite(in_3,HIGH);
        digitalWrite(in_4,LOW);
        analogWrite(EnB,200);// Enablling the Left motor @ speed of 200
    }
}

Do the motors stop immediately if you just disconnect them from the power?

Never use delay() on something that has to be responsive.

@MarkSmith yes they stop immediately when I disconnect them from the power

are you saying I shouldn't have delays for the ultrasonic sensor, and delay for displaying to the serial because those are the only place I used the delays in the program and I need the delays for a successful sensor operation  @EdgarBonet

delay(1000) is not directly responsive. Might want to move that to after the motor control?

As already stated, your problem is in the use of delay(), which
blocks the program until the delay is over. When your program needs to
be responsive, you have to write everything in a non-bloking manner.
The basics of non-blocking management of time are covered in the
Blink Without Delay Arduino
tutorial, which I
strongly encourage you to read. Applying the technique of the tutorial
to your printing of the distance gives something like this:
static uint32_t last_time_printed;
uint32_t now = millis();
if (now - last_time_printed >= 1000) {
    Serial.println(Distance);
    last_time_printed = now;
}

I think the code is quite straightforward: you record the last time you
printed the value and, if it has been one second since last time, you
print it again.
You also have some other blocking calls in the section where you operate
the sonar. I would not worry too much about delayMicroseconds(): these
are really tiny delays, and your robot does not need to be that
responsive. I would worry about pulseIn() though: this function blocks
until it sees the end of the pulse, or until it reaches a timeout. The
default timeout is one second, which is way too large for this
application. Instead of relying on the default, you should specify a
timeout as a third parameter, as in
duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

This would limit the range to about 8 m, which I think should be
more than enough.
Reading the sonar pulse in a completely non-blocking fashion is
possible, by using either an input capture unit or an interrupt, but I
guess it is not worth the trouble, as your robot can probably cope well
with being blocked for 50 ms.

As some of the comments have mentioned, the delay(1000); is probably doing you in. What's happening there is the code does absolutely nothing but count 1000ms for that time, so if the obstacle comes within 25cm during that delay, nothing will happen until the delay is done counting and the if statement occurs.
If you still want it to serial print every second, but not have that effect of slowing your response, try a counting variable (I forget the actual name). It's like a flag that you count on, so for example, you could have int printCount = 0; and instead of the delay(1000);, you'd have

delay(1);
if(printCount > 999){
  Serial.println('Whatever');
  printCount = 0; //resets counter
} else{
  printCount++;
}

make so much sense to me now thank you for your help I really appreciate it @Orotavia

Although this kind of works (albeit with very inconsistent timings), I don't think it's wise to encourage the OP to persist in using delay().

While I totally agree with the other answers on the issue of using a non-blocking timer, I would like to add another factor about motor braking from a purely "electrical" point of view.......
To "brake" a running DC motor, you need to short the two terminals. This will generate a back current in the coil which will reverse the magnetic field and stop the motor much faster than by just cutting off power to the terminals. This is not possible to implement using a Bi-polar H bridge motor driver like L293D. You need to use a MOSFET type H-bridge.

You can break with a bipolar driver, if only through the free-wheeling diodes. This is even documented as “Fast motor stop” in the L293D datasheet.

@Edgar Could you provide a reference to this please? I can't find any mention of this in the [datasheet] (http://pdf.datasheetcatalog.com/datasheet/stmicroelectronics/1330.pdf)

See e.g. table 3 of the datasheet.

I see the reference now, thanks. But this TI datasheet looks much more detailed than the one I linked to (SGS Thomson). I wonder why...


text:
Additional boards manager option is missing from Arduino IDE
I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?

Update to a version that has the option.

I just installed the ide 2 days ago . I have the latest one.

What version do you have that you think is the latest one?

Version of installed ide is 2:1.0.5+dfsg2-4

1.0.5 is ancient.

You need to download and install a recent version of the Arduino IDE from:
http://www.arduino.cc/en/Main/Software
When you install the Arduino IDE using apt-get you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:
https://github.com/arduino/Arduino/pull/2703

the URL is the following and the 1.8.2 IDE accepted it:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Good luck,
endre
P.s.: I found the answer/URL here:
No Response to AT commands

this worked....actually this is the correct url

You stated in the comments that you are using version 1.0.5. This is a very old version. Go through you computer and make sure you uninstalled any old versions, then try to reinstall the ide.
Make sure you download from arduino.cc, the official location to download the software.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How to get and interpret digital accelerometer data?
I am trying to connect an Arduino to a digital accelerometer. The Arduino receives commands from a mobile app and transmits over Bluetooth through hardware serial.
I also posted this question here.
Code:
 #include < SPI.h >

const int X8 = 0x06;
const int Y8 = 0x07;
const int Z8 = 0x08;

/*
bits
1 0  mode 00: standby, 01: measurement
5     1: spi 3 wire, 0: 4 wire
4      self test
3     2 glevel: 01 2g
1 0  mode, 00 standby, 01 measurement
*/
const int MODE = 0x16;

const int STATUS = 0x09;

//7 digital filter band width, 0 62.5 Hz, 1 125 Hz
const int CONTROL = 0x18;

bool isTesting = false;

const int chipSelectPin = 7;

void setup() {
    Serial.begin(9600);
    SPI.begin();
    pinMode(chipSelectPin, OUTPUT);

    //set up standby, spi 4 wire, 2g range,
    writeRegister(MODE, 0x04);

    //set up speed
    writeRegister(CONTROL, 0x00);

    delay(100);
}
void loop() {
    if (getSerial() == 't') {
        isTesting = true;
        writeRegister(MODE, 0x05); // 0000 0101- 0001 0101 0x15
        testing();

    }

}
void testing() {
    while (isTesting) {
        if ((readRegister(STATUS) & 1) == 1) {
            Serial.print((char) readRegister(X8), DEC);
            Serial.print("x");
            Serial.print((char) readRegister(Y8), DEC);
            Serial.print("y");
            Serial.print((char) readRegisterChar(Z8), DEC);
            Serial.print("z");
        }

        if (getSerial() == 'u') {
            isTesting = false;
            writeRegister(MODE, 0x04);
        }
    }
}
char getSerial() {
    if (Serial.available()) {
        char c = Serial.read();
        return c;
    }
    return 'x';
}
byte readRegister(byte thisRegister) {
    byte inByte = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}
char readRegisterChar(byte thisRegister) {
    char inChar = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inChar = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inChar;
}
void writeRegister(byte thisRegister, byte value) {
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(128 | thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data. The data received when the sensor is on a flat surface is:

x  y   z
5 -11 74
4 -19 74
2 -9 69
0 -8 68
7 -16 68
7 -11 73

When the self test is run, the results are:

-5 -20 122
-4 -22 122
-1 -20 123
-4 -20 123
-5 -21 121
-3 -18 123
-8 -22 127

From the data sheet: "When the self-test function is initiated through the mode control register ($16),
accessing the "self-test" bit, an electrostatic force is applied to each axis to cause it to deflect. The Z-axis is trimmed to deflect
1g."

Is the data correct? How is it interpreted? If the z data during self test is 1g, shouldn't it have the same magnitude as when it is on a flat surface?
I adapted to code to get the 10 bits of data:
const int X10_LSB = 0x00;
const int X10_MSB = 0x01;
const int Y10_LSB = 0x02;
const int Y10_MSB = 0x03;
const int Z10_LSB = 0x04;
const int Z10_MSB = 0x05;

//[...]

void testing() {
        while (isTesting) {
            if ((readRegister(STATUS) & 1) == 1) {

                int xData = (readRegister(X10_MSB) << 8) | readRegister(X10_LSB);

                // checks if bit 9 is 1 and sign extends
                if ((xData & 512) == 512)
                    xData = (0b1111110000000000 | xData);
                int yData = (readRegister(Y10_MSB) << 8) | readRegister(Y10_LSB);
                if ((yData & 512) == 512)
                    yData = (0b1111110000000000 | yData);
                int zData = (readRegister(Z10_MSB) << 8) | readRegister(Z10_LSB);
                if ((zData & 512) == 512)
                    zData = (0b1111110000000000 | zData);

                Serial.print(xData);
                Serial.print("x");
                Serial.print(yData);
                Serial.print("y");
                Serial.print(zData);
                Serial.print("z");

            }

The outputs for 2g measurement is:

4 246 -183
5 245 -183
5 245 -182
6 245 -181

For the self test:

252 -20 -134
253 -21 -133
253 -21 -135
253 -20 -135

the values for 8 and 10 bits of data don't correspond. What am I doing wrong?
Update: I rewrote the code to get the 10 bits of data with the LSB bits fisrt as per a comment:
Code:
     int xData =(readRegister (X10_LSB));
        xData = xData | (readRegister (X10_MSB)<<8);
        xData = xData << 6;
        int yData =(readRegister (Y10_LSB));
        yData = yData | (readRegister (Y10_MSB)<<8);
        yData = yData << 6;
        int zData = (readRegister (Z10_LSB));
        zData = zData | (readRegister (Z10_MSB)<<8);
        zData = zData << 6;

        xData /= 64;
        yData /= 64;
        zData /= 64;

The results for the sensor when on a flat surface:

0 -4 71
4 -11 70
5 -13 70
2 -12 70

The results when self-test is applied:

-2 -19 123
-2 -19 122
-4 -20 122
-3 -21 122

Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

Why didn't you tell us that it is about a MMA7455L sensor and that you are also asking the question here: http://forum.arduino.cc/index.php?topic=465471.0
Have you tried a library that is known to be working well ? You could try to shift the 10 bits 6 bits to the left for a 2's complement 16 bit integer. You read MSB first, but according to the datasheet: "XOUTH should be read directly following XOUTL read".

Have you tried this link sketch from the Arduino Playground?

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data

you are using it in 2g mode, so you have only 8bit of data.

The data received when the sensor is on a flat surface is:

this is correct. You have a 8bit range (256 value, from -128 to +128) that map a range from +2g to -2g. So we have 256lsb/4g = 64lsb/g.
Motionless, the lenght of the gravity vector (sqrt(xx+yy+z*z)) must be close to 64. Of corse you need some offset and non-linearity calibration but the data seems fine.
Also if you look at the piece of datasheet you posted in table "Sensitivity", you will see they call the LSB "count", and they are in the range we calculated!

When the self test is run, the results are:

again this is correct, if your sensor is flat in way the Gravity apply on the Z; what you see is the normal gravity (64) summing up to the self-test offset (64), giving you a nice ~128

I adapted to code to get the 10 bits of data:
Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

to use 10bit, you must set the full scale range to +-8g. If you look at the piece of datasheet you posted, table "Output Signal", you see how many bit are avaiable for each range.
If you think about it, how does the sensor know if you want to read 8 or 10bit? (remeber the DS say you must read the low register BEFORE high register!) if you read only 8bit, you would be loosing the 2msb, one rapresenting the sign and the other the most important bit that can change your result by 2^9=512
btw also you first 10 bit conversion is wrong as you flip the bit for 2's complement, but does nothing to the value bit.
The solution with bit shitf of 6 follow by divising is working but a bit strange to see. I would go for something more "standard" like
int xData = readRegister (X10_LSB) | (readRegister (X10_MSB) << 8);
if (xData | 0b0000 0010 0000 0000){ //if negative
    //keep 9 bit raspresenting the value and multiply by -1 to keep the sign
    xData = (xData & 0b0000 0001 1111 1111) * -1;
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
MPU-6050, why is pitch, yaw and roll data not being consistent (value keeps getting higher/lower when it is stable)?
I recently bought a MPU 6050 that I plan to use with a drone. However I face some difficulties now because the MPU is not giving me steady results.
The results (pitch, roll, yaw) i get are not consistent. If I for example keep the chip stable on a table the value keeps increasing/decreasing even though it is not being touched/moved.
I also seem to get different results if i restart it even though i use it at the same angles.
Is something off with my code or is there anything else I need to do in order to fix this issue?
Appreciate any help I can get! :)
Here is my current code:
#include <Servo.h>
#include <Wire.h>

int gyro_x, gyro_y, gyro_z;
long acc_x, acc_y, acc_z, acc_total_vector;
int temperature;
long gyro_x_cal, gyro_y_cal, gyro_z_cal;
long loop_timer;
int lcd_loop_counter;
float angle_pitch, angle_roll;
int angle_pitch_buffer, angle_roll_buffer;
boolean set_gyro_angles;
float angle_roll_acc, angle_pitch_acc;
float angle_pitch_output, angle_roll_output;

void setup() {

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

setup_mpu_6050_registers();
for (int cal_int = 0; cal_int < 2000 ; cal_int ++){

read_mpu_6050_data();
gyro_x_cal += gyro_x;
gyro_y_cal += gyro_y;
gyro_z_cal += gyro_z;
delay(3);
}

gyro_x_cal /= 2000;
gyro_y_cal /= 2000;
gyro_z_cal /= 2000;
loop_timer = micros();

}

void loop(){

read_mpu_6050_data();

gyro_x -= gyro_x_cal;
gyro_y -= gyro_y_cal;
gyro_z -= gyro_z_cal;

angle_pitch += gyro_x * 0.0000611;
angle_roll += gyro_y * 0.0000611;

angle_pitch += angle_roll * sin(gyro_z * 0.000001066);
angle_roll -= angle_pitch * sin(gyro_z * 0.000001066);

acc_total_vector = sqrt((acc_x*acc_x)+(acc_y*acc_y)+(acc_z*acc_z));
angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;
angle_roll_acc = asin((float)acc_x/acc_total_vector)* -57.296;

angle_pitch_acc -= 0.0;
angle_roll_acc -= 0.0;

if(set_gyro_angles){
angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004;
angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004;
}
else{
angle_pitch = angle_pitch_acc;
angle_roll = angle_roll_acc;
set_gyro_angles = true;
}

Serial.println(angle_pitch_output);
Serial.println(angle_roll_output);

while(micros() - loop_timer < 4000);
loop_timer = micros();
}

void read_mpu_6050_data(){

Wire.beginTransmission(0x68);
Wire.write(0x3B);
Wire.endTransmission();
Wire.requestFrom(0x68,14);
while(Wire.available() < 14);
acc_x = Wire.read()<<8|Wire.read();
acc_y = Wire.read()<<8|Wire.read();
acc_z = Wire.read()<<8|Wire.read();
temperature = Wire.read()<<8|Wire.read();
gyro_x = Wire.read()<<8|Wire.read();
gyro_y = Wire.read()<<8|Wire.read();
gyro_z = Wire.read()<<8|Wire.read();

}

void setup_mpu_6050_registers(){

Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);
Wire.endTransmission();

Wire.beginTransmission(0x68);
Wire.write(0x1C);
Wire.write(0x10);
Wire.endTransmission();
Wire.beginTransmission(0x68);
Wire.write(0x1B);
Wire.write(0x08);
Wire.endTransmission();
}

Did you put together pieces of code you found on the internet ? Can you tell where you found them ? It is a confusing mix of different programming styles and the formulas, the usage of the Wire library, the mixing of int, long and float are also confusing. The MPU-9250 has a magnetometer for the yaw. There are a number of good libraries for sensor fusion with filters for the 6DOF or 9DOF sensors. The MPU-6050 and MPU-9250 can also use the internal dmp firmware. You could start with the Sparkfun.com website and search for MPU-9250.

I do not use mpu-9250, i use the mpu-6050. And yea when it comes to the code i have found it everywhere and put together something on my own also which makes it a bit chaotic!

The MPU-6050 is outdated and the modules on Ebay could have a wrong capacitor making it even more noisier. Can you give a reference for those formulas ? Without reference I have a lot of doubts. Looking at the code, I even have doubts about the 4ms delay. Your loop is probably more slowed down by the full output buffer of Serial than by micros(). I strongly suggest to use a library and you might consider to buy a MPU-9250. Are you perhaps using a 5V Arduino without I2C level shifter ?

I bought it from ebay so perhaps the quality is not great :( My arduino has a I2C i believe.
Do you think this example could work well? https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino

I see some problems: the use of the Wire library is wrong (a endTransmission after requestFrom, a while loop after requestFrom); no sensor fusion; shifting a 8-bit variable 8 times to the left. This one tests new formulas. I think the results are a little noisy. Remove the display calls: https://github.com/kriswiner/MPU-6050/blob/master/MPU6050IMU.ino  This one works: http://forum.arduino.cc/index.php?topic=58048.0  This one is most often used: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050 but there have been some complaints that it does not use a real Kalman filter.


text:
What difference makes resistance of thermistors?
Following this thermistor tutorial i used 1k thermistors (and resistors) instead of 100k as in video.

What difference does it make?
What about 10k thermistors?
Is it good idea to use 1k/10k/100k potentiometer instead of resistors to tune up readings?

Maybe "thermistor" tag should be created here? 150 reputation required to do that.

A thermistor of 1k is less noise and more current. The 1k thermistor heats up with 6mW, I don't know if that will influence the themperature. To calculate the temperature you also need the specific numbers for that type of thermistor. When you would use the numbers of the 100k thermistor then the result of the formula could be less accurate. I prefer a "ntc" tag, or is "thermistor" more common ?

pots tend to have more thermal drift than carbon-film or wire-wound resistors. for basic hobby-level measurements, the specific resistance doesn't matter much. if you're integrating it with an LM334 for long-run sensing, one range might offer better integration than another.

Wish I knew which answer is proper to mark...

Skip to the end to get the easy answer!
Your choice of thermistor and bias resistor values depends on the following:
1.  How much current do you want to spend?
2.  How do you want the thermistor resistance to compare with the wiring resistance?
3.  How much filtering do you need?
4.  What kind of linearization do you want to apply?

A lower value thermistor will pull more current than a higher value one.  More current means less battery life but also affects (2) and (3) below.
For a given system wiring resistance, increasing the thermistor resistance reduces the measurement error due to the wiring. If your thermistor is 100 ohms (25C nominal) and your wiring is 1 ohm, then you would have a 1% error at 25C.  For an NTC (Negative Temperature Coefficient) thermistor, as it gets hotter and it resistance decreases, the wiring error  increases because the wiring represents a greater percentage of the total resistance.
Filtering a resistive sensor in front of an ADC can be done by simply putting a capacitor across the ADC input.  As your sensor resistance increases, the size of the capacitor required decreases for the same cutoff frequency.  Even if filtering is not needed, be sure to check the ADC input impedance requirement as sample and hold circuits need their minimum AC input impedances to be satisfied as well as the DC input currents:  Too much sensor impedance does not go well with too high ADC input current.
Unless you are using a platinum RTD with its linear response curve, your thermistor resistance vs temperature curve is going to be logarithmic where each end of the curve will be asymptotic.   This means you will get good resolution around the 25C reference temperature but at one end you'll get very little resistance change for a large change in temperature and at the other end you'll get a lot of resistance change for very little change in temperature.  By putting a resistor in parallel with the thermistor you can flatten out the curve to fit your measurement needs.

All this being said, your best bet is to put the thermistor curve into a spreadsheet and adjust the values until you get current consumption you can live with with a curve that gives you the information you need.  See this example for a 10K NTC sensor with linearization (Either the RT/R25 or RT-vs-Temp values are almost always listed in the data sheet for each thermistor):  Spreadsheet for this graph

I don't see the point of your linearization resistor: it can only lower your resolution and increase the current consumption. Per Thévenin's theorem, your circuit is equivalent to having the thermistor connected to a single pullup of resistance Rbias∥Rlinear pulling towards Vbias×Rlinear÷(Rbias+Rlinear). In other words you are only wasting part of your ADC range.

I see no pros to using a lower resistance thermistor in your answer; why might they even exist? Why ever use something like a 10 ohm (if it exists) vs. 100k or higher?

The spreadsheet link is not accessible anymore

The standard way to measure a resistive sensor is to make a voltage
divider with the sensor and a fixed resistance between Vcc and GND, like
this:
Vcc
 │
 Rb
 │
 ├─── analog input
 │
 Rx
 │
GND

where Rx is the resistance you want to measure and
Rb is a known bias resistance. The only unknown is the choice
of the bias resistance.
The simple rule of thumb is to choose a bias resistance close to the
typical values of the resistance you want to measure, as this will
optimize your measurement resolution. More specifically, the relative
measurement resolution, which could be stated as the number of ADC steps
you get per percent change in resistance, is maximal when Rx
= Rb, and decreases only slowly as Rx gets
further from Rb.
Now, one could argue that the relative resistance resolution is not
always the best performance metric. You may want to maximize the
absolute resistance resolution instead, or maybe the absolute
conductance resolution. Each of these choices would lead to a different
choice of bias resistor. For the case of a thermistor, however, the
choice is pretty clear: the resistance varies almost exponentially with
temperature, which means that the absolute temperature variations are
practically proportional to the relative resistance variations. If you
want to use temperature resolution as a metric, you could go through a
tedious calculation only to find out that the optimal Rb is
darn close to Rx.
In short, if your thermistor is 1 kΩ at 25 °C, and you will
use it near 25 °C, then a 1 kΩ pullup will give you the best
temperature resolution.
Now, measurement resolution may not be the only issue you care about,
and you may want to sacrifice some of it in order to improve something
else. For example:

Current consumption: a 1 kΩ thermistor in series with a 1 kΩ
pullup will draw 2.5 mA (assuming Vcc = 5 V), which
could rise to near 5 mA if it gets really hot. If you are running
off battery power this could be an issue.
Self heating: in that 1 kΩ + 1 kΩ configuration, the
thermistor will dissipate 6.25 mW. I've seen the datasheet of a
typical thermistor stating a thermal dissipation constant of
7 mW/K. This means the measurement current would heat the
thermistor to 0.9 °C above ambient temperature, which you would
need to take into account in your temperature calculations.

Both of these issues would be mitigated by using a larger value for
Rb, only at the cost of measurement resolution. Switching to
a 10 kΩ thermistor would mitigate these issues without sacrificing
resolution.

Related:

Selecting bias resistor for thermistor
Choosing the correct thermistor

I was trying to figure this out myself and was going to ask a question to verify my results. Since this question is so close, I'll just post my results as an answer and comments/votes can help me figure out if it's correct!
I've been going by this tutorial on Adafruit which, unfortunately, doesn't talk about why they use a 10k Ohm thermistor paired with a matching fixed/bias resistor.
So we're on the same page, here's the circuit used (voltage divider, pic taken from the second related answer above):

The formula used to get from resistance to temperature (taken from the Adafruit guide, which uses the Steinhart-Hart equation):

Here's the full code used to find the temperature based on the voltage divider created by the fixed/bias resistor and the thermistor:
int pin_therm = A0;    // analog read pin
float reading;         // hold thermistor resistance
float stein;           // hold calculated temp

int res_fixed = 10000; // 10k fixed resistor
int res_therm = 10000; // 10k thermistor
int therm_nom = 25;    // nominal thermistor temp
int therm_b = 3950;    // thermistor B coefficient

reading = analogRead(pin_therm);
reading = (1023 / reading) - 1;
reading = res_fixed / reading;

// apply the S-H equation
stein = reading / res_therm;    // (R/Ro)
stein = log(stein);             // ln(R/Ro)
stein /= therm_b;               // 1/B * ln(R/Ro)
stein += 1.0 / (25.0 + 273.15); // + (1/To)
stein = 1.0 / stein;            // Invert
stein -= 273.15;                // convert to C

My aim is to measure around 150-250C, and I was curious what my resolution was after seeing very specific, "steppy" values when watching serial output. For example, as temps rose I'd see values like 202, 211, 222 but nothing in between.
I used R to send all possible ADC values of 0-1023 through the equation to find the corresponding calculated temperature.
In my case, I modified the code above for the Honeywell 135-104LAG-J01 thermistor I was using (T = 25C, B = 3974). Using the rule of thumb to match the fixed resistor, here's what I get with 100k Ohms, showing ADC values for 150-250C. It revealed that this setup would only give me ~5 readings over 200-250C!

Going back to the math, it looked like I could drop the fixed resistance for better resolution. Here is the same 100k thermistor, but comparing the resolution obtained with 22k, 47k and 100k fixed resistors:

Using a lower fixed resistor, I have substantially more data points in my range of interest! We can simply compare the ADC ranges that make up this 150-250C span: ~20 for 100k and ~80 for 22k.
I'm not really worried about current consumption, but since it came up in the other answers, we can also increase the thermistor nominal resistance. Here's a plot breaking down by thermistor (100k - 1M) and matching fixed resistor (same 22k-100k values). I've removed the dots to make it less busy and the gray "mini-plot" titles are the thermistor values I looked at:

Lastly, to spare you from having to calculate the min vs. max ADC ranges covering the desired 150-250C range, here's a simple bar plot showing how many steps we get in this range.

So, with a 1M Ohm thermistor and 22k fixed resistor, we could have ~0.5C resolution in this high range (100C span divided by ~200 ADC steps).

I echo the suggestion of John Taylor to plot things out, but in my case, the datasheet didn't list the key values required for his spreadsheet. I think spelling out the Adafruit code and putting my R code at the end can help understand how to do this (approximated) in order to compare temperatures of interest vs. ADC steps which cover it.

As a last aside, I ran into the mention of "source impedance" on one of the related questions. I'm not an electrical engineer, but some answers suggest that there may be a time delay issue with reading ADC values when the circuit resistance is very high:

Required output impedance for ADC input?
Input impedance of Arduino Uno analog pins?

That said, since I'm measuring high on the temp scale, an NTC thermistor will have less than max resistance. We're also helped by the fact that the equivalent resistance is:
1/((1/R_fixed) + (1/R_therm))
So, even with a 1M thermistor an 100k fixed, our equivalent resistance at room temperature is:
1/((1/1000000) + (1/100000)) = ~91k
This will only reduce further at higher temps, but I thought I'd mention it for the sake of thoroughness!

Here's the R code used to generate the multi plot covering 100k-1M thermistors vs. 22k-100k fixed resistors:
## for plotting
library(ggplot2)

## R kept wanting scientific notation, e.g. 10e5
options(scipen=10)

## range for ADC reading
inputs <- 0:1023

## create all combos of fixed resistor, thermistor, and ADC values
combos <- expand.grid(res = c(22000, 47000, 100000),
                      therm = c(100000, 250000, 500000, 1000000),
                      adc = 0:1023)

## make sure it's sorted the right way
## also, give it a unique identifier per combo
combos <- combos[order(combos$therm, combos$res, combos$adc), ]
combos$grp <- paste0(combos$res, "_", combos$therm)

## calculate the temps for each thermistor/fixed res combo
dat_lst <- lapply(unique(combos$grp), function(grp) {

  temp <- combos[combos$grp == grp, ]
  res <- unique(temp$res) / ((1023 / inputs) - 1)
  stein <- res / unique(temp$therm);
  stein <- log(stein);
  stein <- stein / 3974.0;
  stein <- stein + (1.0 / (25.0 + 273.15));
  stein <- 1.0 / stein;
  stein <- stein - 273.15;

  temp$temp <- stein

  return(temp)

})

## combine results
data <- do.call(rbind, dat_lst)

## some factor re-labeling to make plots more readable
data$res <- factor(data$res,
                   levels = c(22000, 47000, 100000),
                   labels = c("22k", "47k", "100k"))
data$therm <- factor(data$therm,
                     levels = c(100000, 250000, 500000, 1000000),
                     labels = c("100k", "250k", "500k", "1M"))

## reduce to only values in our range of interest
data <- data[data$temp > 150 & data$temp < 250, ]

## the plot itself
p <- ggplot(data, aes(x = adc, y = temp, colour = as.factor(res),
            group = grp)) + geom_line()
p <- p + scale_x_continuous("adc value")
p <- p + scale_y_continuous("calculated temp, C")
p <- p + facet_grid(therm ~ .) + theme_bw()
p <- p + scale_colour_discrete("fixed resistor")
p

## to save it out
png("./therm-vs-fixed.png", res = 200, width = 1600, height = 900)
p
dev.off()

You would have reached the same conclusion much faster by applying the rule of thumb I posted in my answer: choose a fixed resistor close to the value of the resistance you want to measure. Example: Your 1 MΩ thermistor, in the middle of the relevant temperature range (200°C) has a resistance of 7.23 kΩ. You would then pair it with a fixed 6.8 kΩ resistor (the closest E6 series). Likewise, the 500 kΩ thermistor would be paired with 3.3 kΩ. All the fixed resistors you choose for your plots are way too high. You did exactly the kind of mistake that rule of thumb helps to avoid.

@EdgarBonet this answer was as much for me to process though why that rule of thumb makes sense as to add to this discussion. Maybe it will help someone to see the data vs. just taking it on faith. People think in different ways, and different answers can help things "click." Your answer is right on; I hope this supplements it as folks wander through.

Your idea of illustrating the concepts graphically is great. It does help many people, including myself, get the things. The problem is with your poor choice of data. Since all your fixed resistances are too high, your curves show a consistent trend: the lower the fixed resistance, the better. And that would be a very wrong conclusion to draw. Had you better chosen your fixed resistors, not only would you have revealed the optimum, but you could also asses how well the rule of thumb performs at getting you close to that optimum. Then you would have posted a great answer.

@EdgarBonet Gotcha. So if my example range of 150-250C is some range R1-R2, show what the curves look like for Rb < R1 and Rb > R2? Keep in mind I did most of this before finding this answer. Honestly, most people will google "how to read a thermistor," find people throwing out a 10k thermistor and 10k fixed resistor (or just saying "match them") and never find their way here. My plots look like they do because I was starting with what exists in tutorials and I slowly started testing the waters from there...


text:
How to drive a strip of 12 V no-addressable LEDs?
I recently bought this LED Strip. I got the 5M 3528 300LEDs SMD RGB Non-waterproof ones. However, I am not sure how to use them. On the strip there is four wires. I have tried supplying power to the wire that says it needs power and then I put ground to each of the other wires, but that only turns on a colour. How do I make it so I can choose what colour to use (Wiring, Code, etc.)?

The page you link to sells different models of LED strips. Some of them, which are based on the WS2812B chip, allow the LEDs to be individually addressed. However, the strip you got has no WS2812B and is not addressable. The original title of your question, “WS2812B LED Strip”, was then extremely misleading. That's why @Orotavia posted a first answer that is not applicable to your strip. I edited the title to better reflect the reality.

EDIT: I'm sorry, I misunderstood! I assumed your LEDs were the 4pin serial version, whereas it makes more sense to me that they are the 6pin analog version. I must've brushed over the part where you said you grounded the colored wires and got that corresponding color.
You will provide 12V to the Power wire. To light the strip Red, you'd ground the Red wire, ground Blue for Blue, etc. Ground Red and Blue to light Purple, mixing colors etc etc.
So what if you wanted teal? or maybe a different shade of green? You'll need a way to generate PWM on the R, G, and B pins. Basically if you have an 80% duty cycle on Blue, that means it's only grounded 80% of the time. This corresponds to 80% brightness of the blue LEDs, then you could mix that with say 60% red and 10% green, or whatever you wanted to get a full 16 million colors. This is most easily accomplished with a microcontroller, and so I'll provide schematic and code tips for the simplest solution: an Arduino.
Schematic

simulate this circuit – Schematic created using CircuitLab
I chose Pins 9, 10, and 11 of the Arduino because they are all PWM; you can choose any PWM pins you want (denoted by ~ or # usually). Just reflect those changes in the sketch.
Arduino pins are also only capable of sinking about 40mA if I remember correctly, so you'll need to control some MOSFETs with the PWM. I find you can't go wrong with the IRFZ44N, but that's just what I've had available to me.
Arduino Sketch
How you control it is up to you; sensors, potentiometers, networked, bluetooth, constant fade pattern, there's a slew of options. So this code will tell you the necessary functions, but from there it's a matter of programming and integration of whatever else you want.
void setup(){
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop(){
  //255 -> 100%   ;   0 -> 0%
  analogWrite(9, 255); // turn red to 100%
  analogWrite(10, 0); // turn green to 0%
  analogWrite(11, 128); // turn blue to 50%
}

If this doesn't work, please let me know and I'll fix it. I forget if analogWrite is okay with being called in a simple, unrestrained loop over and over, and I also forget if Arduino pins have internal pull-downs

The line's on the strip are Power, Red, Green, Blue

Sorry, I've misunderstood! I've edited my post to hopefully better answer your question.

Note that the specs of the strip mention “Working Input Voltage: 12VDC”.

Note also that 1) The MOSFETs will invert your signal: Arduino pin HIGH → MOSFET conducting → strip line grounded → LED shines. 2) You may want to add pulldowns to the MOSFET gates, as the Arduino Uno has no internal ones: at power-up the output pins will float for about one second while the bootloader runs.

Oops, yeah I didn't even select the correct LED strip for 12V. I've also fixed the inversion issue and added pull-downs. Sorry for so many errors, Amorris, I think Edgar Bonet has caught them all now though, should be good to go.

This code only displays a bright red and a dim blue, not a teal colour or whatever colour you said it would make. If you could, please link to a page for some addressable WS2812B strips? Luckily, I only bought those for $4 :P

The PWM explanation section was just to describe PWM, sorry if that wasn't clear but it doesn't match up to the code. Modify the numbers as you see fit to get the color you want, be it teal or any other. As for an LED strip, just google 'WS2812B LED Strip', you'll find tons. WS2812B are the addressable ones, WS2812 (no B) are NOT addressable. Be careful with eBay sellers claiming they have addressable LEDs when they really don't. An alternative is SK6812 too, those are addressable.


text:
Is it wrong power supply?
I used this cheap impulse power supply, and it worked on Arduino with prototype board for some short time, but then it stopped while I felt a burning smell. Is "impulse" a wrong type of power supply for Arduino board?

On that board I had 0,96" OLED display (0,08W) connected, 3 LED's, 2 thermistors, 1 buzzer. All is working fine while powered by USB cable from laptop.

that PSU should be fine, you might have mis-wired something.

A DC power supply with the right voltage is okay, also that one. You did connect it to the barrel jack ?
The most likely reason is that your Arduino board draws too much current for the voltage regulator on the Arduino board. Suppose you have an Arduino Uno with a servo motor or a lot of leds and they require 500mA. The voltage regulator would heat up with (9V-5V)*500mA = 2 Watt.
Can you find the voltage regulator on the Arduino board ? You can check if it is getting to hot by holding your finger on the voltage regulator. If you can keep your finger on it, then it is okay.
The voltage regulator should reduce the current too prevent that it gets too hot, but it is not hard to blow the voltage regulator despite that.
The DC power supply could be bad quality and could have an output voltage that is too high or has voltage peaks, or there is a leakage current from the mains. Do you have another power supply ?
I use a good quality and certified DC power supply of 7.5V. In the photo I see all the right certification labels, but I don't know if they are real.
What was connected to your Arduino board ? If nothing was connected, then you are in trouble, and it could be faulty DC power supply or a bad Arduino board.

Voltage regulator got hot indeed at that moment. It is Arduino Uno (non-genuine), and its working until now on USB power supply.


text:
Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only
I have an Arduino Pro Mini as an ISP programmer with the ArduinoISP sketch running on it (19200 baud), and an addition in boards.txt that has a 'Standalone ATMEGA328 8MHz Internal' entry that specifies 8MHz and a bootloader file, along with some other things.
I'm trying to upload a simple blink sketch to an ATMEGA328 (not 328p, though the issue persists with that board as well) with no external components (internal clock)
The Problem
I can flash the bootloader no problem. I can also upload code the first time just fine. The problem is when I try to upload any different code after the first time, it gives a verification mismatch error at a seemingly random byte, complaining that 0xsomebody != 0xsomeotherbyte (also seemingly always different). This usually causes the sketch the stop working, and the LED to behave erratically.
IDE Verbose Outputs
Verbose output for burning the bootloader
Verbose output for first upload of simple sketch: basically Blink.ino
Verbose output for second upload of modified sketch: changed first delay to 1200 (side note: uploading an identical sketch doesn't give the verification mismatch error)
Verbose output for sufficiently different sketch (four digital writes, ie heartbeat example)
The Sketch
void setup() {
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  delay(1100);
  digitalWrite(6, LOW);
  delay(400);
}

Bootloader Files
This is the boards.txt entry that I'm using:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=19200

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

I've added this entry to Users/me/Local/Arduino/packages/arduino/hardware/avr/1.6.17 as well as Program Files(x86)/hardware/arduino/avr
Here's the HEX file for the bootloader incase that's useful as well
The Programmer
Here's a schematic of the programmer:

The solder jumper 'CAP1' is soldered closed.
And the connections to the ATMEGA328

simulate this circuit – Schematic created using CircuitLab
And lastly, a photo of the setup:
Thanks in advance

Bootloader  specs might be relevant – generally, bootloader files set the fuses as well as loading boot loader code.  ¶  For an ArduinoISP question, I'd expect to see details of what you do to keep the Pro Mini from resetting, wiring diagram, photo of setup, and verbatim pastes of commands you entered and responses you got.  Figuring out ArduinoISP problems can be difficult even with all info available first hand; trying to do it at second hand without details isn't worthwhile, IMO.

Thanks for the info! I've edited my original post to include hopefully all relevant information about my problem.

I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.
So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.


text:
Obstacle avoidance algorithm
TARGET
The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).
This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot  manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.
I will appreciate it if I could get some helpful suggestions and insights.

Pathfinding usually relies on the obstacles/path being known to the algorithm. The most basic form of obstacle avoidance is simply trying to get around it. This can be done by checking if there is an object infront of the robot, and if so, go to the right (and ocassionaly check if the obstacle is still there). Just try to program this out and then find scenario's where it makes sense to go back, to check if you can go around the left side. It can often help to think of how YOU would solve this problem if you were the robot.

In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

There is a very simple weighted index algorithm called the 'Bubble Rebound Algorithm' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.
Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.
But first I suggest you take a look at my blog post about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.
I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.
On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.

The problem
Given an unknown graph (or just world), a robot/person should be able to find a way between two points.
Pathfinding is often done on a known world, this website allows you to check out the different algorithms, which very much look like what you want to achieve.
Since you mentioned moving obstacles, you may also look at collision avoidance algorithms. But it depends on if the moving obstacles themselves also avoid collisions. To be able to avoid moving obstacles, you'll have to be able to know their location, direction and speed, to be able to calculate where you would collide (and how to avoid it). But usually, just braking whenever they get too close may just work (maybe even drive backwards if they get even closer).
The approach
So, we've got a startpoint and an endpoint. Our initial plan would be to travel straight from start to end, since this is obviously the shortest path.
But it would be ideal if there wasn't an obstacle, and for us to verify our approach, we'll just think of an obstacle. Let's say there is a wall right in front of you, what are you going to do? You can't see where it ends (I believe your robot doesn't), so you're just going to walk around it, you could choose a random way, (left or right, maybe even backwards)
What algorithm
Basically you want to get to the endpoint, so you're going to have an algorithm that has some kind of "fitness" based on how close you are to the endpoint.
You could:

Brute force: Try every single route, until you've found the way.
Right hand rule: I've heard that, in mazes, if you always hold your right hand against the (right) wall, eventually you'll get to the end.
Greedy algorithm: Just move towards the point, if you can't go any furhter, choose whatever seems to get you closer. If nothing is getting you any closer, choose the route that moves away the least.
Heuristic algorithm: Move one way, until choosing another round will be more likely to be a solution, then choose to go down another lane. Until this one seems to be leading you away.
Search algorithm, like breadth first or depth first search, check this video

Just try some of the algorithms, to see which one works best. Or try to determine/explain why one algorithm is/should be better than the other.


text:
How can I read a piezo sensor and have it output a fixed voltage?
I'm trying to creature an instrument out of a few boards I have. The plan is to have piezo sensors wait for a hit, then be read by a digital pin, then execute code based on what piezo sensor was hit.
I know how to make a note play, but I don't know how to read a signal from a piezo that's between 3V and 5V. I'm not worried about velocity measurements, I just want there to be a hit, register the hit through arduino, then relay the pin number to a track number.
I read that pin change interrupts can read a signal instantly.
Below is some example code for my audio output board that plays audio files. This specific bit of code is for "notes" on an instrument.
          wTrig.masterGain(-8);                 // Lower main volume
          wTrig.trackPlayPoly(6);               // Play first note
          delay(1000);
          wTrig.trackPlayPoly(7);               // Play second note
          delay(1000);
          wTrig.trackPlayPoly(8);               // Play third note
          delay(1000);
          wTrig.trackFade(6, -50, 5000, 1);     // Fade Track 6 to -50dB and stop
          wTrig.trackFade(7, -50, 5000, 1);     // Fade Track 7 to -50dB and stop
          wTrig.trackFade(8, -50, 5000, 1);     // Fade Track 8 to -50dB and stop

I don't have experience with code, but this is how I think activating a note would work:
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

As far as limiting voltage, don't I just need to put some resistors in circuit with the piezo sensors?
In psuedo-code, this is what I want to make happen:
Listen for signal from any pin
Store that pin number as a variable
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

A piezo will output a decaying sinusoid when you feed it an impulse (a hit on the attached surface). Problem with a high frequency sinusoid is that one: half the time it's negative, and two: it forces a near-real-time monitoring of the analog voltage there, ie no or small delays in your code.
I've made a pattern recognition 'drum' with piezos, and the general approach was to first start with plotting the analog voltage of the piezo. This is done by putting the positive of the piezo to an analog pin and the negative to ground, and a 1M resistor between the leads (this value worked for me, play with different values to see what works best). Then do a serial plot (ctrl shift L in the IDE) and observe:

how high the peak is for different distances and strengths of 'knocks'
how many times a significant peak occurs before decaying.

Your end goal is to have the Arduino recognize a peak by seeing when the analog reading is above a threshold value , then have a dead period where it ignores subsequent peaks (so it doesn't read multiple events on a single sinusoid), and then play your note. Longer dead period means less false-positives, shorter means more responsive.
I apologize for the long-windedness of my somewhat ambiguous response, I'll try to remember to paste my code when I'm at my computer tomorrow.

I actually found a tutorial on how to plot a serial plot of a piezo before, but that's as far as I've gotten. I understand what you're saying.

If the piezo is mounted to a surface, and you're hitting the surface to create vibrations, it is complicated as mentioned in the other answer, and it would be a good idea to connect piezo brass to a stable 2.5V and use rail clamping diodes on the pin.  For this purpose, you may be okay with just a couple 100 ohm resistors as a divider and a capacitor between ground and the 2.5V.  The proper audio way is more involved.
But if you're tapping the piezo directly with your finger, or tapping a thin plate and foam on top of the piezo, it's a lot simpler.  I've done this with a 100k ohm resistor in parallel (better response and consistency than 1 M ohm) and 5V zener diode in parallel for a 5V processor.  An analog pin with AnalogRead function can determine the voltage.  Brass wired to ground, center area wired to pin.  I've found that placing thin foam underneath everything gets rid of the crosstalk, especially if you don't need velocity sensitivity.
I would avoid using the delay function because it will prevent other piezos from working during that time.  Millis() calculations allow other actions to be performed.

Perhaps you could use the schema editor to enhance the answer?

Perhaps.  I searched for this schema editor (here and Google) and did not find it.


text:
Broadcast data to radius of at least 500 meters
I need to broadcast small amounts of data in a radius of about 500 meters to 2 Kms. in real time. Any compatible receiver in the range should be able to receive that data. Is there a suitable module for the same? I am considering HC-12 but don't think it can used for broadcasting data to all the surrounding receivers.

look into LoRa gateways, then use whatever MCU/software you want.

Maybe you can look into the LoPy Microcontroller, a MicroPython enabled controller, that has a 1km WiFi range. It uses the Espressif ESP32 chipset (with 802.1b/g/n 16mbps WiFi) and has Bluetooth (BLE & Classic) integrated into the board.
(Reference: https://www.pycom.io/product/lopy/)

You can use NRF2L01 2.4ghz rf tranceivers.They have a range of approx 1 km without antannae and 1.8 km with antannae.Also the ESP8266 wifi module normally has a range of 300m but can be used for the ranges you require with some big dish antannae.


text:
How to include Voltage code in 4 digit 7 segment dislay
As a continuation of my question. Here's the code for controlling the 4 digit 7 segment display:
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;
int p = 9;

int d4 = 10;
int d3 = 11;
int d2 = 12;
int d1 = 13;

void setup()
{
  //set all the pins of the LED display as output
  pinMode(d1, OUTPUT);
  pinMode(d2, OUTPUT);
  pinMode(d3, OUTPUT);
  pinMode(d4, OUTPUT);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(p, OUTPUT);

}
/***************************************/
void loop()

{
  //The 7-segment LED display is a common-cathode one. So also use digitalWrite to  set d1 as high and the LED will go out
  digitalWrite(d1, HIGH);
  digitalWrite(d2, HIGH);
  digitalWrite(d3, HIGH);
  digitalWrite(d4, HIGH);

  switch(x)
  {
    case 0:
    digitalWrite(d1, LOW);//Light d1 up
    break;
    case 1:
    digitalWrite(d2, LOW); //Light d2 up
    break;
    case 2:
    digitalWrite(d3, LOW); //Light d3 up
    break;
    default:
    digitalWrite(d4, LOW); //Light d4 up
    break;
  }
}
//The function is to control the 7-segment LED display to display numbers. Here x is the number to be displayed. It is an integer from 0 to 9
void pickNumber(int x)
{
  switch(x)
  {
    default:
    zero();
    break;
    case 1:
    one();
    break;
    case 2:
    two();
    break;
    case 3:
    three();
    break;
    case 4:
    four();
    break;
    case 5:
    five();
    break;
    case 6:
    six();
    break;
    case 7:
    seven();
    break;
    case 8:
    eight();
    break;
    case 9:
    nine();
    break;
  }
}
void clearLEDs() //clear the 7-segment display screen
{
  digitalWrite(a, LOW);
  digitalWrite(b, LOW);
  digitalWrite(c, LOW);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
  digitalWrite(p, LOW);
}

void zero() //the 7-segment led display 0
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, LOW);
}

void one() //the 7-segment led display 1
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void two() //the 7-segment led display 2
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, LOW);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void three() //the 7-segment led display 3
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, HIGH);
}

void four() //the 7-segment led display 4
{
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void five() //the 7-segment led display 5
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void six() //the 7-segment led display 6
{
  digitalWrite(a, HIGH);
  digitalWrite(b, LOW);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void seven() //the 7-segment led display 7
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, LOW);
  digitalWrite(e, LOW);
  digitalWrite(f, LOW);
  digitalWrite(g, LOW);
}

void eight() //the 7-segment led display 8
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);
}

void nine() //the 7-segment led display 9
{
  digitalWrite(a, HIGH);
  digitalWrite(b, HIGH);
  digitalWrite(c, HIGH);
  digitalWrite(d, HIGH);
  digitalWrite(e, LOW);
  digitalWrite(f, HIGH);
  digitalWrite(g, HIGH);

My problem is how to include the voltage code here? Here's the code for voltage code:
    /*
* Display5vOrless sketch
* prints the voltage on analog pin to the serial port
* Warning - do not connect more than 5 volts directly to an Arduino pin.
*/

const float referenceVolts = 5.0; // the default reference on a 5-volt board
const int batteryPin = 0; // battery is connected to analog pin 0

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

void loop()
{
 int val = analogRead(batteryPin); // read the value from the sensor
 float volts = (val / 1023.0) * referenceVolts; // calculate the ratio
 Serial.println(volts); // print the value in volts
 delay(500);
 }

Please help me! Thank you!

Are you sure you want to merge them before they are working? Check them first then try to merge them yourself. How would you go about that? Describe your reasoning. Then and only then ask for help.

Isn't there a library for this, im thinking there is some steps that you need to cover before it will work.

Yes you can display single digits what happen when you want to display double or triple digits. You need a code that can handle that. You need to cut up volts an iterare over it. Anyway create a class that takes volt and return it on the display. That's what you you need to do to merge that code. Are you up for that? Or are you gonna find a library that can handle that?


text:
What happens if we connect GND and +5v?
What will happen if I by mistakenly connect GND and +5v of an Arduino Nano? Is there any protection for it? Or will it get short and fry out something?

You'll probably fry the voltage regulator, I don't believe it's protected.

How to check whether its fried

The Magic Smoke™ will escape.

Actually, I have really burned my Arduino Nano and What should I do I don't know

And my CH340G was smelling

Throw it away and get a real one.

if you're handy with SMD work, you can swap out a blown regulator or diode on an MCU

One more thing I programmed it to behave as a voltage regulator and I was saying it send data to my PC Now when I plug it with a battery first the tx and led get really high for a sec and then tx stays on for sometime then it stops and then the led starts blinking very fast and after a few secs it gets dim

It maybe the Ch340g or the diode

I think I burned my CH340G because yesterday when I plugged it into my computer there was Hardware named Ch340g in the coms but after issue it isn't there and even it was even smelling quite a bit !

Depending on how you are powering your board different things will happen.

If you are powering through USB from a PC the PC should, according to the USB standard, detect an over-current situation and disconnect the power from the port. However some don't, in which case see point 2.
If you are powering through USB from a USB power supply (phone charger, etc) the charger's output voltage will drop to near zero and the current will hit maximum for the supply. This may or may not damage the supply, but either way it's not a nice thing to do.
If you are powering from a small external battery (say a 9V PP3 battery) things will start to get hot. The voltage regulator will most likely overheat, the battery may overheat, but not much damage should occur - a small PP3 battery can't provide much current.
If you are powering from a large external battery (e.g., Li-Ion cells) or an external power supply, things will get more nasty. The on-board regulator will overheat. If it isn't thermally protected (genuine Arduinos should be, but cheap Chinese clones may not be) then it will fail and you will find smoke coming out of the regulator. At this point the regulator is dead. If the board contains a polarity protection diode that may fail in the same way (I have seen these blow clean off the board before). Physical damage (blackening and blistering) may occur to the PCB as well.

So all in all shorting +5V to GND is never a good idea.

According to this image and this datasheet, that nano's voltage regulator is internally limited.
That means it will heat up and shut down if over-loaded. Of course, your nano could use a less-effective regulator and simply smoke away. It's also possible that the 5205 would not clamp in time to prevent damage on an instant dead-short. Generally, i've found the arduino boards to be fairly resilient, compared to other MCUs, so you can probably get away with it at least a time or two.
Dead shorting is never a good idea even if you can get away with it because there can be incremental (as opposed to catastrophic) damage. You might cause instability in the regulator, and you might limit it's ability to limit volts. Those problems might not be revealed instantly, but instead at the worst (unexpected) time.
EDIT:
based on your edit, it sounds like your "FTDI" is fried, but not necessarily your MCU.

I think I burned my CH340G because yesterday when I plugged it into my computer there was Hardware named Ch340g in the coms but after issue it isn't there and even it was even smelling quite a bit !


text:
How to make a 5-volt relay work with NodeMCU?
I have hooked up 2 channel 5-volt relays with NodeMCU v1.0 as shown in the fritzing below.

Relay are powered with a different power source than NodeMCU.
As of now, I am powering the NodeMCU from my laptop and the relay board from a 5-volt battery.
Below is the code I have written:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, HIGH); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, HIGH); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}

When I execute the URL: 192.168.1.8/relay1 the outputLed blinks as per the logic in turnOnRelayOne.
But neither of the relays turns on. Please help.

Im not sure but it looks like it's not a closed circuit, the 5 volt. I wonder if the ground from the 5volt outlet could be split up, one for NodeMCU and one for the relay. Then you would have a closed cuircuit between the relay and NodeMCU.

all what you need to do is connect the g on the relay to g on the esp8266 and the battary

Simply connect the Vcc of the relay to 3V of NodeMCU.It's working for me.

I have several of these modules. They have an optional opto-isolator built-in, but you have to remove the jumper to use it.

Connect your GPIO trigger as you have it
Run the relay's Vcc and Gnd pins to the MCU, not the power plug.
connect the power plug's +5v to the left-most pin, where the jumper once stood: JDVcc
connect the power plug ground to the MCU or the open common Gnd on the left-group of pins.

Now your relay coil(s) will be powered by the 5v plug, but the relay's logic and control are handled by the MCU.

Can you please elaborate the last connection in your answer, possibly share a fritzing diagram also?

a diagram will take me a while, i'm swamped at work, but it's a common ground on that last connection: as long as the OP's black wire connects to either GND on the relay or a gnd on the MCU it's ok.

Just to confirm, the ground from the 5V supply could either be connected to the second ground (the one beside JD-VCC) on the relay or to a ground pin on the MCU. Correct?

right, the GNDs on the relay module (and MCU) have continuity, so those options behave identically.

The relay has no reference for what the voltage from the NodeMCU is. Since the power supplies of the two devices are isolated (from each other; the laptop may not be isolated itself, but the battery certainly should be) you can (and in fact must) connect the grounds of the relay board and the NodeMCU together. If neither power supply is isolated or if you are unsure if they are isolated then you should use an optoisolator in order to prevent potential power issues.

I believe the problem could be that the relay is 5v but the signal coming from the NodeMCU is 3.3v. You may need do something like boost the signal to 5v or implement a logic level shifter, for example.
Here's a related post:
https://electronics.stackexchange.com/questions/213051/how-do-i-use-a-5v-relay-with-a-3-3v-arduino-pro-mini

That is not the case, IMO. The output of the NodeMcu is not driving the relay but driving a transistor/fet/optocoupler. In all cases, 3.3V is perfectly valid to turn on. @Ingacio is correct, the grounds must be connected. Now only one wire is the connection between the NodeMcu and the relay. "Voltage" is defined as a difference between two potentials, hence one wire is not enough.

How are you powering your ESP-12E?  This is not included in your diagram. I have had success using the VU pin (5V output) when powering from the Micro-USB.  You would then connect VCC to VU, GND to GND, and Signal to your GPIO4.  If you are powering your ESP-12E from a 5v power supply directly into the VIN pin, then I would power the Relay from the same 5V power supply.  you would connect the + from the power supply to VIN (ESP) and VCC (relay) all the grounds tied together then the GPIO4 to Signal.

This relay module works differently.
It is on when the signal is LOW and it turns off when the signal is HIGH (3v3V on the NodeMCU)
So you only need to modify the code in the two functions to be LOW instead of HIGH
Also make sure the NodeMCU and the relay module have a common ground.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, LOW); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, LOW); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}

Hm, can you infer from that drawing the actual type of the relay module? Many modules wok using positive logic, i.e. setting input high turns the relay on.


text:
Passing a substring to a function or sub
I'm trying to send each character of a string object to a subroutine. I'm using the following code to do this, but it doesn't work:
string sInput = "some text"
for (int i=1; i < sInput.length(); i++) {
  showLetter(sInput.substring(i, i));
}

Subroutine:
void showLetter(String sInput)

My belief is that this should be iterating through the string and selecting one character (not to be confused with a char) at a time and sending it to the subroutine.
I haven't used C++ for 30 years and I am having difficulty finding why this won't work. I understand that I could use a char array, but I wanted to use this method.
If C++/Arduino coding doesn't work this way, to get credit you MUST explain why not.
Any help would be appreciated.
entire code follows...
/*
visual morse code

a dot is 1 unit
a dash is 3 units
  space between parts of the same letter is one unit
the space between letters is 3 units
the space between words is 7 units
*/

void parseString(String sInput);
void showletter(char sInput);
void dot(void); //dot
void dash(void);  //dash
void letterSeparator(void); //between letters
void wordSeparator(void); //space
int baseUnitLength = 100;

// the setup function runs once when you press reset or power the board
void setup(){
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop(){
  //call a routine with a string.
  //the routine parses the string and blinks the dot and dash for morse code for each character

  parseString("sos ");

  //showLetter("s");
  //showLetter("o");
  //showLetter("s");
  //showLetter(" ");
}

void parseString(String sInput)
{
  for (int i=1; i<sInput.length(); i++){
    showLetter(sInput.substring(i,i));
  }
}
void showLetter(String sInput){
  if (sInput == "a")
    {
      dot();
      dash();
      letterSeparator();
    }
  else if (sInput == "b")
    {
      dash();
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "s")
    {
      dot();
      dot();
      dot();
      letterSeparator();
    }
  else if (sInput == "o")
    {
      dash();
      dash();
      dash();
      letterSeparator();
    }
  else if (sInput == " ")
    {
      wordSeparator();
    }
}
void dot(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void dash(){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(baseUnitLength * 3);
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength);
  }
void letterSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 3);
  }
void wordSeparator(){
    digitalWrite(LED_BUILTIN, LOW);
    delay(baseUnitLength * 6);
  }

If you write "to get credit you MUST explain...", then it is likely you won't get any response. People here are not answering for credits, they answer because they want to help.

"It doesn't work" isn't exactly helpful either...

If you haven't been working with C++ for 30 years, then you are totally outdated with the language as it stands today. I'd suggest you update your knowledge first. Also, regarding your question, if you had taken a look at String API in Arduino reference, then you would have found out what are the problems with your code.

@dda - i'm sorry if my description of the result is unacceptable.  I quite frankly do not what else to say.  The issue is clearly in the for loop in the code.  When executed it does nothing. No blinking, Nothing. I assumed people who have worked with and know arduino/C++ would either know why this doesn't work or would attempt to recreate a situation where it does.  Sorry, but that's all I have.

So here is the answer you did not find in the Arduino reference https://www.arduino.cc/en/Reference/StringSubstring for 2nd argument: to (optional): the index to end the substring before Note the "before" mention, which mean substring(i,i) will always be empty as it should be substring(i,i+1). And this is actually NOT a C++ question, but only an Arduino API question.

@jfpoilpret I thank you very much for your help. The arduino example i read, references 5 characters, but the substring method/function returns 4.  i don't understand why I have to +1 the second parameter and it isn't clearly stated that this is what you have to do nor why you have to do it.  the documentation clearly states, "with two parameters looks for a given substring from the first parameter to the second." That's not very clear, to me, in regards to positional reference and not how other languages do it.

It is very common. This is called a "semi-open" range, which is how the STL (Standard Template Library) also does it. See, for example, a Stack Overflow post. Without a semi-open range it is impossible to pass an empty range. The documentation for substring is very clear on this point: the optional ending index is exclusive (the corresponding character is not included in the substring).

Mr. jfpoilpret provided me with the answer and should be credited, as such.
It appears the subString function needs to have 1 added to the second parameter in order to properly reference the number of characters you need in the String.
In my case, iterating through a String and referencing only one character at a time means I need to do the following sInput.substring(i,i+1)
Also, the String object uses a zero based index.
EX:
   String sString = "This is a peach.";
   sString.substring(0,4)     //should return "This"
   sString.substring(8,9)     //should return "a"
   sString.substring(15,16)   //should return "."
In addition, you could also use the String function charAt (EX: sString.charAt(i)).
The charAt returns a char and if you are passing it to a function/sub you need to make sure the function/sub is expecting a char data type.
Also, it is easier to use a switch case when using the charAt function, as you don't have to do a conversion from String to char, as switch case does not work with Strings.

I understand you are trying to learn stuff, but what you are doing is highly inefficient. On a microcontroller memory is short, and the String library in particular tends to fragment memory. Your technique of breaking up a String into individual single-character String objects is the very thing that is likely to fragment memory. You are much better off converting it to an array (using c_str) and then indexing into that in the usual C way.

You got your answer, and you understood how this works. However, your
sentence “It appears the subString function needs to have 1 added to
the second parameter [...]” makes me believe you find this behavior
somewhat contrived, whereas it should be intuitive to any C or C++
programmer.
As I think this may help, I will share here the mental picture I use for
thinking about array indices. I call it the “L-shaped cursor”, and it
goes like this:
An array index can represent two different things:

a particular cell within the array
an “edge” of a cell, i.e. either the limit between two cells or an
edge of the whole array.

This is depicted in following picture of an array of length N, where
the numbers above it are the edge indices and the numbers below are the
cell indices. i and j are just two particular indices:
0   1   2           i           j               N
┌───┬───┬───┬───────┰───┬───────┰───┬───────┬───┐
│   │   │   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  ┃   │  ⋅⋅⋅  │   │
└───┴───┴───┴───────┺━━━┵───────┺━━━┵───────┴───┘
  0   1   2           i           j          N−1

Since each index can represent two things, I like to think about them as
being L-shaped cursors, like the ones I've drawn in bold for the indices
i and j.
Now, if you think about the purpose of the substring() method, it's
job is to cut a slice along the string, and you need to tell it where to
place the “knife”. Since the knife will cut along edges, it's perfectly
natural to use edge indices for that. Then
someString.substring(i, j)

will give you the slice of the string that lies between the edges i
and j. Looking at the picture above you can see this includes the cell
numbered i but not the one numbered j.
I hope this picture helps you find the behavior of substring() more
natural now. It does help me avoid fencepost
errors.

Very nice and I thank you for the information.  you hit the nail on the head in your first paragraph.  I'm used to higher level OO languages and scripting code where this is never an issue. So to me, it appears somewhat odd. But, it makes sense once it was explained.  I took C++ forever ago because it was required but I haven't touched it since.

I would suggestion the following:
String sInput = "some text";

void showLetter(char c);

for (int i = 1; i < sInput.length(); i++) {
  showLetter(sInput[i]);
}

Rewritten using C/C++ strings (null-terminated character vector):
const char* sInput = "some text";

void showLetter(char c);

for (int i = 1; i < strlen(sInput); i++) {
  showLetter(sInput[i]);
}

And slightly more efficient:
const char* sInput = "some text";

void showLetter(char c);

const char* sp = sInput;
char c;
while ((c = *sp++) != 0) {
  showLetter(c);
}

The next step is to move the string literal to program memory to reduce the amount of RAM needed.
Cheers!

Mikael - thank you for the attempt, but I understand chars and char arrays and how to pass by value and reference.  However, what I'm looking for is an answer to why, what I am trying to do, doesn't work.  To me the substring function appears to return a string object that I should be able to pass to a function/sub expecting a string as an argument.  But, it doesn't seem to be working.

Could you elaborate on "But, it doesn't seem to be working". Is that a compile or run-time error? Are the parameters to substring() correct?

no errors. the application compiles and loads into the arduino Uno, but produces no output.  I guess I could have been clearer on that point.


text:
How to read NodeMCU GPIO pin status?
I am setting up a page on NodeMCU running as a web server and I want to be able to turn on and off a light based on the url being clicked.
I want to know how I can get the status so that I can set the URL based on the pin status as well as pass  the GPIO pin status in the JSON from the NodeMCU web server.
The code is here.

Independent of the setting of port direction (input or output), pin can be read through the digitalRead():
int pin_light = 3;
int status = digitalRead(pin_light);

The OP said he has a NodeMCU board. Those runs Lua code. Your example seems to be C-code and would not work on a NodeMCU unless you "reflash" it to standard Arduino C-code. Reading a pin on NodeMCU should be gpio.read(PIN)

The OP said he has a NodeMCU board. Those runs Lua code. Your example seems to be C-code and would not work on a NodeMCU unless you "reflash" it to standard Arduino C-code. Reading a pin on NodeMCU should be gpio.read(PIN)

You are rigth, but question refers an example with code and C and it is tagged with C :blink:


text:
how to send argument to ESP8266WebServer objects on function
this probably simple thing to do however I can't think of a way to pass argument to function call
ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }

  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

in the above function where I am calling toggleRelayOne using server.on("/relay1", toggleRelayOne); I want to be able to pass relay id so I can use same function to toggle multiple relays.

server.on ( "/", handleRoot );
why it used??

When a user tries to navigate to "/" I call a function  handleRoot . This function reads the data from sensors connected to ESP826.

Use server.arg() to pass commands from the web as GET params:
digitalWrite (5, relay1);
becomes
digitalWrite (server.arg("pin").toInt(), relay1);
where the URL is something like http://192.168.1.5/relay1?pin=15
Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.


text:
Why is the BLE device not starting on my Arduino Pro Mini?
I recently purchased a 5V arduino pro mini that I now wish to connect to a BLE device.
I firstly tried the BLE device with my Uno board and it worked very well! However when I now try to use it on my mini it does not start.
This is my wiring:
First I connect the pro mini to the uno in order to upload the code looking like this:

Arduino Mini Pro to Arduino Uno
RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

Then I wire the mini to my BLE device (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up):

Arduino Mini Pro to BLE nRF8001
13 --> SCK
12 --> MISO
11 --> MOSI
10 --> REQ
9 --> RST
2 --> RDY
GND --> GND
VCC --> VIN

When I connect this setup to the computer the arduino uno starts and also the pro mini (both has LED lights on). I upload a simple test code that worked when i tried it with the uno but the BLE device does not respond (it seems like it does not turn on) when i use it with the pro mini.
Any idea what might be wrong? I have my board put as: Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz).
Thanks a ton!! :)

This is my wiring: First I connect the pro mini to the uno in order to upload the code looking like this:

Arduino Mini Pro to Arduino Uno

RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

How would this work? The bootloader in the Uno and Mini Pro will both try to reply. You need a FTDI or a USB-to-UART module instead of the Uno. Alternatively, start by programming the Uno to act as a USB-to-UART converter using Serial and SoftwareSerial.
Cheers!

I saw the connection from this thread: http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS Check under "Step 1". I also found this thread that has similiar connection: http://www.instructables.com/id/Uploading-sketch-to-Arduino-Pro-Mini-using-Arduino/?ALLSTEPS

But maybe it will not work to use the Uno as a "code-uploader". I have this at home also: https://www.youtube.com/watch?v=59VHCXNxSvQ Check minute 1.56. I have the red one. Would that work with the Pro mini?

The second link is fine. The MCU on the Arduino Uno is removed and the board is used as a USB-to-UART. The first link is an SMD AVR MCU and the trick might be the 3.3V setting. The Mini Pro is using 5V.

Ah ok. I do not have a big MCU/Atmel on my current arduino (i got a chinese copy) and i assume it will be hard to remove it. Did you see the youtube-video, do you think that could work with the pro mini to upload code? It has GND, RXD, TXD and VDD pins

Use a simple software serial read/write though sketch on the Uno as I suggested. https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

Yeah could do that but I would prefer to use the USB if it works. When I connect it to my pro mini both light up when i insert the usb to the computer.  Seem to have a little bit of a problem to upload code though

Looking at the schematics for the Uno it might be possible to force the MCU to disconnect by putting RST to GND. The issue is then to get the signal from the USB MCU to the Mini Pro. Alternatively a manual RST signal for the Mini Pro before upload. This depends on your Chinese copy. Would need the schematics or picture of the board to determine that.

Picture: http://imgur.com/a/cQj1w where you can see my Uno, Mini pro, FTDI module and also another FTDI module CALLED Crius. it says 3.3V and 5V on the back of it with the pins: GND, CTS, VCC, TXO, RXI, DTR

Use the blue FTDI module marked FTDI TOOL. It is made to plug into the Mini Pro directly! Check the pin marking. Why use the Uno? You have perfect tools for the job!

I actually just find it hidden in my box when I went to get a few more cables! Terrific :) Thanks a lot for all your help!

When it comes to board-settings, should I still use Arduino Pro Mini?

Yes, the Arduino IDE setting should be the target board. In this case the Pro Mini. Check frequency (8 or 16 MHz) and voltage (3.3V or 5V).

Actually you connect the Bluetooth module and connect it so that you can upload over Bluetooth. Google will help you find info about that :)

The ftdi tool indeed works very well! I just spent 2 hours finding the correct driver for it but finally got it working

Nice! Here are three links if you want to upload over the Bluetooth module; https://create.arduino.cc/projecthub/YoussefSabaa/arduino-bluetooth-programming-shield-wireless-upload-code-1a397c,  https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth and simplest https://www.itead.cc/blog/upload-program-to-arduino-with-bt-shield