text:
How to send data from firebase php to arduino?
In the project I am working on

I want to send data to firebase going to arduino this specifically by
  sending an information to change the wifi

SSID
password

materials I used:

esp8266-01
arduino uno r3
firebase
web server (000webhost)

code for arduino

    #include <SoftwareSerial.h>
#include <DHT.h>;
SoftwareSerial Serial1(10, 11);
#define Trash "Trash3"
#define DHTTYPE DHT11
#define DHTPIN 2
#define TRIGGER_PIN 4
#define ECHO_PIN 3

DHT dht(DHTPIN, DHTTYPE, 11);

float humidity, temp_f;
int distance;
long duration;

String buff(64);
String getStr(128);

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  //Serial1.resetESP();
  delay(2000);
  Serial1.setTimeout(5000);

  dht.begin();
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
      ; // do nothing
  }
  Serial.println("OK, Connected to WiFi.");

  sendCommand("AT+CIPSTA?");
  //sendCommand("AT+CIPDNS_CUR?");
  sendCommand("AT+CIPSTAMAC?");

}

void loop() {

  temp_f = dht.readTemperature();
  humidity = dht.readHumidity();
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  duration = pulseIn(ECHO_PIN, HIGH);
  distance = duration * 0.034 / 2;

  // connect to server
  if (sendCommand("AT+CIPSTART=\"TCP\",\"gg.com\",80")) {
    Serial.println("connected to Cloud");

    // build HTTP request
    getStr = "GET /upload.php?trash=";
    getStr += Trash;
    getStr += "&distance=";
    getStr += distance;
    getStr += "&temp_f=";
    getStr += temp_f;
    getStr += "&humidity=";
    getStr += humidity;
    getStr += " HTTP/1.1\r\n";
    getStr += "Host: gg.com\r\n\r\n";

    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

      // send HTTP request
      Serial.println(getStr);
      Serial1.print(getStr);

      // print HTTP response
      if (Serial1.find("+IPD,")) { // response received
        int l = Serial1.parseInt();
        while (l > 0) {
          if (Serial1.available()) {
            Serial.write(Serial1.read());
            l--;
          }
        }
        Serial.println("--------------");
      } else {
        Serial.println("no response");
      }
    } else {
      Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
  } else {
    Serial.println("Error connecting");
  }
}

bool connectWiFi() {

  if (!sendCommand("ATE0")) // echo off
    return false;
  if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
  if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;
  return sendCommand("AT+CWJAP=\"CAPSTONE\",\"capstonemis\"");
}

bool sendCommand(const char* cmd) {
  Serial.println(cmd);
  Serial1.println(cmd);
  while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
      Serial.println(buff);
      if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
        return true;
      if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
        return false;
    }
  }
}

code for firebase

<?php

require 'firebaseLib.php';
$Trash = $_GET["trash"];

$Distance = $_GET["distance"];
$Temperature = $_GET["temp_f"];
$Humidity= $_GET["humidity"];

// --- This is your Firebase URL
$baseURI = 'https://thesis1-69.firebaseio.com';
// --- Use your token from Firebase here
$token = 'gg';
// --- Here is your parameter from the http GET

$devicestatus= array('Distance' => $Distance,'Temperature' => $Temperature,'Humidity' => $Humidity);

$firebasePath = '/thesis1-69/';

$full= array($Trash => $devicestatus);

/// --- Making calls
$fb = new Firebase($baseURI, $token);
$fb -> update($firebasePath, $full);

?>

any  guide and help can help me a lot
thank you so much :)

this is code from my chat with Xiaomy https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

yeah I am xiaomy

@Juraj can we create a chat?

why as new user?

I can't reply on the conversation and can't post new question in the recent account

we made an error in this code. change String buff(64); String getStr(128); to String buff; String getStr; and add  buff.reserve(64);  getStr.reserve(256); as first in setup()

no need to add some code on the PHP?

is this right sir?
void setup() {
buff.reserve(64);
getStr.reserve(256);
Serial.begin(9600);

I just wanna change the wifi through POST so I want to used it
I will send data to firebase then will received by the arduino

good morning sir
thank you sir
can you provide me an example of receiving the information back to arduino
I just want to change the SSID & password of arduino (esp-01) by using an app
that app uses the firebase to send data to web server back to arduino
so the wifi will be change
then no need to manually code it by using arduino IDE

it would be better to return the new ssid and password as a response of the existing request, which sends sensor data. of course only if the wifi should reconnect

so I will use the POST?

POST request is different from GET request only in one thing: it can send data in the 'body'. as you can see in my answer the data send are not in the URL, but after the request header. the response format is same for GET and POST

ah sorry about that
thank you for the right idea sir :)
but how can I get what I want?

so it will be depending on the arduino code or firebase php?

first in php add the response if the ssid should change. the Arduino sketch as it is  now prints the received response. then you can ask how to parse and process it

so likely GET request too?

I just thought to make a variable but I don't know how the firebase data will be receive by the web server

add a response to the GET request which delivers the sensor data

same format with the trash?

the GET request you have, can return the new ssid and password

I'll set 2 variables?
I don't know how can I make it
because GET request is used by the arduino to send data from web server to firebase to app

and the new ssid should be retrieved from somewhere else? not over the php page?

the app is connected to firebase
so the firebase will received the ssid and password
set by the user that use the app

I think php page will be a gateway between the arduino and firebase

so the php page can return the new ssid and password as a response to the GET request it received with the sensor data.

yes sir
I think

Comments are not for extended discussion; this conversation has been moved to chat.

add global variable String data; and in loop()
data = "trash=";
data += Trash;
data += "&distance=";
data += distance;
data += "&temp_f=";
data += temp_f;
data += "&humidity=";
data += humidity;

// build HTTP request
getStr = "POST /upload.php HTTP/1.1\r\n";
getStr += "Content-type: application/x-www-form-urlencoded\r\n";
getStr += "Content-length: ";
getStr += data.length();
getStr += "\r\nHost: gg.com\r\n\r\n";
getStr += data;

Thank you sir
so the data, it represents SSID and password?

I wanna keep both the GET and POST

for example
I will set variable namely data1 and data2
then on the
return sendCommand("AT+CWJAP="CAPSTONE","capstonemis"");
}
will be replace
return sendCommand("AT+CWJAP="data1","data2"");
}
is this right sir?

I don't need to add some PHP code on the website server?

so you want to "get" data. why do you want to do it with a "post" request?

ah it doesn't need a "post" request to get data from firebase/web server?
I got the wrong idea on using "post"
I thought it was for receiving data from firebase to arduino
I will change the wifi of arduino (esp8266-01) by using an app
that app send data to firebase then it will send data(SSID & password) to arduino


text:
esp8266 code not working anymore
hi i have developed year age an Adruino application that allows me send and receive data from a mobile application using esp8266 esp01 back then it worked really well but now i tried to rerun the same code using a different esp8266 esp01 the app won't work so i was wondering if the firmware flash has to do something with it because flashed the first esp firmware and the second is not but a friend of mine worked with the second one fine so here is my code
float Temperatur;
  String Temperatur1;
#include <SoftwareSerial.h>

#define DEBUG true

       SoftwareSerial esp8266(8,9);
