text:
arduino web client uploading data to mysql database
I have got this quick sketch that post data to mysql db using php add.php module.
#include <SFE_BMP180.h>
#include <SPI.h>
#include <Ethernet.h>
#include<dht.h>
dht DHT;

// You will need to create an SFE_BMP180 object, here called "pressure":
SFE_BMP180 bmp;

#define DHT11_PIN 2

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
char server[] = "192.168.1.3";

EthernetClient client;
byte php_server[] = {192 , 168 , 1 , 3};

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000; // READING INTERVAL

String data;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  if (bmp.begin()) {
    Serial.println("BMP init Success");
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  char status;
  status = bmp.startTemperature();
  if (status != 0) {
    delay(status);
    status = bmp.getTemperature(tempInC);
  }
  else Serial.println("error retrieving temperature measurement\n");

  humidity = DHT.humidity;
  data = "?temp1=" + String(tempInC) + "&hum1=" + String(humidity);

  if (client.connect(server, 80)) {
    Serial.print("connected. My IP is ");
    Serial.println(Ethernet.localIP());
    client.println("POST /arduino/add.php HTTP/1.1");
    client.println("Host: 192.168.1.3");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
  }
  else {
    Serial.println("connection failed");
  }
  Serial.println(data);
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  delay(300000); // WAIT FOR A WHILE BEFORE SENDING AGAIN
}

but its not updating the database, using the below add.php file from arduino web-client.ino
<?php
        include("connect.php");

        $link=Connection();

        $temp1=$_POST["temp1"];
        $hum1=$_POST["hum1"];

        $query = "INSERT INTO `tempLog` (`temperature`, `humidity`)
                VALUES ('".$temp1."','".$hum1."')";

        mysql_query($query,$link);
        mysql_close($link);

        header("Location: index.php");
?>

i checked in mysql prompt which is also the result displayed if I open the server url : 192.168.1.3/arduino/index.php
mysql> select * from tempLog;
+---------------------+-------------+----------+
| timeStamp           | temperature | humidity |
+---------------------+-------------+----------+
| 2016-11-28 11:50:37 |           0 |        0 |
| 2016-11-28 12:30:25 |           0 |        0 |
+---------------------+-------------+----------+
2 rows in set (0.00 sec)

I don't know how the first entry got created but second one I created by manually executing the url 192.168.1.3/arduino/add.php?temp1=26.64&hum1=18
the index page is showing he data from db as shown above in sql, that means connection is established and mysql and table is fetched from correct db. i.e. arduinoSensorData  in my case.
my serial monitor window got updated:
BMP init Success
connecting...
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.64&hum1=18
connected. My IP is 192.168.1.131
?temp1=26.57&hum1=18

which means arduino is not able to put data to db using add.php

When you manually executed the command it didn't write the temp&hum to the DB.  So you have a fundamental problem on the server side, before you even start involving an Arduino.  (Are you sure its not a firewall issue?)

I know on my router I have firewall turned off

I would suggest, that you give IP as another Parameter to the add.php and the insert-statement. With this you could test from where the call is made. If it is also 0. Then you got either a problem with the firewall as Matt stated, or it can be a probleml with the Variables of the add.php. (I don't know php so good)

POST data doesn't need a ?. Also you can't get GET parameters (from URL), from the $_POST variable.

yes, yesterday I realized and fixed it. thanks

I came to learn in my php code posted above, I am using $_POST variable when I should rather be using $_GET
In the PHP script, there are $_GET and $_POST variables that contain the data passed to the script, depending on the method used to to activate the script.
so using $temp1=$_GET["temp1"]; and $hum1=$_GET["hum1"]; fixes the problem.


text:
Why do I get access denied when I do have mysql root user added to grant all privileges?
I am using the below mysql example sketch to upload data directly to mysql db.
#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress server_addr(192, 168, 1, 3);
//char server_addr[] = "192.168.1.3";

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

char user[] = "root";
char password[] = "secret";
char INSERT_SQL[] =
 "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

void setup() {
  Ethernet.begin(mac_addr, ip);
  Serial.begin(9600);
  delay(1000);
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password))
  {
    delay(500);
    Serial.println("Connection Successfull,inserting to database.");
     /* Write Hello, World to MySQL table test_arduino.hello */
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

I am getting the error in serial Monitor:

Connecting...
Error: 76 = Access denied for user
  'root'@'192.168.1.177' (using password: YES).
Connection failed.

even when I have all prvialages on root user for the ip of client !
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT host FROM mysql.user WHERE User = 'root';
+---------------+
| host          |
+---------------+
| 127.0.0.1     |
| 192.168.1.177 |
| ::1           |
| localhost     |
| raspberrypi   |
+---------------+
5 rows in set (0.00 sec)

I ran the following query :
mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

and got the below result !
+-----------+----------+------+------------------+
| ip        | hostname | port | current_database |
+-----------+----------+------+------------------+
| localhost | ceres    | 3306 | test_arduino     |
+-----------+----------+------+------------------+
1 row in set (0.00 sec)

however I am trying to access the test_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have 192.168.1.177 as well ? if so How do I insert ip to database test_arduino ?
then what am I missing ? please help.

Did you do flush privileges; after grant?

Yes off course , I did flush permissions.

Try to investigate if this is the case.

How do I check on stored procedures ? I also later grant on 'root'@'%' which shows up in list of host shown above. But I m not sql guy don't know how to get rid of host from above list like raspberrypi host is not even there, I just realised ceres host is missing

For that you can find notes here and here.

Are you sure there isn't a firewall issue here?

Well, @Gerben if that was a firewall issue I would have not got that error message in serial monitor

My last bought w/:mysql access denied" had to do with where I was logging in from.  Perhaps you can check by using the same credentials on the machine you are running mysql on.  If that works, then start looking at how you have setup the mysql security w.r.t. "trusted" IP addresses. (oh, I see you tried 'root'@'%'.  Just the same, try logging in from the mysql host machine anyways.)

@Chupo_cro i do not see any precedure definer if I run the command , show procedure status; however I ran the query SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database; while test_arduino database selected, and it did not listed 192.168.1.177 ip from which I am trying to insert !

I finally figured out
By default it may proabbly have an IP address 127.0.0.1 bind to the 3306 port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP 192.168.1.145. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP 192.168.145 bind to 3306 port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN.
Then you login to mysql server , and create a user :
CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then you grant privileges as shown below.
GRANT ALL ON *.* TO 'myuser'@'192.168.156';
GRANT ALL ON *.* TO 'myuser'@'%';

Important Note:  the ip address shown in above mysql queries 192.168.156 is the ip address of my ethernet client establishing connection with database on mysql remote server.
Thats it.

source: Stack Exchange

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

sort: votes


text:
I am having trouble with fading two LEDs
I've tried to modify this code, but everything I tried failed.
Where am I going wrong?
All I want to happen is when button 1 is pressed LED 1 fades up and when released LED 1 fades out and the same again with the 2nd LED when button 2 is pressed LED 2 fades up and when released it fades out.
int ledpin = 10;
int ledpin1 = 11;
int pushbutton = 7;
int pushbutton1 = 8;

int brightness = 255;
int fadeamount = 1;

void setup ()
{
  pinMode (ledpin,OUTPUT);
  pinMode (ledpin1,OUTPUT);
  pinMode (pushbutton,INPUT);
  pinMode (pushbutton1,INPUT);
}

void loop ()
{
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in ledpin
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out ledpin
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);

  }

  if( digitalRead(pushbutton1)==HIGH && brightness<255 )
  {
    // fade in ledpin1
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin1,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton1)==LOW && brightness>0 )
  {
    // fade out ledpin1
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin1,brightness);
    delay (1);

  }

}

Create 2 sets of brightness, fadeamount variables, one for each button/LED. You can put them in a struct to make things simpler:
struct brightness {
    int brightness;
    int fadeamount;
    int ledpin;
    int pushbutton;
};

struct brightness set1;
struct brightness set2;

Then initialize them in init.
The LED goes from full brightness to off in 0.255 seconds. That is pretty quick.
You can add a millis() based timer on the brightness change:
struct brightness {
    int brightness;
    int fadeamount;
    int ledpin;
    int pushbutton;

    //add the following
    unsigned long timeChanged;
    unsigned long timeBetweenChanges;
};

void handleButtonFade(struct brightness* set){
      if( millis() - set.timeChanged < set.timeBetweenChanges)
          return;

      if(digitalRead(set1.pushbutton)==HIGH && set.brightness<255 )
      {
        // fade in ledpin
        set.brightness = set.brightness + set.fadeamount;// increase brightness
        if( set.brightness>255 ) // check that brightness doesn't exceed 255
          set.brightness = 255;
        analogWrite(set.ledpin,set.brightness);
      }
      else if( digitalRead(set.pushbutton)==LOW && set.brightness>0 )
      {
        // fade out ledpin
        set.brightness = set.brightness - set.fadeamount;// decrease brightness
        if( set.brightness<0 ) // check that brightness doesn't go below 0
          set.brightness = 0;
        analogWrite(set.ledpin,set.brightness);

      }

}

void loop(){
    handleButtonFade(&set1);
    handleButtonFade(&set2);
}

Small Change in these lines :