void setup()
{
  Serial.begin(9600);
        esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

Serial.println("Server START");
  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 //sendCommand("AT+CWJAP=\"AF23_WI-FI_476C\",\"A776RAEQ\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  /*
  Temperatur=(5.0*analogRead(A0)*100.0)/1024;
   Serial.println(Temperatur);
  Temperatur1=(5.0*analogRead(A0)*100.0)/1024.0;
   Serial.println(Temperatur1);

  if(Temperatur > 50)

   {digitalWrite(11, HIGH);
    digitalWrite(12,LOW);}
    */
  if(esp8266.available()) // check if the esp is sending a message
  {

     Serial.println("esp avai");
    if(esp8266.find((char*)"+IPD,"))
    {Serial.println("found ipd");
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
//      sendHTTPResponse(connectionId,Temperatur);
     esp8266.find((char*)"pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

  if((pinNumber==12)&&(pinNumber!=11))
     {digitalWrite(12, HIGH);
     digitalWrite(11,LOW);}
    if((pinNumber==11)&&(pinNumber!=12))
     {digitalWrite(12, LOW);
     digitalWrite(11,HIGH);}
    if((pinNumber==13)&&(pinNumber!=12)&&(pinNumber!=11))
     {digitalWrite(12, LOW);
     digitalWrite(11,LOW);}

     // build string that is send back to device that is requesting pin toggle
     String content;

     if(pinNumber==11)
     {
       content = "L'exutoire est en cours d'ouverture";
     }
     else if(pinNumber==12)
     {
       content = "L'exutoire est en cours de fermeture";
     }
     else if (pinNumber==13)
   {  content = " Il est arrêter ";}

       else if (pinNumber==10)
   {  content =  Temperatur1 ;}
     sendHTTPResponse(connectionId,content);
    }
  }else {
    Serial.println("not available");
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

at first i got no response from the esp  then i tried to change esp8266.begin(9600); to 115200  i got this
    Server START
    AZ+RST

    OK‡

     ets Jan  8 2013,rst cause;2, boot modd:(3,7)

    loaf 0x40100000, len 2408, soom 16
    tail 8
    chksum 0xe5
    load 0x3ffe8000, len 776, room 0
    tail 8
    chksum 0a tail 8m8r   S5o
Œãœ
AT+CWMODQO¦CC¡C¡jªHüAT+CIFSR
+CHFSR:APIP,"182.168.4.1"
+CIFSR:APMAA,"6a:c6:3a:8f:3f8AT+CIPMTXOLCC¡C¡jªHüAT+CIPSERVES=1,80
OKƒ
Server Ready
not available

Newer ESP8266 boards have a newer version of the AT firmware on them by default. This runs at 115200 baud compared to the 9600 baud of the old ones.
However, you cannot run SoftwareSerial reliably at 115200 baud.
You need to reconfigure the ESP-01 to run at 9600 baud using the AT commands.
There are a number of different commands depending on the firmware version. One of these may work:
AT+IPR=9600
AT+UART_DEF=9600,8,1,0,0
AT+CIOBAUD=9600

thank you very much i tried to add one of them but nothing changes in fact i no longer get responses neither at 115200 baud.nor at 9600 baud and the blue led of the esp-01 is lightning

That is a common complaint. You may want to re-flash the firmware on there. There's plenty of tutorials around for how to do that.

source: Stack Exchange

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

sort: votes


text:
Options for powering a Futaba servo
In one of my earlier questions it was determined for me that my Futaba Servo should not be powered directly from the 5v pin of my Arduino and should instead be powered by an alternative source. I was told the Servo requires a “high current 5 volt power supply” so I’m wondering what my best options are as my knowledge in servo control is quite limited. Is there some type of board that helps with this? Do I need a specific battery? If the servo needs a battery could it run off of the same battery as the arduino? Im trying to keep my design as compact as possible so multiple battery packs could pose complications.
The specific information can be found here.
Thanks for any help!

Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.
These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.
The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.
4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.
All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to MATCH voltage ratings of a power source to the device being powered, and ensure the device being powered DOES NOT EXCEED the current rating of the power source.

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


text:
My PIR sensor output changes but digitalread high all the time
This is my final project, I have to communicate with two wemos d1 mini by LAN. The problem is that when I read the state of the PIR sensor it is "HIGH" all the time, but when I connect the led light, it blinks as I move my hand - so the sensor is not broken.
I have tried with D7,D2,D3 and its the same... code is in the loop body
PIR output is directly connected to the D0.

#include <SPI.h>
#include <ESP8266WiFi.h>

int pirPin = 0;
int val=0;
/*int led1 = 1;
int  led2 = 3;
int led3 = 4;
int senzor2 = 5;
int led4 = 6;
int led5 = 7;
//int led6 = ;
*/
int ledPin = 2;
String ID = "001";

boolean uspostavljenostVezeSaServerom=false;
char ssid[] = "arduinoserver";           // SSID od mreže na koju se spaja
char pass[] = "arduinoserver";            // lozinka mreže na koju se spaja

unsigned long askTimer = 0;

IPAddress server(192,168,1,80);       // fiksna adresa servera na koji se spaja arduino(klijent)
IPAddress ip(192, 168, 1, 79);
IPAddress gateway(192,168,1,1);           // gateway mreže (nije obavezno)
IPAddress subnet(255,255,255,0);          // subnet mreže (nije obavezno)

WiFiClient client;

void setup() {
  pinMode(pirPin,INPUT_PULLUP);

  Serial.begin(115200);               // podešavanje bauda za komunikaciju
  spajanjeNaMrezu();                  // spajanje na mrežu
}

void loop () {

  if(uspostavljenostVezeSaServerom==false)spajanjeSaServerom();  // arduino uspostavlja komunikaciju sa serverom
  if(WiFi.status() != WL_CONNECTED) spajanjeNaMrezu();

val = digitalRead(pirPin);
  Serial.println(val);
delay(300);

  //Serial.println(digitalRead(val));

 /* client.connect(server, 80);   // Spajanje na server
  client.flush();
  client.println(ID);
  String answer = client.readStringUntil('\r');   // čekanje povratne poruke dok ne dođe do znaka "/r"
  */
}

void spajanjeSaServerom(){

  String answer;
  while(answer != "OK")
    {
      Serial.println("Uspotavljanje veze s serverom...");
      client.connect(server, 80);   // Spajanje na server
      client.flush();
      client.println(ID); // slanje koda klijenta serveru
      Serial.println("Šaljem ID: " + ID);
      answer = client.readStringUntil('\r');
      Serial.println("Odgovor servera: " + answer);
    }

  Serial.print("Veza uspostavljena!");
  uspostavljenostVezeSaServerom=true;
}

void spajanjeNaMrezu(){
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, pass);             // spajanje s ruterom
  while (WiFi.status() != WL_CONNECTED) {
      Serial.println("Spajanje na mrežu...");
      delay(500);
  }
  Serial.println("Uspjesno spajanje na WiFi");
  Serial.print("Status: "); Serial.println(WiFi.status());
  Serial.print("IP: ");     Serial.println(WiFi.localIP());
  Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
  Serial.print("SSID: "); Serial.println(WiFi.SSID());
  Serial.print("Signal: "); Serial.println(WiFi.RSSI());

}

use Dx constants. pirPin = D2; https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

Yeah, int pirPin = 0; does not look right. Instead use int pirPin = D0;

I tried before, but not working :(
"error: 'D0' was not declared in this scope"

did you select "Wemos D1 R2 or mini" in Tools menu?

I selected ESP8266, that was the problem :). Thanks alot !


text:
Fritzing part repositry - GY-30
There is no GY-30 light sensor part design in the standard Fritzing repository.

Is there an official alternative part repository containing Fritzing fzpz file for this sensor?  Does it go by any other name or part code?

Design your own part. Or find some other I2C breakout in the fritzing library that has the same pinout. Or use a 5 pin header instead.

a bit time consuming, and i'm sure that there is something out there

This part also goes by the name BH1750.  And that is available in the Fritzing  parts library.

This is the correct one : http://goo.gl/JiTmQt  it is called BH1750FVI Breakout Board (GY-30). The bare BH1750 has a different pin order.

thanks for reviving this.  i've been using the GY-302.  I'll give this part a look, tks!!!!


text:
ESP32 Alexa Integration; Cannot correctly control more than one device
I created a garage door opener recently that is controllable through Alexa, using this library: https://github.com/Aircoookie/Espalexa
Everything is operating as expected, meaning I was able to detect my device and control the garage (using routines).
The issue came when I went to integrate Alexa into another previously completed/operational project. I was able to successfully discover and control the second board, kind of.
At this point I have added two ESP32 boards to Alexa, named differently of course. When I went to test the second board(meaning that it was successully discovered, and the ESP was receiving most commands) I noticed that Alexa was also opening my garage. If i unplugged my garage door opener(first board to be added) the second board starts to all receive commands, although degraded; for example;
In the above noted library Alexa should be able to control 'brightness' of dimmable lights. Of course this device is not a dimmable light but for the purposes of the integration, this library emulates smart lights. I am never able to see Alexa trying to set a brightness whose value is not 0.
Example, this is successfully executed on board 2, sometimes only when board 1 is unplugged:
void alexa_change_hdmi(EspalexaDevice* d) {
    Serial.println("Executing");
    uint8_t brightness = d->getValue();
    Serial.println(brightness);
    doing more things....

Here, brightness is always printed as 0.
So, after I added board X to alexa and tested successfully, I added board Y to alexa. Board X receives both commands for X and Y most of the time. Vice versa if board Y is the only device on. This is not intended by design. I would like to control them separately(preferably through the use of one alexa device).
I'm not sure if this (^) is related to the inability of Alexa to tell the two distinct board apart. I'm not sure why i'm not getting a brightness level, I would like to use it to make decisions, example;
if (brightness == '2.55') {
unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
}

Has anyone seen this issue integrating several ESP32 devices with one Amazon Echo? Has anyone ever gotten brightness to successfully pass into the function that alexa triggers?
EDIT*
After doing some more testing it appears that ESPALEXAWITHASYNCWEBSERVER is causing Alexa to not be able to differentiate between the distinct boards. This implies that if you want to use more than one device with this library, you cannot use the async example.
As a side effect, brightness always returns 0 when not using the async library, meaning you can really only use this library to control on and off state, not brightness, if you have more than one ESP device. ASYNC example correctly returns brightness, all other examples return 0, no matter what you set the brightness to.

Try this library , in past i have used 5 device at a time
fauxmoesp

Faumo is not working for me, unable to detect devices


text:
DHT11 sensor providing -999 outputs
I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.
My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.
if the image doesn't load this is the code;
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  constrain (DHT.temperature, -25, 70);
  constrain (DHT.humidity, 0, 90);

  if((DHT.temperature || DHT.humidity) > -25)
  {
  Serial.print("Temperature, Humidity = ");
  Serial.print(DHT.temperature);
  Serial.print(", ");
  Serial.println(DHT.humidity);
  delay(1000);
  }
}

Thanks in advance for help or direction to help.

-999 means that it didn't get a result from the DHT.  You need to filter them out - which you are attempting to do, but wrongly.
Your line of code:
if((DHT.temperature || DHT.humidity) > -25) {

is not doing what you thing it is.
If you start from the inner most brackets and "reduce", you get:
Is DHT.temperature or DHT.humidity?

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:
Is DHT.temperature not 0 or DHT.humidity not 0?

And of course that will be "true" in 99.99999% of situations.  So insert that into the if again:
if (true > -25) {

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0.  So is 1 greater than -25? Yes. It is.
Instead you should be testing each value separately:
if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

Also your constraints are doing nothing.  constrain() doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable.  So you should:
float temperature = constrain (DHT.temperature, -25, 70);

And then you can use the temperature variable instead of DHT.temperature, and you can guarantee that it will be between -25 and +70.

As I recall you're not supposed to read from a DHT11 or DHT22 more frequently than every 2 seconds. If you wait until 2 seconds pass before reading again you should avoid -999 readings.
Majenko's answer shows you how to check for and skip out-of-range readings, but only reading once every 2 seconds should let you avoid them entirely.
Note that you should also check for NaN (not a number) values returned. That means there was a read error, which does happen from time to time.

Try to use Pull up resistor. Connect the 4.7K resistor parallel to 5v (if your supply for DHT11 is 5v 4.7K is Good, for other voltage, you need another value of resistor) and Data pin.


text:
Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay)
I've setup my NodeMCU v3 with this relay and I got this:

When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a D1 Mini relay shield* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).
So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a logic level converter 3V-5V between the NodeMCU GPIO and the relay IN, would it work?
Thanks in advance.
*must say mine is a clone, but it works

what does this mean? I can only turn it on once

Have you used a multimeter to check if the contacts are switching?

it he relay expects 5 V as HIGH signal, that it is possible that it doesn't read 3.3 V as HIGH. the D1 shield is made for 3.3 V signal

a logic level converter would likely work in your situation (too low of a high voltage to trigger)

in my previous comment "it he" is "if the"

@jsotola I can toggle it once right after I power up the NodeMCU.

@sa_leinad I did. the pin goes from 0V to 3V.

@Juraj I saw people commenting they triggered the relay with 2.5V. So I guess it should work with 3V. But..you never know.

@dandavis I'm definitely getting myself a logic level converter as soon as Monday and I'm gonna try it out.

More than likely it is a faulty board.
The schematic for the D1 Mini relay shield can be found here.
I couldn't find a schematic for the relay that is having the problems but you can see from the picture below that it has 2 LEDs (power and relay signal), a flyback diode and a FET or transistor.

As you can see the circuits are pretty much the same. So my conclusion is that you have a faulty relay board.

that could be tested by giving the trigger pin 5v instead of 3.3. i bet it works fine like that...

Yeah, I don't know much about schematics. But I guessed it was similar to the d1 shield. But I'll surely try what @dandavis suggested and apply 5V to the trigger pin. I'm also getting another relay just like that to see if I can reproduce the issue or if it works with 3V.

@BrunoCardosoDantas did you test it with 5V as per DanDavis' comment?

@sa_leinad sorry for the delay. took a while to get everything. I did tho. Didn't work. I've got a logic level converter and also another relay just as the one that I had the issue. The first mentioned relay didn't work with 3V nor 5V. The new relay didn't work with 5V on VCC and 5V on the INPUT. Yeah, I know. But it did work with 3V on both of them. Don't ask me why tho. It just did.

Ok, so:

I've bought a logic level converter.
Bought another relay.

Now to the results:

With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
With the second relay (the new one), funny enough.. Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.
I guess it should work with 5v...? Right?
Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.

The D1 Mini relay shield would make sense that it works at 3V as that is what the both the Wemos and nodeMCU boards output for a logic high.


text:
More about Problems with using esp8266
I'm running a project under https://www.youtube.com/watch?v=2AL7HfiRlp4&t=23s
I encounter a problem with "deadly error: ESP8266WiFi.h: No such file or directory", the code indicates '' #include  ''.
I read a conversation between John Romkey and Thonka on July 5th '18. I've deleted all libraries that mention esp8266, esp32 and wifi. But from the conversation I don't know what libraries I have to use now? I use the following code:
/*
 * Mert Arduino and Tech - YouTube
 * WiFi Robot controlled by Phone (WiFibot/Android/IoT/ESP8266)
 * NodeMCU ESP8266 Tutorial 03
 * Please Subscribe for Support - https://goo.gl/RLT6DT
 */

/* include library */
#include <ESP8266WiFi.h>

/*
 * If you have no idea about this library, you can watch the tutorial below
 * NodeMCU ESP8266 Tutorial 01: Programming NodeMCU ESP-12E Using Arduino IDE
 * https://youtu.be/NtyFx1frYB0
 */

/* define port */
WiFiClient client;
WiFiServer server(80);

/* WIFI settings */
const char* ssid = "YOUR SSID";
const char* password = "YOUR PASSWORD";

/* data received from application */
String  data ="";

/* define L298N or L293D motor control pins */
int leftMotorForward = 2;     /* GPIO2(D4) -> IN3   */
int rightMotorForward = 15;   /* GPIO15(D8) -> IN1  */
int leftMotorBackward = 0;    /* GPIO0(D3) -> IN4   */
int rightMotorBackward = 13;  /* GPIO13(D7) -> IN2  */

/* define L298N or L293D enable pins */
int rightMotorENB = 14; /* GPIO14(D5) -> Motor-A Enable */
int leftMotorENB = 12;  /* GPIO12(D6) -> Motor-B Enable */

void setup()
{
  /* initialize motor control pins as output */
  pinMode(leftMotorForward, OUTPUT);
  pinMode(rightMotorForward, OUTPUT);
  pinMode(leftMotorBackward, OUTPUT);
  pinMode(rightMotorBackward, OUTPUT);

  /* initialize motor enable pins as output */
  pinMode(leftMotorENB, OUTPUT);
  pinMode(rightMotorENB, OUTPUT);

  /* start server communication */
  server.begin();
}

void loop()
{
    /* If the server available, run the "checkClient" function */
    client = server.available();
    if (!client) return;
    data = checkClient ();

/************************ Run function according to incoming data from application *************************/

    /* If the incoming data is "forward", run the "MotorForward" function */
    if (data == "forward") MotorForward();
    /* If the incoming data is "backward", run the "MotorBackward" function */
    else if (data == "backward") MotorBackward();
    /* If the incoming data is "left", run the "TurnLeft" function */
    else if (data == "left") TurnLeft();
    /* If the incoming data is "right", run the "TurnRight" function */
    else if (data == "right") TurnRight();
    /* If the incoming data is "stop", run the "MotorStop" function */
    else if (data == "stop") MotorStop();
}

/********************************************* FORWARD *****************************************************/
void MotorForward(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,HIGH);
  digitalWrite(rightMotorForward,HIGH);
  digitalWrite(leftMotorBackward,LOW);
  digitalWrite(rightMotorBackward,LOW);
}

/********************************************* BACKWARD *****************************************************/
void MotorBackward(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorBackward,HIGH);
  digitalWrite(rightMotorBackward,HIGH);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(rightMotorForward,LOW);
}

/********************************************* TURN LEFT *****************************************************/
void TurnLeft(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(rightMotorForward,HIGH);
  digitalWrite(rightMotorBackward,LOW);
  digitalWrite(leftMotorBackward,HIGH);
}

/********************************************* TURN RIGHT *****************************************************/
void TurnRight(void)
{
  digitalWrite(leftMotorENB,HIGH);
  digitalWrite(rightMotorENB,HIGH);
  digitalWrite(leftMotorForward,HIGH);
  digitalWrite(rightMotorForward,LOW);
  digitalWrite(rightMotorBackward,HIGH);
  digitalWrite(leftMotorBackward,LOW);
}

/********************************************* STOP *****************************************************/
void MotorStop(void)
{
  digitalWrite(leftMotorENB,LOW);
  digitalWrite(rightMotorENB,LOW);
  digitalWrite(leftMotorForward,LOW);
  digitalWrite(leftMotorBackward,LOW);
  digitalWrite(rightMotorForward,LOW);
  digitalWrite(rightMotorBackward,LOW);
}

/********************************** RECEIVE DATA FROM the APP ******************************************/
String checkClient (void)
{
  while(!client.available()) delay(1);
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

install esp8266 boards package https://github.com/esp8266/Arduino#installing-with-boards-manager

I installed it. Anyway #include <ESP8266WiFi.h>. ''ESP8266WiFi.h:No such file or directory''

did you select an esp8266 board in tools menu?

yes, many boards

reinstall esp8266 boards package

OK!!! I was a bad installer


text:
buzzwire game in arduino
I'm tring to make buzzwire game in arduino and this is what I have from now on.
#include <TM1637.h> // include display library
#include <pitches.h> // include pitches

TM1637 *_display = new TM1637(12, 13); // create display object, 12 = CLK (clock), 13 = D10 (data)

// music
int songState = 0;

int melody[] = {
 NOTE_F4, NOTE_E4, NOTE_D4, NOTE_CS4,
 NOTE_C4, NOTE_B3, NOTE_AS3, NOTE_A3,
 NOTE_G3, NOTE_A3, NOTE_AS3, NOTE_A3,
 NOTE_G3, NOTE_C4, 0,

 NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
 NOTE_GS3, NOTE_A3, NOTE_F4, NOTE_C4,
 NOTE_C4, NOTE_A3, NOTE_AS3, NOTE_AS3,
 NOTE_AS3, NOTE_C4, NOTE_D4, 0,

 NOTE_AS3, NOTE_G3, NOTE_G3, NOTE_G3,
 NOTE_FS3, NOTE_G3, NOTE_E4, NOTE_D4,
 NOTE_D4, NOTE_AS3, NOTE_A3, NOTE_A3,
 NOTE_A3, NOTE_AS3, NOTE_C4, 0,

 NOTE_C4, NOTE_A3, NOTE_A3, NOTE_A3,
 NOTE_GS3, NOTE_A3, NOTE_A4, NOTE_F4,
 NOTE_F4, NOTE_C4, NOTE_B3, NOTE_G4,
 NOTE_G4, NOTE_G4, NOTE_G4, 0,

 NOTE_G4, NOTE_E4, NOTE_G4, NOTE_G4,
 NOTE_FS4, NOTE_G4, NOTE_D4, NOTE_G4,
 NOTE_G4, NOTE_FS4, NOTE_G4, NOTE_C4,
 NOTE_B3, NOTE_C4, NOTE_B3, NOTE_C4, 0
};

int tempo[] = {
 8, 16, 8, 16,
 8, 16, 8, 16,
 16, 16, 16, 8,
 16, 8, 3,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 12,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 12,

 12, 16, 16, 16,
 8, 16, 8, 16,
 8, 16, 8, 16,
 8, 16, 4, 16,

 12, 17, 17, 17,
 8, 12, 17, 17,
 17, 8, 16, 8,
 16, 8, 16, 8, 1
};

// non blocking setup
// free play
unsigned long previousMillis1 = 0; // time words last changed
const long interval1 = 1500; // interval between changing

// music
unsigned long previousMillis2 = 0; // time last changed
const long interval2 = 100; // interval between notes

int displayStatus = 0; // keep track of what's displayed
int mode = 0; // keep track of game mode -- change to 0 or 1 for different modes

bool countdown = false;

unsigned long previousMillis3 = 0; // time last changed
const long interval3 = 1000; // interval between countdown
int count = 20; // challenge mode timer

void setup() {
 // put your setup code here, to run once:
 pinMode(9, INPUT); // setup circuit
 pinMode(10, OUTPUT); // setup buzzer 1
 pinMode(11, OUTPUT); // setup buzzer 2
 pinMode(2, INPUT); // setup button

 _display->set(5); // set brightness
 _display->point(false); // remove colon
 _display->init(); // start display
}

void loop(void) {
 // put your main code here, to run repeatedly:
 int conductVal = analogRead(9);

 Serial.print("Conduction sensor reads");
 Serial.println(conductVal);

 if(conductVal>410){
  //digitalWrite(10,HIGH);
  tone(11,550,400);
  tone(10,0,400);
  delay(5000);
  countdown=false;
 }
 if(mode == 0) {
   // free play
 toggleFreePlay();

 }
 else {
 // challenge mode
 if(digitalRead(2) == HIGH) {
 delay(25);
 if(digitalRead(2) == HIGH) {
 countdown = true; // stop the countdown
 }
 else {
 countdown = false; // stop the countdown
 }
 }
 if(countdown) {
 showCountdown(); // advance countdown
 }
 }
 if(digitalRead(10) == HIGH) {
 delay(25);
 if(digitalRead(10) == HIGH) {
 while(digitalRead(10) == HIGH) {
 buzz(11, NOTE_B0, 1000/24);
 }
 }
 }
 else
 sing();
}

void showCountdown() {
 // countdown the time remaining
 unsigned long currentMillis = millis(); // current time
 if (currentMillis - previousMillis3 >= interval3) {
 previousMillis3 = currentMillis;
 --count;
 showNumber(count);
 if(count == 0) {
 // game over
 countdown = false;
 count = 20;
 // reset countdown
 // buzz 3 times
 buzz(11, NOTE_B0, 1000/24);
 delay(100);
 buzz(11, NOTE_B0, 1000/24);
 delay(100);
 buzz(11, NOTE_B0, 1000/24);
 }
 }
}

void showNumber(int number) {
 // show numbers (maximum 99) on display
 _display->display(0, 25); // write - to segment 1
 _display->display(3, 25); // write - to segment 4

 // write number to middle of display

  if(number == 10)
  {
     _display->display(1,1);
   _display->display(2,0);
  }
  else if(number > 9)
  {
   _display->display(1,1);
   int newVal = number - 10;
   _display->display(2, newVal);
  }
  else
  {
     _display->display(1,0);
   _display->display(2,number);
  }
}

void toggleFreePlay() {
 // scroll between words without blocking
 unsigned long currentMillis = millis(); // current time
 if (currentMillis - previousMillis1 >= interval1) {
 previousMillis1 = currentMillis;
 if(displayStatus == 1)
 showPlay();
 else
 showFree();
 }
}

void showPlay() {
 // write "PLAY" to the display
 _display->display(0, 21); // write P to segment 1
 _display->display(1, 18); // write L to segment 2
 _display->display(2, 10); // write A to segment 3
 _display->display(3, 4); // write Y to segment 4
 displayStatus = 2;
}

void showFree() {
 // write "Free" to the display
 _display->display(0, 15); // write F to segment 1
 _display->display(1, 23); // write r to segment 2
 _display->display(2, 14); // write E to segment 3
 _display->display(3, 14); // write E to segment 4
 displayStatus = 1;
}

void buzz(int targetPin, long frequency, long length) {
 /* Buzzer example function by Rob Faludi
 http://www.faludi.com
 https://gist.github.com/AnthonyDiGirolamo/1405180
 */
 long delayValue = 1000000/frequency/2; // calculate the delay value between transitions
 //// 1 second's worth of microseconds, divided by the frequency, then split in half since
 //// there are two phases to each cycle
 long numCycles = frequency * length/ 1000; // calculate the number of cycles for proper timing
 //// multiply frequency, which is really cycles per second, by the number of seconds to
 //// get the total number of cycles to produce
 for (long i=0; i < numCycles; i++){ // for the calculated length of time...
 digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphragm
 delayMicroseconds(delayValue); // wait for the calculated delay value
 digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphragm
 delayMicroseconds(delayValue); // wait again for the calculated delay value
 }
}

void sing() {
 // play the song in a non blocking way
 unsigned long currentMillis = millis();

 if (currentMillis - previousMillis2 >= interval2) {
 previousMillis2 = currentMillis;
 int noteDuration = 1000 / tempo[songState];
 buzz(10, melody[songState], noteDuration);
 int pauseBetweenNotes = noteDuration;
 delay(pauseBetweenNotes);

 // stop the tone playing:
 buzz(10, 0, noteDuration);

 ++songState;
 // start song again if finished
 if(songState > 79) {
 songState = 14; // skip intro
 }
 }
}

First I want to stop continuous buzzing during the game, and I want to make buzzer react when the handle touches the course. Plus, I also want to know how can I change the mode in arduino( and breadboard).

what is the question?

First align your code (make the { and } nicely arranged, to easier read your sketch.

change the mode ... what is mode?


text:
[Solved]How to make my stepper motor run clockwise and counterclockwise?
I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.
I am using AccelStepper Library
Here is my code:

#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
}

I have tried to add delay and counterclockwise code but its not working.
#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  Serial.println("clockwise");
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
  Serial.println("counterclockwise");
  stepper.setSpeed(-1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
}

Try to use lower values for spinning, let's say 150. Some drivers are easy overheating when using higher speeds.

it rotate only in one direction ... which direction is that?

No its not about heating or higher speed
If i put 1200 it move perfectly clockwise if i put value to -1200 it move perfectly counter-clockwise
But if i try to use both it creates problem

What hardware do you use? I mean, what is the stepper motor driver? There are some drivers which overheat easily and (due to built-in overheat protection) stop operation.

@smajli its not about heating
i am missing something with code
if i rotate in 1 direction only with default code it works fine.
Motor - NEMA17 5.5Kgcm Stepper Motor

Hi here it the reference to the library functions that are available in accelstepper library.
Go through the link, it will provide you the issues with your code and example for your application like @smajli said steps more than 1000 is unreliabe, here you can see setSpeed(float) function where setting negative or positive sign selects the direction and value set the speed of rotation.

than you for your input but i am still struggling to understand functions :(
i have changed speed to 1000 and behavior is still same

did you tried -500 and 500 ?

yes buddy seems i can't use delay function in loop but i am not getting how to use other function of this library or use millis function

From the AccelStepper website: link

Speeds of more than 1000 steps per second are unreliable

Try to change the speed to lower value, and let us know what is the outcome.

thank you for pointing out but still same behavior


text:
sim800l only receiving SMS after serial monitor is started otherwise not receiving
I am using SIM800L and Arduino Uno.
The programme is working fine when I turn the serial monitor on using Arduino IDE but when I start the Arduino board by using the adapter it is not receiving anything. I have blinked LED on receiving SMS.
#include <SoftwareSerial.h>

SoftwareSerial wire(3, 2);
String  Grsp;

void setup()
{
   wire.begin(9600);
   Serial.begin(9600);
   wire.println("AT+CMGF=1");
    wire.println("AT+CNMI=2,2,0,0,0");
  pinMode(8, OUTPUT);
  digitalWrite(8, HIGH);
  delay(1000);
    digitalWrite(8, LOW);

   delay(100);
}

void loop()
{

  if (wire.available()>0)
  {
        Grsp = wire.readString();
     Serial.println(Grsp.length());
     Serial.println(Grsp);

     if(Grsp.length() > 100)
     {
       Serial.println("if crossed");

      digitalWrite(8, HIGH);
       delay(1000);
        digitalWrite(8, LOW);

      }

}

}

Do you have any common ground 'GND' between arduino and sim800l module. UART works when there is TX RX and GND terminals are connected between both modules. When you connect it with PC and open your terminal the both got supply from PC thus have common GND connection.

thank you so much Vaibhav you made my day,it was same as you said i used common GND on breadboard.


text:
Change data-type String
I'm currently working with an ESP8266 NodeMCU V3 and an IR transmitter breakout board. The module receives NEC IR commands trough a HTTP request and then sends them trough the IR transmitter. Getting the command from the HTTP request and sending static (pre-programmed) IR NEC commands works perfectly. The problem however is that the NEC IR command I receive trough HTTP is in a String variable/data type (after processing). irsend.sendNEC(); however requires uint64_t as the input type, according to the error message I get in the Arduino IDE.
I don't really know my way around C data types to be honest. Searches like "Arduino String to uint64_t" have came up empty or reversed. One post came close to what I'm trying to accomplish, but irsend.sendNEC(strtoul(irrequest)); didn't do the trick either.
Arduino code;

Check for // Send IR NEC command almost at the bottom
The second and third irsend.sendNEC(); are an example and not in the final code
HTTP request is formatted like http://192.168.1.xxx/rest/ir/nec/0xFB0042BD

Sketch.ino

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_PORT      = 80;
const int   CONFIG_TIMEOUT   = 5000;
const int   CONFIG_IRTPIN    = 2;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <IRrecv.h>
#include <IRutils.h>

// Create webserver object
WiFiServer server(CONFIG_PORT);

// Create IR Send object
IRsend irsend(CONFIG_IRTPIN);

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

  // Print WiFi connection information
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  Local IP: ");
  Serial.println(WiFi.localIP());

  // Start webserver
  Serial.println("Starting webserver...");
  server.begin();
  delay(1000);
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Host: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Port: ");
  Serial.println(CONFIG_PORT);

  // Start IR Send
  Serial.println("Starting IR Send...");
  irsend.begin();
  delay(1000);
  Serial.println("IR Send started!");

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient client = server.available();
  if (client) {

    // New client
    digitalWrite(LED_BUILTIN, 1);
    Serial.println("New client connected");

    // Wait nicely for the client to complete its full request
    unsigned long timeout = millis() + CONFIG_TIMEOUT;
    Serial.println("Waiting for client request to finish...");
    while (!client.available() && millis() < timeout) {
      delay(1);
    }

    // End client connection when timeout is reached to not hold up availability
    if (millis() < timeout) {
      Serial.println("Client request finished!");
    } else {
      Serial.println("Client request timeout!");
      client.flush();
      client.stop();
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();
      return;
    }

    // Catch client request
    String req = client.readStringUntil('\r');
    Serial.print("Request header: ");
    Serial.println(req);
    if (req.indexOf(F("/rest/ir/nec/")) != -1) {

      // Get IR Send NEC request
      String irrequest = req;
      irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
      irrequest.remove((irrequest.indexOf(" ")));
      Serial.print("IR Send NEC code: ");
      Serial.println(irrequest);

      // Send IR NEC command
      Serial.println("Sending IR NEC command");
      irsend.sendNEC(irrequest);    // <<< here lays the problem
      irsend.sendNEC(0xFB0042BD);   // This works
      irsend.sendNEC("0xFB0042BD"); // This doesn't

      // Send HTTP response
      Serial.println("Sending HTTP/1.1 200 OK");
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/plain");
      client.println("Connection: close");
      client.println();
      client.println("OK");

    } else {

      // Invalid request
      Serial.println("Invalid client request");
      Serial.println("Sending HTTP/1.1 404 response");
      client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

    }

    // Flush output buffer
    Serial.println("Flushing output buffer");
    client.flush();
    digitalWrite(LED_BUILTIN, 0);
    Serial.println();
    return;

  }

}

irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 10));  http://www.cplusplus.com/reference/cstdlib/strtoul/ https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/c_str/

irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 10)); did the trick with the help of Juraj. Much thanks! I only had the set 10 to 16 to get it to work.
Working code:

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_PORT      = 80;
const int   CONFIG_TIMEOUT   = 5000;
const int   CONFIG_IRTPIN    = 2;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <IRrecv.h>
#include <IRutils.h>

// Create webserver object
WiFiServer server(CONFIG_PORT);

// Create IR Send object
IRsend irsend(CONFIG_IRTPIN);

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

  // Print WiFi connection information
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  Local IP: ");
  Serial.println(WiFi.localIP());

  // Start webserver
  Serial.println("Starting webserver...");
  server.begin();
  delay(1000);
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Host: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Port: ");
  Serial.println(CONFIG_PORT);

  // Start IR Send
  Serial.println("Starting IR Send...");
  irsend.begin();
  delay(1000);
  Serial.println("IR Send started!");

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient client = server.available();
  if (client) {

    // New client
    digitalWrite(LED_BUILTIN, 1);
    Serial.println("New client connected");

    // Wait nicely for the client to complete its full request
    unsigned long timeout = millis() + CONFIG_TIMEOUT;
    Serial.println("Waiting for client request to finish...");
    while (!client.available() && millis() < timeout) {
      delay(1);
    }

    // End client connection when timeout is reached to not hold up availability
    if (millis() < timeout) {
      Serial.println("Client request finished!");
    } else {
      Serial.println("Client request timeout!");
      client.flush();
      client.stop();
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();
      return;
    }

    // Catch client request
    String req = client.readStringUntil('\r');
    Serial.print("Request header: ");
    Serial.println(req);
    if (req.indexOf(F("/rest/ir/nec/")) != -1) {

      // Get IR Send NEC request
      String irrequest = req;
      irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
      irrequest.remove((irrequest.indexOf(" ")));
      Serial.print("IR Send NEC code: ");
      Serial.println(irrequest);

      // Send IR NEC command
      Serial.println("Sending IR NEC command");
      irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 16));

      // Send HTTP response
      Serial.println("Sending HTTP/1.1 200 OK");
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/plain");
      client.println("Connection: close");
      client.println();
      client.println("OK");

    } else {

      // Invalid request
      Serial.println("Invalid client request");
      Serial.println("Sending HTTP/1.1 404 response");
      client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

    }

    // Flush output buffer
    Serial.println("Flushing output buffer");
    client.flush();
    digitalWrite(LED_BUILTIN, 0);
    Serial.println();
    return;

  }

}