if( digitalRead(pushbutton)==HIGH && brightness<=255 )
else if( digitalRead(pushbutton)==LOW && brightness>=0 )

Also change delay to delay(10) something, instead of delay(1). Only then, human eye can observe that change in brightness from 0-255 :-)
Also adding a capacitor to reduce the debounce in your pushbutton would be a thing to do.

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


text:
Sending servo position data from one Arduino to another
I'm trying to take the position data generated from this servo sweep, and send over serial to another Arduino. The position data is stored as pos in the code I included, what would be the best method for doing this?
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

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

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

How about to just send it over serial? You seem to already have decided, that you want to use serial, so why don't you just do it? Is there a specific problem?

would it just be a basic serial.read() and serial.write command?

Yes that's all you would need. You'd be sending two bytes over, so the receive side would  have to deal with that.

you posted code that has nothing to do with your question ... your question is about sending data from one arduino to another arduino ... you posted code that positions a servo

When using bytes for location (0-180 degrees), you can simply use: myservo.write(pos);myserial.write(pos); and on the receiving side myservo.write(receivedValue); (check some tutorials on how to receive a value.

@jstolat - no, as the question clearly states, they want to add communication to the provided code.  It is very much relevant, as it is the starting point.

Yes, sending data over Serial is as simple as using Serial.write() or it's siblings. When sending data over Serial you have to consider, how you want to send it.

Raw binary data: You can simply use the Serial.write() command, which will send the variable as binary data. If you whatch this on the serial monitor of your PC, you will not see readable numbers, because what is shown there is interpreted as ASCII-encoded data, where every byte value has a corresponding character (for example the value 97 is the letter 'a'). On the other Arduino you just use Serial.read() to write the byte data directly to a variable. This is practical, if you are sending always the same amount of data (like the value of one sensor). If the length of a message is variable, you have to use a delimiter, to mark the end of a message. Here the second way is more save.
ASCII encoded data: You can send your data human readable as ASCII encoded data. The value 128 then would consist of 3 bytes, one for each character. Here you always have to use a delimiter, so that the receiver can tell the values apart. A common message delimiter is the newline character '\n'. On Windows you also often have newline and carriage return '\r' together. For decoding you can use one of the many functions, that convert a string/character array to a number with the wanted format (in your case integer), for example atoi().

Refer to the Serial examples in the Arduino IDE to see the code in action.
Note: Since the value of pos only varies between 0 and 180, you can use one byte to save and transmit it, instead of the 2 bytes the integer uses.

Actually, that simple binary method is limited not to fixed-length messages, but rather to single-word messages.  If you want to send longer messages, regardless if they are fixed length or variable, you need a mechanism to achieve at least initial synchronization to indicate the start of a word.  Time gap is the weakest such method, reserved or escaped codes etc are more robust but complex.  ASCII encoding with a delimiter (especially a newline) does indeed become attractive, and is readily observed in a terminal as well.


text:
Float magnet switch interrupts atmega328p and RN2483 sends data
It was so easy to my mind but it is really not. I have a float switch which goes high when water is floating. So I connect the switch to INT0 pin of MCU. So when water is not floating everything is OK. When the water is floating I send data. I declare the interrupt as follows:
attachInterrupt (digitalPinToInterrupt (switch), float, RISING);

Where float is
void float()
{
detachInterrupt(0);
digitalWrite (LED, HIGH);
txReturn = myRN.txCnf("1");
}

And my main loop is
attachInterrupt (digitalPinToInterrupt (BUTTON), switchPressed, RISING);
digitalWrite (LED, LOW);
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

I can't understand why my led is not going LOW and why I interrupt is useless after the first successful time. I am aware that I must keep interrupts routines short and by txReturn.txCnf("1"); I don't but I can not understand where my logic is wrong.

txCnf might itself depend on interrupts. So your code will hang. Set a Boolean flag in the interrupt routine. The in the loop, if the flag is set, send the data and clear the interrupt.

float switch which goes high .... what do you mean by goes high? .... switches usually open or close

float is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water.  Try calling it something else.
Also, instead of detaching and reattaching the interrupt, use a state machine.  When the interrupt is triggered, you will be able to run different code in the main loop.
unsigned int state;
void setup(){
  state=1;
  attachInterrupt(0,changestate,RISING);
}
void loop(){

switch (state) {
case 1: // do something
// add code here
break;

case 2: // do something else
// add code here
break;
}
}

void changestate(){
if(state==1){state=2;} // interrupt changes state
}

Okay your approach makes more sense and seems to be more efficient. I' ll give it a try.

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


text:
Waveshare Display on ESP32 has weird graphic glitches
I am trying to pass an image to the display through the GxEPD module. I tested the display and its working fine with an example sketch.
I am using a WEMOS LOLIN32 and a 7,5" B/W Waveshare display.
When I add any other image after converting it to hex values, this happens:
This is the image in GIMP:

And this is what the display shows:

As you can see, the display shows the image glitched a lot. It looks a lot like each "row" of a few pixels is mirrored horizontal. The question here is: Why? All I did was converting the image in GIMP to .xbm, taking the content, stripping whitespace, pasting the Arduino syntax around the code and replacing the example file with this one.

looks like a mixup between LSB and MSB encoding

yea, i thought so too, but i dont know how i can effectively solve this - i could include this in my python script im using for formating the code, but i wish there was a simpler fix for that

looks like poor software rescaling to me, are you sure the resolution is correct?

i changed the size of the image to exactly the pixels that were named in the article description - it should definetly be right, i tried making the image a few pixels smaller to see what happen, but that turned the image into an unreadable mess even more.

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


text:
How do you make a stepper motor move in accordance to earthquake data using arduino?
I am new to arduino. I can import the acceleration data from a text file into arduino and I can also make the motor run at that acceleration with a distance calculated from an equation. I use the AccelStepper library but I notice that per acceleration data, the motor stops abruptly and moves  again in a very short delay, causing a lot of vibrations. Is there any easier way to make a stepper motor run with acceleration values from a text file?
The text file is also placed on an SD card, and I use the function Serial.parseFloat() to get the data from the file.
Here is my code:
#include <SPI.h>
#include <SD.h>
#include <AccelStepper.h>
int STP = 4;
int DIR = 3;
const int chipSelect = 53;
double Acceleration = 0;
double Previous_Acceleration = 0;
double Velocity = 0;
double Previous_Velocity = 0;
double Distance = 0;
double Previous_Distance;
AccelStepper stepper(AccelStepper::DRIVER,STP,DIR);
void setup(){
  pinMode(STP,OUTPUT);
  pinMode(DIR,OUTPUT);
  Serial.begin(38400);
  Serial.println("Starting Program");
  delay(1000);
  while (!Serial){
    ;
  }
  Serial.println("Initializing SD Card...");
  if (!SD.begin(chipSelect)){
    Serial.println("SD Card Error");
    while(1);
  }
  Serial.println("Card Initialized");

  File dataFile = SD.open("sinx.txt");

  if (dataFile){
    while (dataFile.available()){
      Acceleration = dataFile.parseFloat();
      Velocity = ((Previous_Acceleration + Acceleration)/2) + Previous_Velocity;
      Distance = ((Previous_Velocity + Velocity)/2) + Previous_Distance;
      stepper.setSpeed(Velocity);
      stepper.setAcceleration(Acceleration);
      stepper.runToNewPosition(Distance - Previous_Distance);

    }
  }
  else{
    Serial.println("Error");
  }
}

void loop(){

}

Have you confirmed that the values you are getting out of your file reading and calculations are actually correct?

Yes, they are the same values if applied in Excel.

However, when ran, the motor stops after a loop is done and resumes. The delay is so short that it seems that it runs continuously, but this causes vibration of the motor causing the readings of the accelerometer to be inaccurate. This may be the cause of a blocking function ( I am inexperienced so I may be wrong ), so is there any way to make the stepper motor move with acceleration without putting distance?

were you able to solve this problem? Would like to hear from you if you were able to solve it.


text:
Arduino sketch unexpected behaviour
I am currently in a arduino project to read some parameters from another microcontroller serially and the arduino is supposed to transmit these serially to dweet.io cloud. I use SIM900 modem for this. But my problem is that if i put some data to the variables, then the post to the cloud becomes unsuccessfull. Without any data in all parameters, the code runs fine.
Please find the code
char code[4] = {'\0'}, voltage[4] = {'\0'}, current[4] = {'\0'}, mcurrent[4] = {'\0'}, acurrent[4] = {'\0'}, power[4] = {'\0'}, pf[4] = {'\0'}, freq[4] = {'\0'}, temp[4] = {'\0'};
const char APN[18] = "bsnlnet";
byte dtype = 0;

#include <avr/pgmspace.h>

void read_comp() {
    byte flag = 0, index = 0, l = 0;
    char c;
    char readings[8] = {'\0'};
    dtype = 0;

    do {
        while (Serial.available() && l == 0) {
            c = Serial.read();
            delay(20);

            if (c == '\n') {
                l = 1;
                break;
            } else {
                readings[index] = c;
                index++;
            }
        }

        readings[index] = '\0';
        index = 0;
        l = 0;

        if (readings[0] == 'v' || readings[0] == 'V') {             //check if received reading is voltage
            dtype = 1;
            flag = 1;

            if (readings[1] == 'o') {
                flag = 100;
            }
        } else if (readings[0] == 'c' || readings[0] == 'C') {  //check if received reading is current
            dtype = 2;
            flag = 1;

            if (readings[1] == 'u') {
                flag = 100;
            }
        } else if (flag == 1 && readings[1] == 'o') {
            dtype = 9;
            flag = 100;
        } else if (readings[0] == 'm' || readings[0] == 'M') {
            dtype = 3;
            flag = 1;

            if (readings[1] == 'c' && flag == 1) {
                flag = 100;
            }
        } else if (readings[0] == 'a' || readings[0] == 'A') {
            dtype = 4;
            flag = 1;

            if (readings[1] == 'c') {
                flag = 100;
            }
        } else if (readings[0] == 'p' || readings[0] == 'P') {
            flag = 1;

            if (readings[1] == 'o') {
                flag = 100;
                dtype = 5;
            } else if (readings[1] == 'f' || readings[1] == 'F') {
                flag = 100;
                dtype = 6;
            }
        } else if (readings[0] == 'f' || readings[0] == 'F') {
            dtype = 7;
            flag = 1;

            if (readings[1] == 'r') {
                flag = 100;
            }
        } else if (readings[0] == 't' || readings[0] == 'T') {
            dtype = 8;
            flag = 1;

            if (readings[1] == 'e') {
                flag = 100;
            }
        }

        if (flag == 100) {
            switch (dtype) {
                case 1:
                    voltage[0] = readings[3];
                    voltage[1] = readings[4];
                    voltage[2] = readings[5];
                    voltage[3] = readings[6];
                    voltage[4] = '\0';
                    flag = 0;
                    break;

                case 2:
                    current[0] = readings[3];
                    current[1] = readings[4];
                    current[2] = readings[5];
                    current[3] = readings[6];
                    current[4] = '\0';
                    flag = 0;
                    break;

                case 3:
                    mcurrent[0] = readings[3];
                    mcurrent[1] = readings[4];
                    mcurrent[2] = readings[5];
                    mcurrent[3] = readings[3];
                    mcurrent[4] = '\0';
                    flag = 0;
                    break;

                case 4:
                    acurrent[0] = readings[3];
                    acurrent[1] = readings[4];
                    acurrent[2] = readings[5];
                    acurrent[3] = readings[6];
                    acurrent[4] = '\0';
                    flag = 0;
                    break;

                case 5:
                    power[0] = readings[3];
                    power[1] = readings[4];
                    power[2] = readings[5];
                    power[3] = readings[6];
                    power[4] = '\0';
                    flag = 0;
                    break;

                case 6:
                    pf[0] = readings[3];
                    pf[1] = readings[4];
                    pf[2] = readings[5];
                    pf[3] = readings[6];
                    pf[4] = '\0';
                    flag = 0;
                    break;

                case 7:
                    freq[0] = readings[3];
                    freq[1] = readings[4];
                    freq[2] = readings[5];
                    freq[3] = readings[6];
                    freq[4] = '\0';
                    flag = 0;
                    break;

                case 8:
                    temp[0] = readings[3];
                    temp[1] = readings[4];
                    temp[2] = readings[5];
                    temp[3] = readings[6];
                    temp[4] = '\0';
                    flag = 0;
                    break;

                case 9:
                    code[0] = readings[3];
                    code[1] = readings[4];
                    code[2] = readings[5];
                    code[3] = readings[6];
                    code[4] = '\0';
                    dtype = 10;
                    flag = 0;
                    break;
            }
        }
    } while (dtype != 10);
}

void modem_initialization(void) {
    char rec_data, r;
    byte network_status = 0 ;//network_status initialized as zero
    byte status_check = 0 ;//status_check initialized as zero
    byte Serial3_cnt = 0;//Serial3_cnt initialized as zero
    byte ok_flag = 0; //ok_flag initialized as zero
    byte count = 0; //count initialized as zero
    clear_rx_buffer();

    while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 5
        switch (Serial3_cnt) {
            case 0:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT"));// Attention command to wake up Serial3 modem
                delay(1000);
                break;

            case 1:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("ATE0"));//Command for disable echo
                delay(1000);
                break;

            /*case 2: clear_rx_buffer();//clearing receiving buffer
                   // Serial3.println("ATV0");// Command for numeric response after this '0'(zero) will be recieved instead of "OK"
                    delay(1000);
                    break;*/
            case 2:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT&W"));// Command TO SAVE SETTINGS
                delay(1000);
                break;

            case 3:
                Serial3_cnt = 4;// exit from the loop
                break;

            default :
                break;
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == 'O') { // 'o' is recieved
                ok_flag = 1;
            } else if (ok_flag == 1 && rec_data == 'K') { // 'K' is recieved
                Serial3_cnt ++;
                ok_flag = 0;
            } else if (rec_data == '0') { // '0'(zero) is recieved (numeric response)
                Serial3_cnt ++;
                ok_flag = 0;
            } else if (rec_data == '+') { // '+' is recieved message
                clear_rx_buffer();

                if (Serial3_cnt > 0) {
                    Serial3_cnt --;
                }
            }
        }
    }

    Serial3_cnt = 0;
    ok_flag = 0;

    while (network_status == 0) { //wait for PIN READY
        if (status_check == 0) {
            delay(1000);
            status_check = 1 ;
            clear_rx_buffer();
            Serial3.println(F("AT+CPIN?")); //checkin PIN return ready(+CPIN: READY) with a valid simcard otherwise error
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == '+' && status_check == 1) { // '+' is recieved
                status_check = 2 ;
            } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
                status_check = 3 ;
            } else if (rec_data == 'P' && status_check == 3) { // 'P' is recieved
                status_check = 4 ;
            } else if (rec_data == 'I' && status_check == 4) { // 'I' is recieved
                status_check = 5 ;
            } else if (rec_data == 'N' && status_check == 5) { // 'N' is recieved
                status_check = 6 ;
            } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
                status_check = 7 ;
            } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
                status_check = 8 ;
            } else if (rec_data == 'R' && status_check == 8) { // 'R' is recieved
                status_check = 9 ;
            } else if (rec_data == 'E' && status_check == 9) { // 'E' is recieved
                status_check = 10 ;
            } else if (rec_data == 'A' && status_check == 10) { // 'A' is recieved
                status_check = 11 ;
            } else if (rec_data == 'D' && status_check == 11) { // 'D' is recieved
                status_check = 12 ;
            } else if (rec_data == 'Y' && status_check == 12) { // 'Y' is recieved
                status_check = 13 ;
            } else if (rec_data == 0X0D && status_check == 13) { //Carriage return
                status_check = 14 ;
            } else if (rec_data == 0X0A && status_check == 14) { //Line Feed
                status_check = 15 ;
            } else if (rec_data == 'O' && status_check == 15) { // '0' is recieved
                status_check = 16;
            } else if (rec_data == 'K' && status_check == 16) {
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //goto next step
            } else if (rec_data != 'R' && status_check == 8) { //+CPIN: NOT READY
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 0; //repeat current step
            } else if (rec_data == 'M' && status_check == 3) { // in case of any message
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 0; //repeat current step
            }
        }
    }

    while (network_status == 1) { //wait for SIM network registration
        if (status_check == 0) {
            delay(1000);
            status_check = 1 ;
            clear_rx_buffer();
            Serial3.println(F("AT+CREG?")); //checking for SIM card registration ,if registerd "+CREG: 0,1" will receive
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == '+' && status_check == 1) { // '+' is recieved
                status_check = 2 ;
            } else if (rec_data == 'C' && status_check == 2) { // 'C' is recieved
                status_check = 3 ;
            } else if (rec_data == 'R' && status_check == 3) { // 'R' is recieved
                status_check = 4 ;
            } else if (rec_data == 'E' && status_check == 4) { // 'E' is recieved
                status_check = 5 ;
            } else if (rec_data == 'G' && status_check == 5) { // 'G' is recieved
                status_check = 6 ;
            } else if (rec_data == ':' && status_check == 6) { // ':' is recieved
                status_check = 7 ;
            } else if (rec_data == ' ' && status_check == 7) { // ' ' is recieved
                status_check = 8 ;
            } else if (rec_data == '0' && status_check == 8) { // '0' is recieved
                status_check = 9 ;
            } else if (rec_data == ',' && status_check == 9) { // ',' is recieved
                status_check = 10 ;
            } else if (rec_data == '1' && status_check == 10) { // '1' is recieved
                status_check = 11 ;
            } else if (rec_data == 0X0D && status_check == 11) { //Carriage return
                status_check = 12 ;
            } else if (rec_data == 0X0A && status_check == 12) { //Line Feed
                status_check = 12 ;
            } else if (rec_data == 'O' && status_check == 12) { // '0' is recieved
                status_check = 13;
            } else if (rec_data == 'K' && status_check == 13) {
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 2; //goto next step
            } else if (rec_data != '1' && status_check == 10) { // +CREG: 0,2 not registered
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //repeat current step
            } else if (rec_data == 'M' && status_check == 3) { // in case of any message
                clear_rx_buffer();
                status_check = 0 ;
                network_status = 1; //repeat current step
            }
        }
    }

    Serial3_cnt = 0;

    while (Serial3_cnt < 4) { // repeat entire loop until Serial3_cnt less than 4
        switch (Serial3_cnt) {
            case 0:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CMGF=1"));// Attention command to wake up Serial3 modem
                delay(1000);
                break;

            case 1:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CNMI=2,1,0,0,0"));//Command to configure new message indication
                delay(1000);
                break;

            case 2:
                clear_rx_buffer();//clearing receiving buffer
                Serial3.println(F("AT+CMGD=1,4"));// Command to delete all received messages
                delay(1000);
                break;

            case 3:
                Serial3_cnt = 4;// exit from the loop
                break;

            default :
                break;
        }

        while (Serial3.available() > 0) {
            rec_data = Serial3.read();

            if (rec_data == 'O') { // '0'(zero) is recieved (numeric response)
                rec_data = Serial3.read();

                if (rec_data == 'K') {
                    Serial3_cnt ++;
                }
            } else if (rec_data == '+') { // '+' recieved ,before "AT+CIICR" command,may be any message
                clear_rx_buffer();

                if (Serial3_cnt > 0) {
                    Serial3_cnt --;
                }
            } else if (rec_data == 'E' && Serial3_cnt > 2) { // '4' recieved (error),in gprs initialisation commands
                clear_rx_buffer();
                Serial3_cnt = 4;
            }
        }
    }

    Serial3_cnt = 0;
}

void clear_rx_buffer(void) {
    Serial3.flush();
}

void gprs_init() {
    byte st = 1, i = 0, response = 0;
    char r[10];

    while (st <= 9) {
        delay(1000);
        clear_rx_buffer();

        switch (st) {
            case 1:
                Serial3.println(F("AT+CGATT?"));
                break;

            case 2:
                Serial3.println(F("AT+CIPSHUT"));
                break;

            case 3:
                Serial3.println(F("AT+CIPMUX=0"));
                break;

            case 4:
                response = cmd1_check(1);
                break;

            case 5:
                Serial3.println(F("AT+CIICR"));
                delay(1000);
                break;

            case 6:
                Serial3.println(F("AT+CIFSR"));
                break;

            case 7:
                response = cmd1_check(2);
                delay(2200);
                clear_rx_buffer();
                break;

            case 8:
                Serial3.println(F("AT+CIPSEND"));
                break;

            case 9:
                Serial3_send();
                ++st;
                break;
        }

        if (st == 10) {
            clear_rx_buffer();
        }

        delay(1000);

        while (Serial3.available() && st < 9 && st != 7 && st != 4) {
            r[i] = Serial3.read();
            i++;
        }

        i = 0;

        if (strstr(r, "ALREADY") != NULL) {
            Serial3.println("AT+CIPSHUT");
            delay(50);
            clear_rx_buffer();
            st = 2;
            r[0] = '\0';
        }

        if (strstr(r, "OK") != NULL || strstr(r, "+CGATT") != NULL || (strstr(r, ".") != NULL && st == 6) || strstr(r, ">") != NULL) {
            st++;
        } else if (strstr(r, "ERR") != NULL) {
            break;
        } else if (response == 1 && (st == 7 || st == 4)) {
            st++;
            response = 0;
        }
    }
}