text:
Should L, TX, RX led light on while connected with laptop
Dear Sir,
               I need to know that should led light named as L, TX, RX should be on when we connect it with laptop?
Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question.
                 Hoping for a favourable answer.
Your's faithful,
Nir Patel.

that would really depend on the device ... right now we have no idea what device you are talking about

On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).
If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.
If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and it will control the LEDs.
If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.


text:
Process Sensor Data from Arduino Yun with Python
I'm currently working on a small project with my Arduino Yún.
I want to process the sensor data in python and send them in a message queue. I need to use Python3.
I cannot find a way to get the sensor data in my Python code.
I already tried to start the python process in my sketch and use the println method of the process object but this doesn't work.
I also tried to use the BridgeClient class from the Arduino Github but it won't work either.
Summarized:
I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.
I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.
The section below contains my Arduino sketch, which does the measurements.
#include <SparkFunHTU21D.h>
#include <Wire.h>

HTU21D myHumidity;

int trigPin = 11;
int echoPin = 12;

void setup() {
  // put your setup code here, to run once:
  pinMode(A1, INPUT);
  Serial.begin(9600);

  myHumidity.begin();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

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

  //Perform 5 SoilMoisture-measurements and get mean
  float soil = meanSoilMoisture(A0, 5);
  float humd = myHumidity.readHumidity();
  float temp = myHumidity.readTemperature();

  float distance = getDistance();

  String dataString;
  dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
  Serial.println(dataString);

  delay(4000);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  long duration = pulseIn(echoPin, HIGH);

  // Convert the time into a distance
  return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
}

float meanSoilMoisture(int analogPin, int nMeasurements) {
  float sum = 0;
  for(int i = 0; i < nMeasurements; i ++) {
    sum = sum + readVH400(analogPin);
    delay(50);
  }

  return sum / nMeasurements;
}

//Perform Measurement
float readVH400(int analogPin) {
  int sensor1DN = analogRead(analogPin);
  float sensorVoltage = sensor1DN*(3.0 / 1023.0);
  float VWC;

  // Calculate VWC
  if(sensorVoltage <= 1.1) {
    VWC = 10*sensorVoltage-1;
  } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
    VWC = 25*sensorVoltage-17.5;
  } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
    VWC = 48.08*sensorVoltage-47.5;
  } else if(sensorVoltage > 1.82) {
    VWC = 26.32*sensorVoltage-7.89;
  }
  return(VWC);

}