char cmd1_check(short int o) {
    byte timout1 = 10500, m1, p1 = 0, resp1 = 0;
    char response1[25] = {'\0'};
    m1 = millis();
    clear_rx_buffer();

    if (o == 1) {
        Serial3.print(F("AT+CSTT="));
        Serial3.print('"');
        Serial3.print(APN);
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.println('"');
        delay(3000);
    } else if (o == 2) {
        Serial3.print(F("AT+CIPSTART="));
        Serial3.print('"');
        Serial3.print(F("TCP"));
        Serial3.print('"');
        Serial3.print(',');
        Serial3.print('"');
        Serial3.print(F("dweet.io"));
        Serial3.print('"');
        Serial3.print(',');
        Serial3.println(80);
        delay(2000);
    }

    do {
        p1 = 0;

        while (Serial3.available()) {
            response1[p1] = Serial3.read();
            p1++;
            delay(20);
        }

        if (strstr(response1, "OK") != NULL && o == 1) {
            resp1 = 1;
        } else if (strstr(response1, "ERR") != NULL) {
            resp1 = 2;
        } else if (strstr(response1, "CONNECT OK") != NULL && o == 2) {
            resp1 = 1;
        }
    } while ((millis() - m1) <= timout1 && resp1 == 0);

    return (resp1);
}

void Serial3_send() {
    Serial3.print("POST /dweet/for/");
    Serial3.print("mythingname");
    Serial3.print("?vo=");
    Serial3.print(voltage);
    Serial3.print("&cu=");
    Serial3.print(current);
    Serial3.print("&Mc=");
    Serial3.print(mcurrent);
    Serial3.print("&Ac=");
    Serial3.print(acurrent);
    Serial3.print("&Po=");
    Serial3.print(power);
    Serial3.print("&PF=");
    Serial3.print(pf);
    Serial3.print("&fr=");
    Serial3.print(freq);
    Serial3.print("&Te=");
    Serial3.print(temp);
    Serial3.println(" HTTP/1.1");
    Serial3.println("connection: keep-alive");
    Serial3.println();
    Serial3.println();
    Serial3.write(26);
    Serial3.println();
    delay(10000);
    Serial3.println("AT+CIPSHUT");
    delay(50);
}

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

void loop() {
    dtype = 0;
    read_comp();
    gprs_init();
}

This looks like you are constructing the data to be sent as GET parameters (i.e as part of the querystring), whereas I believe dweet.io expects them as part of the POST body - as seen here.
There seem to be many people struggling to successfully send HTTP POSTs with a SIM900, but I think this answer outlines the correct sequence to make it work.


text:
Uploading... forever
This is my code:
const int trigPin = 4;
const int echoPin = 2;
const int trigPin2 = 6;
int incomingByte;
int val, val2;
const int echoPin2 = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(trigPin2, OUTPUT);
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2, LOW);

  pinMode(echoPin, INPUT);
  pinMode(echoPin2, INPUT);

  val = digitalRead(echoPin);
  val2 = digitalRead(echoPin2);

  if (val && val2 == HIGH) {
    Serial.println("Elephant on tracks");
  }

  if (Serial.available() > 0) {  // if the data came
    incomingByte = Serial.read();
  }
  // read byte
  if(incomingByte == '0') {
     digitalWrite(trigPin, LOW);
     digitalWrite(trigPin2, LOW);
     Serial.println("The system is OFF.");  // print message
  }
}

Anyhow, I click upload, and as the title of this question says, have to wait forever.
Not only this code, nothing gets uploaded. It was working just fine a week ago.
I run a Windows 7 64-bit system, and have an Arduino Uno R3.
Does anyone have any suggestions?

So you can't upload the sketch to Arduino? No error messages at all? Try to enable the verbose options in settings and paste the result here

Are you uploading to the right serial port? Do you have anything else attached to the Arduino?

Thanks for the suggestions. It finally worked. It was because of my HC-06 Bluetooth module. I don't know if the mistake was mine or if it is a fault with the module.

From your code, I assume that the bluetooth module is connected to pins 0 & 1 on the arduino. These pins are to be kept free/floating/not connected to anything if you need to upload code to your board.
Use software serial in such cases reduces the headache

Comment by SR1 turned into an answer:
Thanks for the suggestions. It finally worked. It was because of my HC-06 Bluetooth module. I don't know if the mistake was mine or if it is a fault with the module.

(Done to reduce "unanswered questions" on this site).


text:
Arduino-uno sending email with Hotmail
I want to get emails read from a Hotmail account using an Arduino Uno. Is there a way to do it with SSL or is there a way to disable SSL?
#include <SPI.h>
#include <Ethernet.h>
// Use comments to enable or disable this define for debug messages
#define DEBUG_POP
// Use comments to enable or disable the deleting of the mail
#define ENABLE_DELETE_POP

// The mac address must be an unique number
// A mac generator is used:
//   http://www.miniwebtool.com/mac-address-generator/
byte mac[] = { 0xDE, 0x36, 0x5F, 0x0A, 0x19, 0x83 };
// change network settings to yours
IPAddress ip(192, 168, 1, 117);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Set the server POP3 address, the port, the user and password.
// The POP3 mail server is something like this:
//     mail.yourdomain.com, pop.yourdomain.com, pop3.yourdomain.com
// Using PROGMEM for these causes a fail when trying to connect and log in.
const char pop_server[] = "pop3.live.com";
const int  pop_port = 995;
const char pop_user[] = "xxxxxx@hotmail.com";
const char pop_pass[] = "xxxxxx";

// The number of milliseconds timeout for parseInt() and find().
// The response time for the Server can still be 10 seconds.
#define POP_TIMEOUT 10
#define POP_TIMEOUT_DEFAULT 1000

EthernetClient client;