I'd like to have a way to send dataString to the linux side of the Arduino Yún and process it with Python3.
As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the println method of the process.
{...}
Process proc;
void setup() {
    {...}
    proc.begin("python3 /mnt/sda1/test.py");
    p.runAsynchronously();
    {...}
}
{...}
    proc.println(dataString);
{...}

I've tried to read this dataString in Python3 in different ways, e.g. I've used the input method, because I read in a forum that I can handle such input like a keyboard input.
It didn't work and I didn't get an error, neither in Python nor in my sketch.
I've read different examples using the Bridge library. So I set up the sketch:
{...}
bridge.put("data", dataString);
{...}

I'd like to try out the BridgeClienton the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.
I would highly appreciate any help from you.

Are you having problems with the python code or Arduino code?

I've written arduino code that does the measurement and python code that processes the measurement and pushes the data into the message queue. I'm having problems with the connection between these two sides. I just need to send the measurment data to the python code somehow - with python3.

Please show us the code you are using. If the problem is with the Arduino sketch, it's "on topic" and we can help you. If the problem is with the python code, it would be better suited for Stack Overflow. Here is a link to a Stack Overflow question that has a simple sketch and python script to test if communication between the two is working: https://stackoverflow.com/questions/24682354/arduino-python3-script/30177116

It's an Arduino Yun, so I'm pretty sure this forum should be better for python and arduino sketch related questions. My code isn't relevant since I'm just reading sensor data, I don't have code for the communication between Yun Arduino and Yun Linux (python3)

It seems to me that you don't understand my question bc. you ignored the fact that I'm searching for a solution for an Arduino Yun. I have a Arduino Uno where everything works fine but I need another device where I listen for the serial data from the arduino. The Arduino Yun has a build in linux system, so I wouldn't need the additional device. I'm struggling to get the data to this linux system.

Please have a look at this question and it's answers: https://arduino.stackexchange.com/questions/18043/share-data-between-the-two-processors-of-the-arduino-yun. Have you tried the "Bridge library"?

Show us the code, or at least the parts relevant to the communication, and any errors etc associated. Edit your question and paste it in. Without that it's more or less impossible to help you.

When you say you tried using the bridge, did you try the tutorial on the Getting Started with Yun page? It is near the end and titled "Communicating with OpenWrt-Yun via Bridge". Once you get that working, maybe tweak it for your particular project? And definitely post the code. Just saying this didn't work, or that didn't do what I want is not helpful because we do not know what you did nor what you are expecting.

I didn't thought that it would be that hard to get sensor data from the arduino side to the linux side of the YUN since I thought this device was build for exactly this reason. I can't find one working example on the net (with python3), I don't want to migrate the BridgeLibrary from Python2 and it seems to me that there are no other options. Thank you to @VE7JRO for your "helpful" link - as quoted there: "Anyway, the real take away here is that the Yun is definitely not worth the hassle for me."

Right now, there are 2 votes to re-open this question, so I'm re-opening it. Comments are for clarifying the question and are not to be used to complain about Arduino products.

You are right, I'm sorry about that.

raphael, as per my comment earlier, we can not read your mind and sometimes you have to start at the basics to rule out possibilities. Did you try the tutorial at getting started with Yun???? If so, did that work? If not, what exactly did not work? When I exactly i mean what errors did you get? At what point did output stop? What happened jut before that and so on. Remember we can not see your environment, we can only rely on what you tell us and the problem might just be that you missed something.

also, i note that you have not actually shown us anything yet...  Please refer to
How to ask a good question
and
create a Minimal, Complete, Verifiable example. Especially the MCVE link (i.e. the second one)

You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.
Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.
From this post to the thread on the Arduino forums, Yun Serial connection between Arduino and Linux

Accepting HTTP connections, as shown in the Bridge tutorial, is
  but one facet of the Bridge library. (And probably the least useful
  and least efficient facet.) It is intended for accepting incoming
  connections from the greater network, not necessarily the local Linux
  processor.
The Bridge library is a collection of different classes that perform a
  variety of operations, all over the serial link between the two
  processors, and all can be used at the same time. The Bridge uses a
  network port paradigm, not HTTP. Using ports gives it a little more
  overhead, but it allows multiple simultaneous "connections" between
  the sketch and Linux sides.
I suggest you take a look at the Process tutorial. It does what
  you want, and 95% of the time it is the only part of the Bridge
  library that I use. The example defines Process objects that are local
  to a function, which run simple commands that do a little bit
  different f processing, return a result, and then exit.
My projects typically define a global Process object which starts a
  Python script, and keeps the connection open. Once open, the sketch
  can write to the Process object at any time, and the Python script
  reads that data from STDIN. Python can write to STDOUT at any time,
  and the sketch can read it from the Process object. The Process class
  derives from the Stream class, just like Serial, so your sketch can
  use any of the read/write methods you would use for a serial port. On
  the Linux side, you are just reading/writing as you would to the
  console. By default, Pythons runs in a buffered mode: I've found that
  you need to add the -u option to the command line that runs your
  Python script, or add it to the hashbang at the beginning of your
  script.
There are those who disable the Bridge library, and use the serial
  port manually on both sides. This can be done, but I've not had to
  resort to that yet. The Process class does everything that a direct
  serial connection can do, and more: you can have multiple simultaneous
  Process connections going, and you can still use all of the other
  Bridge library features. If you disable the Bridge library, you get
  just the one connection stream. It would be a bit more efficient, but
  unless you are dealing with high amounts of data, I'll bet you don't
  need to do that.
My typical project has the sketch running as a rather dumb I/O
  processor, passing barely digested input data down though one or more
  Process objects to a Python script. The Linux side does all of the
  heavy processing and network communications, and then sends output
  data back up the sketch which outputs it to the pins.


text:
ACS712 Module inaccurate reading in some devices
I'm currently trying to isolate what's the problem with a current sensor build I'm working on right now. I'm using a ACS712 that can handle 30A, I've used the code at
http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/
And so far for certain devices like pencil sharpeners, computers, chargers, and other household devices the amperage readout seems is "correct" there's some minor error due to the noise I assume.. There's like .10 amperage difference. But when I plug in a stereo amplifier the error sky rockets to 1 Amp to even 2 Amps and I'm not quite sure what's the problem, I've also tried multiple codes online and all of them reach the same conclusion.
Thanks,

how do you know that there is an error?

I use an amp meter to detect if the current matches, and the readout does not match therefore an error


text:
Problem with reading data from HMC5883L in GY-86
I am trying to read the data from GY-86 with my arduino UNO.
While reading MPU6050 and MS5611, it works quite well. But somehow I can't read anything from HMC5883L. Here is the code I used:
#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;

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

  // Initialize HMC5883L
  Serial.println("Initialize HMC5883L");
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

  // Set measurement range
  // +/- 0.88 Ga: HMC5883L_RANGE_0_88GA
  // +/- 1.30 Ga: HMC5883L_RANGE_1_3GA (default)
  // +/- 1.90 Ga: HMC5883L_RANGE_1_9GA
  // +/- 2.50 Ga: HMC5883L_RANGE_2_5GA
  // +/- 4.00 Ga: HMC5883L_RANGE_4GA
  // +/- 4.70 Ga: HMC5883L_RANGE_4_7GA
  // +/- 5.60 Ga: HMC5883L_RANGE_5_6GA
  // +/- 8.10 Ga: HMC5883L_RANGE_8_1GA
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  // Idle mode:              HMC5883L_IDLE
  // Single-Measurement:     HMC5883L_SINGLE
  // Continuous-Measurement: HMC5883L_CONTINOUS (default)
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  //  0.75Hz: HMC5883L_DATARATE_0_75HZ
  //  1.50Hz: HMC5883L_DATARATE_1_5HZ
  //  3.00Hz: HMC5883L_DATARATE_3HZ
  //  7.50Hz: HMC5883L_DATARATE_7_50HZ
  // 15.00Hz: HMC5883L_DATARATE_15HZ (default)
  // 30.00Hz: HMC5883L_DATARATE_30HZ
  // 75.00Hz: HMC5883L_DATARATE_75HZ
  compass.setDataRate(HMC5883L_DATARATE_15HZ);

  // Set number of samples averaged
  // 1 sample:  HMC5883L_SAMPLES_1 (default)
  // 2 samples: HMC5883L_SAMPLES_2
  // 4 samples: HMC5883L_SAMPLES_4
  // 8 samples: HMC5883L_SAMPLES_8
  compass.setSamples(HMC5883L_SAMPLES_1);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.print("Selected range: ");

  switch (compass.getRange())
  {
    case HMC5883L_RANGE_0_88GA: Serial.println("0.88 Ga"); break;
    case HMC5883L_RANGE_1_3GA:  Serial.println("1.3 Ga"); break;
    case HMC5883L_RANGE_1_9GA:  Serial.println("1.9 Ga"); break;
    case HMC5883L_RANGE_2_5GA:  Serial.println("2.5 Ga"); break;
    case HMC5883L_RANGE_4GA:    Serial.println("4 Ga"); break;
    case HMC5883L_RANGE_4_7GA:  Serial.println("4.7 Ga"); break;
    case HMC5883L_RANGE_5_6GA:  Serial.println("5.6 Ga"); break;
    case HMC5883L_RANGE_8_1GA:  Serial.println("8.1 Ga"); break;
    default: Serial.println("Bad range!");
  }

  Serial.print("Selected Measurement Mode: ");
  switch (compass.getMeasurementMode())
  {
    case HMC5883L_IDLE: Serial.println("Idle mode"); break;
    case HMC5883L_SINGLE:  Serial.println("Single-Measurement"); break;
    case HMC5883L_CONTINOUS:  Serial.println("Continuous-Measurement"); break;
    default: Serial.println("Bad mode!");
  }

  Serial.print("Selected Data Rate: ");
  switch (compass.getDataRate())
  {
    case HMC5883L_DATARATE_0_75_HZ: Serial.println("0.75 Hz"); break;
    case HMC5883L_DATARATE_1_5HZ:  Serial.println("1.5 Hz"); break;
    case HMC5883L_DATARATE_3HZ:  Serial.println("3 Hz"); break;
    case HMC5883L_DATARATE_7_5HZ: Serial.println("7.5 Hz"); break;
    case HMC5883L_DATARATE_15HZ:  Serial.println("15 Hz"); break;
    case HMC5883L_DATARATE_30HZ: Serial.println("30 Hz"); break;
    case HMC5883L_DATARATE_75HZ:  Serial.println("75 Hz"); break;
    default: Serial.println("Bad data rate!");
  }

  Serial.print("Selected number of samples: ");
  switch (compass.getSamples())
  {
    case HMC5883L_SAMPLES_1: Serial.println("1"); break;
    case HMC5883L_SAMPLES_2: Serial.println("2"); break;
    case HMC5883L_SAMPLES_4: Serial.println("4"); break;
    case HMC5883L_SAMPLES_8: Serial.println("8"); break;
    default: Serial.println("Bad number of samples!");
  }

}