void setup()
{
    Serial.begin(9600);
    Serial.println(F("\nArduino POP3 email reader"));

    pinMode(13, OUTPUT);     // the system led is used for testing

    // When the Ethernet Shield is used, there is also a SD card connected
    // to the SPI bus. Disable the SD card with chip select at pin 4.
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    // Start Ethernet. Use only the 'mac' parameter for DHCP
    // Use 'mac' and 'ip' parameters for static IP address.
    //  Ethernet.begin( mac, ip);
    //  Ethernet.begin( mac, ip, gateway, gateway, subnet);
    if (Ethernet.begin(mac) == 0)
    {
        Serial.println("Failed to configure Ethernet using DHCP.");
        // no point in carrying on, so do nothing forevermore:
        while (1);
    }
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    // print your local IP address.
    Serial.println(F("Ethernet started."));
    Serial.print(F("Local IP = "));
    Serial.println(Ethernet.localIP());

    Serial.println(F("Press 'c' to check mail."));
}

void loop()
{
    // Create a buffer to receive the commands in (that is the Subject of the mail).
    char buffer[32];

    byte inChar = Serial.read();
    if (inChar == 'c')
    {
        // The getEmail gets the text of the mail Subject into the buffer.
        // The valid number of received characters are returned.
        // If the return value is < 0, it is an error.
        int n = getEmail(buffer, sizeof(buffer));

        if (n < 0)
        {
            Serial.print(F("Email POP3 failed, error = "));
            Serial.println(n);
        }
        else
        {
            if (n == 0)
            {
                Serial.println(F("Ready, nothing to do."));
            }
            else
            {
                // 'n' is > 0, a command received.
                Serial.print(F("Email checked, Command = \""));
                Serial.print(buffer);
                Serial.println(F("\""));

                // Check the commands.
                //
                // At this moment, a single command 'L' is used to set system led on or off.
                //    L=1   (set led on)
                //    L=0   (set led off)
                if (buffer[0] == 'L' && buffer[1] == '=')
                {
                    digitalWrite(13, buffer[2] == '0' ? LOW : HIGH);
                }
            }
        }
    }
}

// getEmail
// --------
// Find an email on a mail server, using POP3.
// The Subject should start with "ARDUINO " and the text
// after that is copied into pBuf.
//
// The data in pBuf is only valid if the return value is not an error
// (an error is return value less than zero).
//
int getEmail(char *pBuf, int nBufSize)
{
    // nBytes is the number of bytes that is returned by getEmail.
    int nBytes = 0;

    // Connect to server
    // client.connect returns '1' if okay, or negative number if error.
    //    SUCCESS 1
    //    0     (error, unknown timeout, perhaps an error in the library)
    //    TIMED_OUT -1
    //    INVALID_SERVER -2
    //    TRUNCATED -3
    //    INVALID_RESPONSE -4
    //    -5    (there is no mail server at that IP address and port)
    // The string for the server must be a normal string in sram, no PROGMEM allowed.
    int nError = client.connect(pop_server, pop_port);

    // During testing, a value of zero was sometimes returned.
    // This is not according to the documentation and it is an error.
    // Therefor the non-error value '0' is turned into a negative number to
    // indicate an error.
    if (nError == 0)
        return(-200);

    // Only a value of 1 is okay.
    if (nError != 1)
        return(nError);

#ifdef DEBUG_POP
    Serial.println(F("connected"));
    //Serial.println(nError);
#endif
    // The server should respond with "+OK" and maybe more text after that.
    // Check if "+OK" can be read.
    // The parameter 'true' is to read also everything after the "+OK".
    if (!readOk(true))
        return -102;

#ifdef DEBUG_POP
    Serial.println(F("command USER"));
#endif
    client.print(F("USER "));
    client.println(pop_user);
    if (!readOk(true))
        return -103;

#ifdef DEBUG_POP
    Serial.println(F("command PASS"));
#endif
    client.print(F("PASS "));
    client.println(pop_pass);
    if (!readOk(true))
        return -104;

#ifdef DEBUG_POP
    Serial.println(F("command STAT"));
#endif
    client.println(F("STAT"));
    if (!readOk(false))
        return -105;

    // The whole line was like this: "+OK 3 15343"
    // It means that 3 emails are waiting with a total size of 15343.
    // At this moment, the "+OK" is read, but nothing else.
    // Check if there is a space after "+OK".
    char c = client.read();
    if (c != ' ')
        return -106;

    client.setTimeout(POP_TIMEOUT);       // set timeout lower for parseInt
    // Read the number of emails that are on the server.
    int nMails = client.parseInt();
    client.setTimeout(POP_TIMEOUT_DEFAULT);  // restore timeout to 1 second

    // Read the remaining of the response to STAT.
    readRemaining();

#ifdef DEBUG_POP
    Serial.print(F("Number of emails="));
    Serial.println(nMails);
#endif

    // Test if there are emails waiting.
    if (nMails == 0)
    {
        // No emails, but no error. Set buffer to empty string.
        nBytes = 0;               // the returned value
        pBuf[0] = '\0';           // set empty string
    }
    else if (nMails > 0)
    {
        // emails are waiting.
        // Scan the emails until the first is found with the keyword "ARDUINO " at the
        // beginning of the "Subject: ".

        boolean found_and_ready = false;
        for (int nMailNumber = 1; nMailNumber <= nMails && !found_and_ready; nMailNumber++)
        {
            // The command RETR <x> gets the whole mail.
            // The command TOP <x> <size> gets the header plus 'size' of the body.

#ifdef DEBUG_POP
            Serial.print(F("command TOP "));
            Serial.print(nMailNumber);
            Serial.println(F(" 0"));
#endif
            client.print(F("TOP "));
            client.print(nMailNumber);
            client.println(F(" 0"));

            // Use readOk with parameter 'false' to stop reading after "+OK".
            if (!readOk(false))
                return -107;
            // The header of the email is waiting to be read, use the Stream.find() to look for the Subject.
            // The text "Subject: " should be at the beginning of a line, but that is not tested.
            // The first found text "Subject: " is assumed to be the real subject.
            // I have checked many years of emails, and the text is always "Subject: ", and never "SUBJECT: ".
            // At the moment, it is not possible to use the F() macro for Stream.find
            // Only the email that starts with "ARDUINO " at the start of the Subject is used.

            client.setTimeout(POP_TIMEOUT);      // set short timeout for find().
            // find() returns true if found and false if not.
            boolean foundsubject = client.find("Subject: ARDUINO ");
            client.setTimeout(POP_TIMEOUT_DEFAULT);   // restore timeout to 1 second

            if (foundsubject)
            {
#ifdef DEBUG_POP
                Serial.println(F("Found an email for me"));
#endif

                // Read the remaining subject (that is the command for the Arduino) into a buffer.
                // Every line from the mail server should end with CR + LF,
                // but to be sure, both CR and LF are checked.
                // Alternative:
                //    client.readBytesUntil('\r', pBuf, nBufSize);

                // The last position in the buffer is reserved for the zero terminator.
                // So read data until (nBufSize-1).
                int i;
                for (i = 0; i < (nBufSize - 1) && client.available(); i++)
                {
                    char c = client.read();
                    if (c == '\r' || c == '\n')
                        break;
                    pBuf[i] = c;
                }
                // Add zero terminator
                pBuf[i] = '\0';
                nBytes = i;     // the number of received bytes is returned by the getEmail() function.

                // More text of the header could be following the Subject.
                // That is read and disregarded.
                readRemaining();

#ifdef DEBUG_POP
                Serial.print(F("Subject = \"ARDUINO "));
                Serial.print(pBuf);
                Serial.println(F("\""));
#endif

#ifdef ENABLE_DELETE_POP
                // Delete the just read message.
#ifdef DEBUG_POP
                Serial.print(F("command DELE "));
                Serial.println(nMailNumber);
#endif
                client.print(F("DELE "));
                client.println(nMailNumber);
                if (!readOk(true))
                    return -108;
#endif

                // Everything is okay, the mail is read and deleted.
                // Ready for now, don't process the remaining emails.
                found_and_ready = true;
            }
            else
            {
#ifdef DEBUG_POP
                Serial.println(F("No ARDUINO keyword in subject"));
#endif
                // This email has no "Subject: ARDUINO ".
                // But the remaining text has still to be read and disregarded.
                readRemaining();
            }
        }
    }

#ifdef DEBUG_POP
    Serial.println(F("Sending QUIT"));
#endif
    client.println(F("QUIT"));

    // After "QUIT", the server still respons with "+OK",
    // but after that, the connection might get lost.
    // So don't read everything after "+OK" (use parameter 'false' for readOk).
    if (!readOk(false))
        return -109;

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("normally disconnected"));
#endif

    return(nBytes);
}

// Read the response from the mail server.
// That is "+OK" if everything is okay.
// Parameter 'readAll' is to read every character after the "+OK".
boolean readOk(boolean readAll)
{
    // Check the response "+OK" from the mail server
    // In most cases that is followed by a space and more text, but not always.
    // In case of an error the text "-ERR" is received.

    int loopCount = 0;
    char bufOk[4];
    Serial.print("Connected: ");
    Serial.println(client.connected());

    Serial.print("Client Available: ");
    Serial.println(client.available());
    // Wait for response of mail server, with a timout.
    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return false;
        }
    }

    // Read the first three bytes.
    client.readBytes(bufOk, 3);

#ifdef DEBUG_POP
    Serial.write(bufOk, 3);
    Serial.println();
#endif

    // Is it "+OK" ?
    if (strncmp(bufOk, "+OK", 3) != 0)
    {
        popFail();
        return false;
    }

    // When the text after "+OK" is not needed, everything
    // else can be read and disregarded
    // (or shown in the serial monitor during debugging).
    if (readAll)
        readRemaining();

    return true;
}