void loop()
{
  Vector raw = compass.readRaw();
  Vector norm = compass.readNormalize();

  Serial.print(" Xraw = ");
  Serial.print(raw.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(raw.YAxis);
  Serial.print(" Zraw = ");
  Serial.print(raw.ZAxis);
  Serial.print(" Xnorm = ");
  Serial.print(norm.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(norm.YAxis);
  Serial.print(" ZNorm = ");
  Serial.print(norm.ZAxis);
  Serial.println();

  delay(100);
}

I download it from https://github.com/jarzebski/Arduino-HMC5883L.
The program always stuck at
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

Here is the begin function in HMC5883L.cpp
bool HMC5883L::begin()
{
    Wire.begin();

    if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
    || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
    || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
    {
    return false;
    }

    setRange(HMC5883L_RANGE_1_3GA);
    setMeasurementMode(HMC5883L_CONTINOUS);
    setDataRate(HMC5883L_DATARATE_15HZ);
    setSamples(HMC5883L_SAMPLES_1);

    mgPerDigit = 0.92f;

    return true;
}

So, it seems that the begin function always returns False. What should i do to solve this problem?
This is how I connect GY-86 to UNO:
VCC-IN  -> 5V
GND     -> GND
SDA     -> 4A
SLC     -> 5A

Did you run a i2c scanner? Is it found with i2c address 0x1E?
Looking at the schematic, the magnetometer HMC5883L is connected to XDA and XCL. That is not the normal I2C bus, but a second I2C bus from the MPU-6050.
The reason for that is that the 'dmp' firmware in the MPU-6050 can read the magnetometer and do calculations with it, in the MPU-6050.
If you want to communicate with the magnetormeter via the normal I2C bus, then you have to turn on the bypass-mode.
The libraries from Jeff Rowberg and Jarzębski are large. I suggest to enable the bypass-mode and run a i2c scanner.
Do you have a logic analyzer?
Perhaps you can use a simple multimeter. Keep the SDA low (shortcut it to GND) and try to measure if XDA is low as well in the bypass mode.
There is a chance that something is broken.

It might be a problem here.  A i2c scanner only found 0x68 and 0x77. Does it means that my GY-86 is broken?

By the way, I also try to use the I2Cbypass code in this website
link
`mpu.setI2CMasterModeEnabled(false);
mpu.setI2CBypassEnabled(true);
mpu.setSleepEnabled(false);`
But still, it stuck at begin() again.

You still have to call mpu.begin before enabling the bypass. I have added to my answer some background information and how to test the second I2C bus.

Thank to Jot, your answer actually helps me.
Now I am using this code and it is working very well.
#include <Wire.h>
#include <HMC5883L.h>
#include <MPU6050.h>

HMC5883L compass;
MPU6050 mpu;

int previousDegree;

void setup()
{
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
  Serial.begin(38400);

  // Initialize MPU6050
  mpu.initialize();

  // Enable bypass mode
  mpu.setI2CMasterModeEnabled(false);
  mpu.setI2CBypassEnabled(true);
  mpu.setSleepEnabled(false);

  // Initialize HMC5883L
  while (!compass.begin())
  {
    delay(500);
  }

  // Set measurement range
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  compass.setDataRate(HMC5883L_DATARATE_30HZ);

  // Set number of samples averaged
  compass.setSamples(HMC5883L_SAMPLES_8);

  // Set calibration offset. See HMC5883L_calibration.ino
  compass.setOffset(0, 0);
}

void loop()
{
  long x = micros();
  Vector norm = compass.readNormalize();

  // Calculate heading
  float heading = atan2(norm.YAxis, norm.XAxis);

  // Set declination angle on your location and fix heading
  // You can find your declination on: http://magnetic-declination.com/
  // (+) Positive or (-) for negative
  // For Bytom / Poland declination angle is 4'26E (positive)
  // Formula: (deg + (min / 60.0)) / (180 / M_PI);
  float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI);
  heading += declinationAngle;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0)
  {
    heading += 2 * PI;
  }

  if (heading > 2 * PI)
  {
    heading -= 2 * PI;
  }

  // Convert to degrees
  float headingDegrees = heading * 180/M_PI;

  // Fix HMC5883L issue with angles
  float fixedHeadingDegrees;

  if (headingDegrees >= 1 && headingDegrees < 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 0, 239, 0, 179);
  } else
  if (headingDegrees >= 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 240, 360, 180, 360);
  }

  // Smooth angles rotation for +/- 3deg
  int smoothHeadingDegrees = round(fixedHeadingDegrees);

  if (smoothHeadingDegrees < (previousDegree + 3) && smoothHeadingDegrees > (previousDegree - 3))
  {
    smoothHeadingDegrees = previousDegree;
  }

  previousDegree = smoothHeadingDegrees;

  // Output
  Serial.print(norm.XAxis);
  Serial.print(":");
  Serial.print(norm.YAxis);
  Serial.print(":");
  Serial.print(norm.ZAxis);
  Serial.print(":");
  Serial.print(headingDegrees);
  Serial.print(":");
  Serial.print(fixedHeadingDegrees);
  Serial.print(":");
  Serial.print(smoothHeadingDegrees);
  Serial.println();

  // One loop: ~5ms @ 115200 serial.
  // We need delay ~28ms for allow data rate 30Hz (~33ms)
  delay(30);
}

By the way, the code on https://github.com/jarzebski/Arduino-HMC5883L should add
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif

in the begin of setup.


text:
Arduino Uno COM issue + Braccio qu
hey guys so i get this error when plugging in my arduino and not sure why:

Blockquote
Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 930 bytes (2%) of program storage space. Maximum is 32256
  bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving
  2039 bytes for local variables. Maximum is 2048 bytes.
  avrdude: ser_open(): can't open device "\.\COM5": The system cannot find the file specified.
Problem uploading to board.  See
  http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

How can i solve it? It used to work and not sure what's happened... also does anyone know if the Braccio robotic arm can be connected to arduino via just the arduino/usb cable alone? Because when i connect the braccio shield v4 to both th arduino(and to laptop) and to the wall, it actually causes my laptop to switch off ??

it appears that you are asking three different questions .... please ask only one question per post

the error is indicating serial port COM5 on your computer is unavailable. (windows treats a serial port like a 'file' on the programming level, hence the confusing message). This could be a hardware issue or a driver issue. You'll have to troubleshoot that first.


text:
Serial input values only working for very short seconds
I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?
int light=9;

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

void loop() {
  Serial.println("How long do you want the light on for (in seconds)?");
  while(Serial.available()==0){}
  int on_time = (Serial.parseInt() * 1000);
  digitalWrite(light, HIGH);
  delay(on_time);
  digitalWrite(light, LOW);
  Serial.print("The light was just on for ");
  Serial.print(on_time/1000);
  Serial.print(" seconds. ");
}

please include all information .... your code prints to the serial console ... what do you see printed out?

What Arduino do you have? On an Uno, an int has values -32,768 to 32,767. An unsigned int is from 0 to 65,535 (ie. it's only 16 bits). Try using an unsigned long instead of int to see if that helps.

Ok, that makes a lot of sense. I'll try that. Thanks so much! And yeah i have an Uno btw

It completely fixed my program, thanks so much!

"the LED never turns off" is not exactly true. It will turn off, but after a very long delay.

If you add Serial.println(on_time); right after int on_time = (Serial.parseInt() * 1000); you will see the problem. Once you enter the number 33 for example, the integer value printed is -32536. The Allowed data type for delay() is unsigned long, so the negative number is causing a problem.
Using Serial.println() judiciously can be very helpful when you are trying to debug a sketch.

Hi! Thanks for taking the time to help! I've just done as you suggested an yeah i saw the negative number. 2 questions: 1) Why is this happening? Shouldn't it just be 33x1000? I'm a total noob so i don't understand what "unsigned long" is. 2) How can i go about fixing this/avoiding this problem in the future?

On an UNO, the largest "number" you can store in a integer is 32767. 33 seconds times 1000ms = 33000, which is over the 32767 maximum, so the integer becomes a negative "number". Anunsigned long variable can hold a "number" up to 4,294,967,295. 2) To avoid this type of problem, arm yourself with knowledge. I found the examples that came with the IDE were very helpful to determine what variable types to use, and how to use them. Another source of information about variable types, functions, etc. is the Language Reference found here: https://www.arduino.cc/reference/en/.

That all makes sense. Thanks again!

@ThisUsernameHasBeenTaken: Re “Why is this happening?”: Since you are using a signed number, the most significant bit is interpreted as a sign bit. This is how two's complement arithmetic works.


text:
NTP rollover-safe design with ESP8266 (Curiosity)
The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).
If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.
The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):

unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;

this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

This implementation is perfectly fine. The calculations are done with
unsigned numbers, so they are naturally rollover safe. The day NTP time
rolls over, secsSince1900 will become a very small number, and
subtracting SEVENZYYEARS from it will cause an extra roll over. Owing
to the rules of modular arithmetics, these two rollovers compensate and
you are guaranteed to get the correct result modulo
232 s.
In the end, you get a Unix time as an unsigned 32-bit integer. Unix time
is traditionally signed, which makes the 32-bit representation roll over
in January 2038. The authors of this library have instead chosen to
represent it as an unsigned number, which means it will roll over in
February 2106.

Huh. That's actually rather cool. I knew of a similar method for millis(), but didn't know this worked for NTP as well. Thanks!

@RDragonrydr: carry propagates from low to high in addition/subtraction.  The low bits of the result do not depend on any higher bit positions, so if you want a 32-bit result it's always safe to truncate your inputs instead of doing a 64-bit subtract and truncating the result.  Same for left shift, or the low N bits of an N x N multiply.  See also Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted?

I knew that, but I didn't know that the Arduino's method would manage to handle the rollover in NTP, not quite accidentally, but without needing to detect it per se. I figured that, since the time is an absolute delta past a certain start date, that any rollover would HAVE to give the wrong time once it occurred.


text:
Bit Number to Byte Value conversion (AVR Docs)
I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_use_bv.html
I has a macro called _BV that

convert a bit number (usually within a byte register) into a byte value

And the example tells this

_BV(3) => 1 << 3 => 0x08

I am kinda used to bits and bytes etc. But I don't understand what the 3 in this example is? It says it converts a bit number but 3 is not binary it is an integer. And the macro resolves it to 0x08 which is the value of 8 in decimal.
I am very confused. I hope someone can explain to me what is happening here!

when you see 0x08, do not think "decimal" ... think "hexadecimal" ..... hexadecimal numbers convert to binary easily ..... for example, 0x98 is same as 0b10011000

The bits within a byte are numbered 0 through 7 from right to left. The
rightmost (least significant) is bit 0, next is bit 1... and the
leftmost (most significant) is bit 7.
The expression _BV(3) builds a byte where bit 3 is set (is 1) and all
other bits are clear (are 0). In binary it looks like this:
position:   7  6  5  4  3  2  1  0
bit value:  0  0  0  0  1  0  0  0

The macro expands to 1<<3, which takes the integer 1 (0b00000001 in
binary) and shifts all its bits by three positions to the left. The
result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8
in decimal.

and bear in mind @xetra11 that it is only coincidence that in this case, the hexadecimal number and the decimal number are the same. Had bit 4 been set to 1 instead of bit 3, it would have been 0x10 in hexadecimal, and 16 in decimal! It may be useful to consider that decimal numbers are all "base 10" (hence the word DEC-imal). But binary numbers are base '2', and hexadecimal numbers are base 16. The base - 1` is the highest number that can be in a 'digit' before a carry must happen to represent the number. For hexidecimal, in order to have 16 digits, it goes from 0-9 followed by A-F.


text:
Arduino SD Card open file modes append / overwrite
Running Arduine IDE SD DataLogger Example, my data gets appended to a txt file.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

Is there an explicit option to open the file in overwrite / append modes?

thanks for the edit @michael

If you look in this library, you see:
File SDClass::open(const char *filepath, uint8_t mode) {

    ...

    if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) {

So you can use all these mode combinations (e.g. O_CREATE, O_APPEND, O_WRITE).

answered the question as asked. UPVOTED & ACCEPTED  :)

The Arduino SD library is an Arduino wrapper of old version of SdFat library (put into utility subfolder of the SD library). This SdFat library has constants like O_READ, O_WRITE, O_APPEND.
Arduino wrapper has constants
#define FILE_READ O_READ
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

You can use the SdFa library constants in the wrapper calls.
File dataFile = SD.open("datalog.txt", O_READ | O_WRITE | O_CREAT);

Warning: not all versions of SD library bundled in different board packages have O_APPEND in #define FILE_WRITE. Even in the Arduino SD library the O_APPEND was removed some time ago and then the change was reverted, because all dataloger examples used FILE_WRITE.

nice solution thanks!  UPVOTED

You only need to open the file with FILE_WRITE and use file.seek(EOF) to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.
File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");

perfect for day-to-day solutions, thanks!  UPVOTED


text:
LED dimmer not fading out
I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?
int blue_led=10;

void setup() {
  pinMode(blue_led,OUTPUT);
}

void loop() {

  int voltage=0;

  for(int i=0;i<=255;i+1){

    analogWrite(blue_led,voltage);
    voltage=voltage+1;
    delay(8);
  }
   int volts=255;

   for(int i=0;i<=255;i+1){

    analogWrite(blue_led,volts);
    volts=volts-1;
    delay(8);
   }

}

your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)

i could be used instead of voltage and volts, couldn't it? I mean, is max voltage 255?

Sure, 'i' could be used, because 255 is indeed the maximum allowed value for the  PWM pins. But again, the 'i' in the OP's code will never go past '0', until the for() loop is fixed.
Here's a handy article about it...
https://www.allaboutcircuits.com/projects/using-the-arduinos-analog-io/

Ah i understand. I just made the changes and it works perfectly! Thanks so much!

Thanks for the explanation, Randy. @ThisUsernameHasBeenTaken, if the answer solved your problem you can mark it as accepted (see help center)

Just done :) Thanks

Also note that using delay is generally a bad idea. (Your code freezes until the delay time passes, so your Arduino can't do anything else during that pause.) You should get used to writing code that records the current value of millis() and waits for it to increment to a desired end value. Do a Google search on "Arduino blink without delay" for an explanation of that.


text:
Arduino IDE upload error
I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

Sketch uses 7514 bytes (23%) of program storage space. Maximum is
  32256 bytes. Global variables use 415 bytes (20%) of dynamic memory,
  leaving 1633 bytes for local variables. Maximum is 2048 bytes.
avrdude: verification error, first mismatch at byte 0x0002
0x5d != 0x62 avrdude: verification error; content mismatch
avrdude: verification error; content mismatch

I'm using Arduino UNO R3
This is the code I'm trying to run
    #include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
}

Also, every other code(not using the IRremote library) uploads just fine without any errors.

Is it a genuine Arduino or a cheap Chinese knock-off?

There can be power/connection problem or somehow the bootloader has been damaged.
So

Check power
Check Connection

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.


text:
GPS Module don't provide full data
I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.
My pin configuration:
GPS ------- ESP32
VCC ------- 3v3
GND ------- GND
TX -------- RX2 (pin 16)
RX -------- TX2 (pin 17)
Baud Rate: 9600
My code:
#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}

OUTPUT

The output looks perfectly fine. You just don't have a GPS signal.

@Majenko is right put your GPS outside (in open sky) then you will the latitude and longitude with other parameters as well.

GPS seems to be working and informing you that you have no signal.  Usually happens inside buildings, when far from a window or when antenna isnt properly connected.
Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky.  Wait for a couple of minutes until you get a fix on 4 or 5 satellites.

have also found this happens when the power to the module is lower than needed, for example 5v being shared with other modules such as a 1602 display


text:
Check if Arduino Uno connected with PC
I'm using Arduino Uno controller
How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.
I've tried Serial.available(), but I'm not sure, if I can do it this way:
if (Serial.available())
{
   val = true;
}
else
{
   val = false;
}

I want use this condition to avoid setup() commands by some unexpected reason in case if controller powered only with adapter

I don't know the answer of the problem, but your code can be rewritten to a shorter and equally functional val = Serial.available();

you can do another thing like you continuously send some random data over serial. when arduino is connected to the PC it will receive same data from arduino, indicating arduino is connected to your PC. For reception point of view you can write some python script as well.

You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.
If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC
If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)

It's an ATMega16u2, not a ATMega32u4, that's on the Arduino UNO. Other than that, options 3 would be possible.

@Gerben I was totally sure it was the same as on the Leonardo.. Goot catch, I fixed it in the answer. Thank you

And older revisions were using ATMega8u2. Knockoffs started 8u2 or FTDI, ended with cheaper CH340G