void readRemaining()
{
    // This function is called after checking the "+OK".
    // It reads everything from the server, until no more text is
    // available.

    while (client.available())
    {
        char c = client.read();
#ifdef DEBUG_POP_EXTRA
        Serial.print(c);
#endif
    }
    return;
}

void popFail()
{
    int loopCount = 0;

#ifdef DEBUG_POP
    Serial.println(F("popFail"));
#endif

    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return;
        }
    }

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("disconnected due to fail"));
#endif
}

Output:
Arduino POP3 email reader
Ethernet started.
Local IP = 192.168.1.117
Press 'c' to check mail.
connected
Connected: 1
Client Active: 0

Timeout
Email POP3 failed, error = -102

Your title says it's about sending mail, while the code only contains code for receiving mail

Hotmail doesn't provide a non-encrypted POP3 service, which would normally run on port 110.
You have no choice but to use the SSL service.  However, you can't.  Or not easily.  SSL is quite a heavy protocol and it is highly doubtful the little Uno is capable of even coming close to being able to work with it.
The Due might have a chance, but again, unlikely.
You would be best off using a computer (server) to check the emails for you and provide a "digest" of information to the Uno instead.

A Due certainly has the resources (memory) to do it, though the challenge may be in finding/creating an implementation.  Something with networking on board and an existing library might be easier and more cost effective - for example, a raspberry pi (though at the cost of a more delicate writable-filesystem OS installation).  The idea of using an additional server as a proxy to help out is a good one though, if the unsecured nature of the communication to/from that server is acceptable.


text:
Calculate how much battery power left
I run my 12V car battery trough a trimpot into my pro micro, micro controller.
I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.
But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??
Sorry for my English
Thanks! //Rasmus

This would be easier if there was no engine involved. Throwing the engine in makes this very, very difficult to solve.

Is is a camper van that has an extra battery. So the sweet part is that the remains of the battery  can be calculated when the motor is not running. And its also then its the most important to know for how long I can run my stereo =)

Take a look at http://electronics.stackexchange.com/questions/110104/calculating-battery-percentage-using-an-arduino. You can measure battery percentage

Thx @PhillyNJ!!

You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.
You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.
But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.

I think can get the current out of it using another calculation! But the thing is that its a camper van that has an extra battery. So the sweet part is that the remains it will be calculated when the motor is not running.


text:
Segmentation fault at Serial.begin()
I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by dnf from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:
"/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
lto1: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://bugzilla.redhat.com/> for instructions.
lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
compilation terminated.
/usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.
I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

What IDE version are you running? And how did you install it?

How did avr-gcc find its way into /usr/bin?  How exactly have you installed Arduino?  Are you intentionally using an avr-gcc different than the one packaged with it, or is that an accidental case of a system version overriding Arduino's?

Edited the question - version 1.8.4, installed from repos. I didn't setup any magic with avr-gcc - I did not change anything.

@ChrisStratton which arduino provided /usr/bin/arduino, then find /usr/bin/arduino -name avr-gcc did not output anything. ls -l /usr/bin/avr-gcc gives -rwxr-xr-x. 2 root root 830016 Aug  2 20:40 /usr/bin/avr-gcc and /usr/bin/avr-gcc --versiongivesavr-gcc (Fedora 6.3.0-3.fc27) 6.3.0`

@ChrisStratton I installed using sudo dnf install arduino. The blink works as it should. I also tested a switch and it works as well. Is it possible to download the binary and run it along the redhat version?

Do not install from repos. Download the official tarball from Arduino.

If you install the download in a unique path, probably, but safer to remove the redhat version with their package manager.  This looks to be the same as the bug the Arduino-Makefile project is talking about, applying to at least the fedora type avr-gcc package over a wide range of versions.  You might be able to fix it if you can get the IDE to add the build flag they discuss, but simpler just to use the working download from Arduino unless you particularly want to avoid that.

Thanks for help! The official Arduino binaries did the trick :) Could you please transform the comment into an answer as I could then upvote and accept it? Thanks a lot.

There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


text:
Motor encoder and interrupts
I'm trying to write motor controller for automated blinds using Raspberry Pi Pico with arduino-pico.
My problem is that I can't seem to get a consistent result from motor encoders.
In my setup function I attach the interrupt:
void motor0Enc1handler() {
  motor0.handleEnc1();
}

void setup() {
  attachInterrupt(digitalPinToInterrupt(motor0.getEnc1()), motor0Enc1handler, RISING);
}

Motor is a class with the following interrupt processing code:
int Motor::getEnc1() {
  return _enc1;
}
void Motor::handleEnc1() {
  // debug only
  if (digitalRead(_enc1) != HIGH) {
    _false_triggers++;
  }

  if (digitalRead(_enc2) == HIGH) {
    // debug only
    if (!_going_down) {
      _direction_changes++;
    }
    _going_down = true;

    _pos = _isLeft ? _pos - 1 : _pos + 1;
  } else {
    // debug only
    if (_going_down) {
      _direction_changes++;
    }
    _going_down = false;

    _pos = _isLeft ? _pos + 1 : _pos - 1;
  }
}

Interrupt is attached to one of the hall effect sensors on the motor. It has 2 sensors set an angle, so the direction of the motor can be determined.
For example, when _enc1 is HIGH and _enc2 is low at the same time it means that the motor is moving in one direction, when _enc2 is also high it moves in the opposite direction.
Here is much better explanation of this.
The main point is that the timing is extremely important to properly calculate the number of rotations the motor made.
For example, if handleEnc1 is delayed the motor would have slightly moved already and digitalRead(_enc2) will return incorrect value.
In my interrupt I've set up a few debugging variables:
_false_triggers is incremented when handleEnc1 is triggered, but when trying to read the same pin value it returns unexpected result. For example, handleEnc1 is triggered on RISING, so I would expect the pin value to be HIGH. If it's not high, it means that the interrupt was delayed and the hall effect sensor is not reporting a different value, because the motor shaft has rotated.
_direction_changes is incremented when motor is supposed to be moving in a single direction, so I would expect digitalRead(_enc2) == HIGH to always be true or false depending on the direction. If the motor keeps turning in the same direction it should never be incremented.
My hardware setup is:
Raspberry Pi Pico (_enc1 is pin 20, _enc2 is pin 21).
Motor is JGA25-370 with encoders.
Interrupts are triggered at about 2 interrupts per millisecond.
What happens is that I get non-zero _direction_changes and _false_triggers during normal operation:

start the motor to go in a single direction
serial print direction changes and false triggers from time to time
write current motor position into a file with LittleFS in flash memory.

In this case I get about 15-20 _direction_changes per 10000 steps and around 10 _false_triggers.
When I disable writing of motor position into a flash file it get less _direction_changes (around 10) and _false_triggers drops to zero, which is an improvement and it proves that the code is susceptible to competing interrupts (I imagine writing to file system or serial uses interrupts).
However, this is not ideal, since I need to use SPI as well to talk via nRF24l01 and I also need to persist current motor position periodically in case of a power loss.
Also, I don't want to have a position drift for my automated blinds, even though it's relatively small, but it will compound over time.
Am I not using interrupts correctly encoders?
Is there a better way to approach this?
I was thinking about attaching interrupts to both _enc1 and enc2 and push events into a queue and then process it in the main code, but I don't think it's going to work. I can only attach interrupts to either FALLING or RISING so I would be able to detect pulses in a single direction, if I attach interrupts to CHANGE it would mean I'd have to read pin value from within interrupt which is prone to the same issue that I'm already experiencing.
I guess my main problem is that I feel like I shouldn't be having this problem. I only have 2 pulses per millisecond, so it's not that many. Interrupt code is not doing much (unless I'm not supposed to do digitalRead in an interrupt). So I feel like there should be a reliable way to maintain motor position even if there is other stuff going on in the application.
The full code is here in case it's helpful.

"Am I not using interrupts correctly encoders"? I would suggest that you read Nick Gammon's Interrupt to understand the "do and don't of interrupt" first. I would also suggest you move most of the code in your Motor::Motor() construct to Motor::begin() as when you instantiating an instance of Motor object before the setup(), many of the peripherals might not be ready, or available yet.

Thanks!
I've read the post and so far other than not using volatile it seems like I'm not violating any rules of interrupts. That post even mentioned reading and writing to pins.
Since it's Raspberry Pi Pico I was able to use PIO to read interrupts (found a project on Github) which seems to have improved things, but I'd still like to to understand why it's not reliable the way I've implemented it.
Thanks for the advice about moving Motor::begin() into setup, it's a good point.


text:
Cannot set MOSI pin low even after ending SPI
I'm building a battery operated device and must shutoff MOSI pin during sleep because it leaks current through the SD card if I don't (about 400 µA).
Problem is, it won't stay off.  I've looked at SPI documentation and as far as I know I just need to call spi.end() then set pinmode to output and finally digitalWrite LOW.  I observe with an oscilloscope that it does go low upon my asking it to but only for about 1 µs (actually it goes low twice within a 5 µs time period).
I've also tried manually setting the pin low using the PORT registers and the behavior is the same... see relevant code:
spi.end();

//pinMode(pin_MOSI, OUTPUT);
//digitalWrite(pin_MOSI, LOW);

//Both above (commented out) and below result in the same behavior -- pin does not stay LOW

DDRB |= B00100000;            //set pin 5 as output
PORTB &= B11011111;           //set output low for pin 5

delay(5000);

...As you can see there is a delay to ensure that it isn't being set high by some other code.
Is there some sort of SPI interrupt that automatically sets the pin high again?
Hardware details:
MCU: ATMEGA1284P;
Programmer: Atmel-ICE

UPDATE (13-Mar-2019):
I didn't realize that SPI is implemented by Atmel in hardware directly (see datasheet page 105):

MOSI/PCINT13 – Port B, Bit 5
  – MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI0 is enabled
  as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI
  is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is
  forced to be an input, the pull-up can still be controlled by the PORTB5 bit.

I am currently chasing down this latest information and will hopefully come to a resolution soon.  I will post any progress.

is it a SD module with logic level conversion?

@Juraj: No level shifting, straight 3.3 volts to the SD card.

I thought you using SPI.begin() and SPI.end() to use the embedded hardware from the Arduino IDE. You are bit-banging instead?

@CrossRoads: I'm using SPIClass from <spi.h>.  I'm assuming that is part of the Arduino core but I'm not certain.  I have successfully gotten it to work by clearing the SPI enable bit (SPE) from the SPCR register so I know the library was not doing it for me.

@Juraj: I'm using ATmega1284P which is a 3.3 volt MCU -- doesn't have 5 volts.  Thanks!

my runs at 5V. default here is 5V.

@Juraj: Good point!  I incorrectly assumed the ATmega1284P was a 3.3 volt part but it can go as high as 5.5 volts -- mine is running at 3.3 volts as that is my designed VCC level.

You're not running 16 MHz are you? That could be unstable.  Speed grades: 0 - 4MHz @ 1.8 - 5.5V, 0 - 10MHz @ 2.7 - 5.5V, 0 - 20MHz @ 4.5 - 5.5V per the datasheet.

@CrossRoads: I thought I was running at 8 MHz but upon trying to verify found that indeed I am running at 16 MHz at 3.3 volts!  It had been working fine but no guarantee that there won't be issues!!  Using an external oscillator at 16 MHz -- I've figured out how to add a prescaler to slow the MCU to 8 MHz then changed the F_CPU field in boards.txt so that timing wasn't messed up in the Arduino code.  I think everything is finally working.  Thanks so much for the comment -- it wasn't yet a problem but I'm sure could have become a major issue under certain conditions (like maybe warmer temps)!

Indeed, SPI is hardware implemented.  I was able to get the MOSI pin to operate as intended by clearing the SPI enable bit from the SPCR register as follows:
SPCR &= 0B10111111;  //disable SPI

To re-enable after sleep, I'm assuming I'll just do SPCR |= 0B01000000; ...pretty sure that will work but I'll update here if I have to modify my solution.
.
Perhaps also pertinant information:
I was using an object of SPIClass in SPI.h which is from the Arduino core libraries -- for some reason it wasn't disabling SPI in hardware when calling the spi.end() method, maybe because there was some other SPI object initialized by some other library.  Here is the source from SPI.cpp for the end method:
void SPIClass::end() {
  uint8_t sreg = SREG;
  noInterrupts(); // Protect from a scheduler and prevent transactionBegin
  // Decrease the reference counter
  if (initialized)
    initialized--;
  // If there are no more references disable SPI
  if (!initialized) {
    SPCR &= ~_BV(SPE);
    interruptMode = 0;
    #ifdef SPI_TRANSACTION_MISMATCH_LED
    inTransactionFlag = 0;
    #endif
  }
  SREG = sreg;
}

The line SPCR &= ~_BV(SPE); should have done the job for me but I'm guessing it never got there because initialized was probably still non-zero.

If you didn't have #include <SPI.h> at the top of your sketch, how were you able to use SPI.begin(), SPI.transfer();  etc?

@CrossRoads: I did have SPI.h included -- sorry if that was not clear.

I thought I read something about not using the library, but I don't see it now. Perhaps I had two topics confused.  Glad you got it sorted.

Perhaps the SPI library got improved in the years that passed since this answer was written. spi.end() has the desired effect now. Setting/clearing the bit in SPCR is still faster though.

@DmitryGrigoryev: Take a look at the end() method that I copied from the core source files (above toward the end of my answer).  If the member variable 'initialized' (which is defined as uint8_t) is not zero then clearing the SPI enable bit in SPCR never happens.  I think the issue is that one of the libraries I was using called SPI.begin() but never called SPI.end() which means SPI was never able to deactivate.  I ended up rewriting the code without the other libraries and the problem was solved.


text:
Programming pic microchip
I have a few pic chips, mainly pic16f72 and pic16f73 on old ups circuits, realized they are not that bad. Their adc capabilities are my point of focus.
I have an esp32 (my first mcu) and i am very disappointed mainly because its adc being crap, I did some research on programming pic chips, some could be programmed via an arduino but my chips were not mentioned anywhere. I wanna program them via my esp32..
Is there a way to program them via arduino (esp32 in my case)? I can build some basic circuits but diy pic programmers require a preprogrammed pic chip which I can't produce if I can't program one already.

In principle you should be able to program every PIC, that works with ISP, over an Arduino. Though I haven't done that myself yet

Can you point me in the right direction? I asked here because i don't know pic[s] and if arduino projects on internet for programming them gonna work with my pics

What exact select criteria for picking pic16F72/73? You mentioned esp32 ADC(which is 12-bit) bad performance so you drop it and pick two MCUs that only offer 8-bit resolution ADC? Getting an Arduino Nano or Uno will give you at least 10bit ADC. If you said ESP32 ADC is a crap because of its non-linearity, it can be calibrate with a Look-up table, here is how I did it, it is still noisier than lower-speed MCU, but it is 12-bit ADC, so depend on what you are looking for.

8-bit ADC resolution on Pic16f72 means 5/256=19.5mV/bit resolution. 12-bit ADC resolution on ESP32 means 0.8mV/bit resolution. if whatever you are measuring can tolerant 19.5mV/bit, then the non-linearity and the higher noise on ESP32 is probably doesn't matter much to you anyway.

BTW, you can find all the info about PIC IDE and toolchain at Microchip website

Makes sense, thanks for calculations, my first attempt was trying to use a thermistor for temp readings and i wasn't satisfied and i did calibrate it

Ha, using a thermistor was exactly what I did when I discover the non-linearity problem of ESP32 (I saw 2 degree Celsius differences caused by non-linearity), read my blog

Thats the blog i followed, did you use a capacitor? And should i connect it to 5v or 3.3v?

For PIC32 you need chipKIT.  Not all chips are supported, but most of the PIC32MX and PIC32MZ chips are. Which exact PIC32 chip(s) do you have?
You will need to install a bootloader, for which you will need a programmer. It is possible to build a programmer using an Arduino, though TBH I'd just pick up a cheap PICkit2 clone from China.
As for the 8-bit PICs, no, they can't be programmed like an Arduino, simply because there is no open source C++ compiler available.

It seems, that you are talking about 2 different things:

The programming/burning of the PIC can be done via an Arduino (so you don't need to build a complex PIC programmer circuit). It is irrelevant, what microcontroller type is on the programmer, as long as the programmer speaks ISP (the programming protocol). So even, when your specific PIC is not mentioned at your found sites, it should work nonetheless. The connections are every time the same, though of your specific PIC the used pin functions might be on other pins (consult the datasheet for this).
An Arduino project - meaning the sketch/program, that was written for a normal Arduino, is normally not easily reusable. PICs are different microcontrollers with different hardware, so you need to port those projects to your specific microcontroller, which might involve extensive changes. When you have an Arduino Project, that was directly written for your PIC, then you can reuse it. (Be sure to install the correct core for your PIC in the Arduino IDE)


text:
Error compiling for board Arduino Nano 33 BLE
I am trying to use pulse sensor with Arduino Nano 33 BLE sense, but when I verify it, it shows Error compiling for board Arduino Nano 33 BLE. The code is from the pulse sensor website. The code works with all Arduino board, but it is not working with the Arduino Nano 33 BLE.
This is the code:
/*  Getting_BPM_to_Monitor prints the BPM to the Serial Monitor, using the least lines of code and PulseSensor Library.
 *  Tutorial Webpage: https://pulsesensor.com/pages/getting-advanced
 *
--------Use This Sketch To------------------------------------------
1) Displays user's live and changing BPM, Beats Per Minute, in Arduino's native Serial Monitor.
2) Print: "♥  A HeartBeat Happened !" when a beat is detected, live.
2) Learn about using a PulseSensor Library "Object".
4) Blinks LED on PIN 13 with user's Heartbeat.
--------------------------------------------------------------------*/

#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                               // Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {

  Serial.begin(9600);          // For Serial Monitor

  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
   if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {

 int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                               // "myBPM" hold this BPM value now.

if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
 Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
 Serial.print("BPM: ");                        // Print phrase "BPM: "
 Serial.println(myBPM);                        // Print the value inside of myBPM.
}

  delay(20);                    // considered best practice in a simple sketch.

}

The error text:
    Arduino: 1.8.7 (Mac OS X), Board: "Arduino Nano 33 BLE"

In file included from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.h:439:0,
                 from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:16:
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp: In member function 'boolean PulseSensorPlayground::sawNewSample()':
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:72:41: error: 'cli' was not declared in this scope
 #define DISABLE_PULSE_SENSOR_INTERRUPTS cli()
                                         ^
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:105:5: note: in expansion of macro 'DISABLE_PULSE_SENSOR_INTERRUPTS'
     DISABLE_PULSE_SENSOR_INTERRUPTS;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:73:40: error: 'sei' was not declared in this scope
 #define ENABLE_PULSE_SENSOR_INTERRUPTS sei()
                                        ^
/Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:108:5: note: in expansion of macro 'ENABLE_PULSE_SENSOR_INTERRUPTS'
     ENABLE_PULSE_SENSOR_INTERRUPTS;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
exit status 1
Error compiling for board Arduino Nano 33 BLE.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The code is from the pulse sensor website: https://pulsesensor.com/pages/installing-our-playground-for-pulsesensor-arduino.

wow! you are one of the very few people that has actually formatted the code when asked ... upvote for that

I tried #define USE_ARDUINO_INTERRUPTS false, but it is still the same error


text:
5V on HIGH Digital Pins, Only While Using USB Power
So I have a small problem with my Arduino Pro Mini here. May be worth noting that it is a clone, but otherwise this is still some weird functionality. I have done some experimenting so I'll just set the scene for you. I have everything that requires power connected to the + and - lines on my breadboard, that way I can avoid drawing more than about 20mA across any individual pins. I currently have my Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. It actually is currently outputting 5.36V.
I have made sure all my pins I'm using for output are indeed set as output, the problem only arises when I attempt to power the device from something OTHER than USB power. I tested the output from my wall adapter connected to RAW and to a random VCC pin, both have the same effect.
When powering the device via USB (USB to Deek-Robot ASP, then to Pro Mini), if I set my digital output pin to HIGH, I get 5v. This is enough to turn on a 5v relay that then supplies power from the supply to a small water pump. However, if I use the regulated wall-power, I get about 3.7 to MAYBE 4.15v, which sadly is not enough to switch the relay to the NO position.
I have tested the voltage coming from the USB ASP as well, it is 4.95v.
EDIT: The wall-plug voltage drops from 5.36 with no load except the meter to 4.7v with the Arduino and a couple LEDs attached, if that means anything.

RAW pin requires at least 6 V

Power supply was dropping to 3.8 volts under basic load, once it turned on some LEDs it was just too low to activate the relay switch. Crappy Chinese parts.

So your problem is mainly related to the weak power supply, and to your attaching it to the wrong pin (RAW instead of Vcc). However, external supply at Vcc + USB in parallel is forbidden. Additionally, there are only few 5V relais that need only 20 mA.

The question does not mention relays that I see.  However, there are many 5V, 20mA coil relays.  A simple search at Digikey turns up 42 for example in SMD and thruhole (with some duplication for differents methods of delivery packaging) https://www.digikey.com/products/en/relays/signal-relays-up-to-2-amps/189?k=relay&k=&pkeyword=relay&sv=0&pv1989=0&pv72=249586&umax671=20&rfu671=mA&sf=1&FV=-8%7C189&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25

"Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. "
That is the problem. RAW pin expects more like 6V to 6.5V for the regulator to output 5V.
If you are supplying 5V, connect to the 5V, or VCC and GND pins.
If you are connecting to USB via an  FTDI Basic or equivalent, and the 5V supply at the same time, then the computer may not like having the USB 5V line back driven from an external source (mine complains about a "power surge" and shuts down the USB port). Make up a breakout cable between the FTDI and the Promini and either disconnect the 5V line, or put a diode in series so the Promini can't supply 5V back thru the FTDI and into the USB port.  That way the FTDI chip is powered from USB, but the Promini is not, and all the hardware is happy.
Make sure to use series resistors with LEDs to avoid overcurrent from the Promini output pin, which will either damage the IO pin, possibly damaging the 328P, or damaging the LED from overheating from excess current.  (5.36V - 2.2V)/.02A = 156 ohm. A 180 ohm, 220, 270, 330, some value in that range will do. 1K will probably be fine, LEDs these days can be quite bright even at lower current; 20mA can be blindingly/annoyingly bright.


text:
How to respond dynamically by using File Containing Templates?
We are developing a Web Console and REST API for the NodeMCU V3 ESP8266, using ESPAsyncWebServer. We are facing some difficulties to serve dynamic pages using File Containing Templates! We're unable to replace REQ_HOST_ID with request->host() using Template Processor! The following code is working fine when a static host name is supplied.
// server->on("/", HTTP_GET, HomePage::index);

void HomePage::index(AsyncWebServerRequest *request) {
    Serial.println(request->host());
    auto processor = [](const String &var) -> String {
        if (var == "REQ_HOST_ID"){
        //  return F(request->host()); //FIXME
            return F("10.10.10.1");
        }
        return String();
    };
    AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/www/index.html", String(), false, processor);
    response->addHeader("Server", "Academia Web Server");
    request->send(response);
}

Edited:
Commented code causes a compile-time error and needs to be fixed to set the value of request->host(). request->host().c_str() causes the same error!
/Users/Chorke/Documents/Arduino/libraries/AcademiaCoreWeb/src/pages/HomePage.cpp: In lambda function:
/Users/Chorke/Documents/Arduino/libraries/AcademiaCoreWeb/src/pages/HomePage.cpp:16:22: error: 'request' is not captured
             return F(request->host()); //FIXME
                      ^
/Users/Chorke/Library/Arduino15/packages/esp8266/hardware/esp8266/2.6.3/cores/esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'
 #define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
                                                                            ^
/Users/Chorke/Library/Arduino15/packages/esp8266/hardware/esp8266/2.6.3/cores/esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'
 #define F(string_literal) (FPSTR(PSTR(string_literal)))
                                  ^
/Users/Chorke/Documents/Arduino/libraries/AcademiaCoreWeb/src/pages/HomePage.cpp:16:20: note: in expansion of macro 'F'
             return F(request->host()); //FIXME

Your help resolving this issue is highly appreciated.

Buggy in which way?

return F(request->host()); causes compile time error! Need to fix this and it belonging  issues. It's suppose to be there is two issue 1. request not accessible inside lambda expression and 2. directly belongs to the data type conversion

A compiler error is not a bug... please include the error message

Fixed:
auto processor = [request](const String &var) -> String {
    if (var == "REQ_HOST_ID"){
        return request->host().c_str();
    }
    return String();
};

Two mistake causes compile time error:

Needs to pass request to the Lambda expression
Need not to wrap the dynamic value with F() macro


text:
RTC 1307 when connected to a relay via Arduino Nano
I was posting a question but to be completely sure i did some more tweaking in the code and solved at least functionally my problem.
I decided to post it anyway to have suggestions for a better solution and / or help whoever has the same problem.
The project is a flowers watering application.
I set up an RTC connected with Arduino Nano using LEDs to simulate the operations, it works really well, no mistakes when RTC.readTime requests.
Once satisfied I replaced the LED with a relay to be connected to the pump, and then the problem appeared:
Randomly the reading is not correct, something like (YYYY/MM/DD H:M:S) represented as 165/0/165 0:165:0.
The combinations of 165 and 0s are completely random but only 165 and 0s are present.
My solution was to check after each reading if there was any 165s into the returned data, and if yes, read the time again. This was the medicine.
This mistake appears only and always when i replace the LED with a relay, with or without connected charge.
Circuitry is very simple as well as is the code.
  RTC.readTime();
  if (RTC.h == 165 ||
      RTC.m == 165 ||
      RTC.s == 165 ||
      RTC.dd == 165 ||
      RTC.mm == 165 ||
      RTC.yyyy == 165 ) {
        RTC.readTime();
        Serial.print("Mistake found in step N. ");
        Serial.println(countCycles);
  }

  countCycles ++;

From the printout I can confirm that the mistake is absolutely random but never immediately subsequent to another mistake.
Any clues?
Thank you for any comments

Did you use a relay or a all-in-one relay module/breakout? A relay itself requires some additional components to connect it to an Arduino. They also require quite a bit of current, which can cause a short voltage drop, which some components don't like. Turning a relay off can cause some back EMF, which some components don't like. Adding a large capacitor might be enough to fix these issues.

Hi Gerben, thank you for your answer.

Answer to your question first: I used a Relay module from Elegoo that as said does not need any other components to be connected with Arduino, nevertheless i believe that a condenser will not do any harm. Which capacity do you think suitable? and where to fit it? my electronic skill is quite low 'cause i am more a SW guy beginning to play with Arduino for fun while retired. I dont know where to put a picture here, otherwise i may have posted a picture of the module. Ciao

Just forgot to say that i powered the circuit with a proper source with load of current available.

I'd try a 10-100 uF (electrolytic) capacitor near the module. It might be that your power-supply can't handle the very sudden increase in current fast enough. I too came from a SW background. When things start to act weird, it's mostly a power issue, I've learned.

Do you mean between + and - on the power supply?  An update on the mistakes is that they appear in sequence as well so i had to set a do - while loop.

Yeah, sorry. I should have mentioned that. Between + and - (Vcc and GND).