text:
MQTT with OLED realy :- display not coming properly
I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. Also like to display status on OLED
here is my code
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "ssid"
#define wifi_password "wifipassword"
#define mqtt_server "192.168.1.1"
#define mqtt_user "username"
#define mqtt_password "password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String display_line2;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;

WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>

Security Door

<button class="button">Open</button>

<button class="button">Close</button>

)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  //dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();

 if(strcmp(topic, "livingroom/securitydoor") == 0){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function --------------------------------------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

//----------------------- LED display--------------------------------------

void doorOpening() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Opening");
  display.display();
}

void doorClosing() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Closing");
  display.display();
}

actually doorOpening() function is coming and doorClosing() function is not coming on OLED
again i am not very good in programming and arduino/esp8266

I would suggest leaving the MQTT broker and perhaps the OLED out of the software until you get the primary feature of opening and closing the garage door working as expected.  Also, there is no reason to assume certain libraries are compatible with one another.  Even if they work on one Arduino platform they may not work with one another on a different platform.

but here if i call the function in voild loop, oled is displaying what i expected also MQTT is always working for me.
i thought of doing the mqtt and oled before actual electrical circuit

Could be  a number if issues you might have with your code or the MQTT source.  For instance, are you actually sending "OFF" instead of "off" or even "Off"?  That is why I said do the simple things first.  Make sure they work.  Then add to what you know works.  When something breaks and you can not figure it out.  That would be the time to ask a question.

BTW, consider using Tasmota and a supported Sonoff ESP based product instead of writing your own code.  With Tasmota you can assume the MQTT feature works, the web server works, the WIFI works and the control over the supported Sonoff relays work.

i found the issue, actually relay pin was defined on D1 & D2 by mistake i connected oled to that pins


text:
Can Chirp Waves be sent using JSN-SR04T?
So i have project for underwater rangefinding using JSN-SR04T. I've read on the datasheet that the module sends square waves. Is it possible to program it so that it sends Chirp waves instead ? (Help with the coding is very appreciated)
Thanks in advance

Does the data sheet say the module can send chirp waves?

no, it says it sends square waves

Well surely that was your answer?

This question is not about Arduino, this question can be better solved by contacting the supplier, this question shows no/little effort of the asker and is too broad (also asks help for "coding"). Please read https://arduino.meta.stackexchange.com/questions/2523/how-to-ask-a-good-question-for-arduino-stack-exchange I'm voting to close, but please feel free to adjust your question accordingly.

As I googled the sensor, I found various sites stating, that a JSN-SR04T behaves exactly like the HC-SR04. The difference is mainly the water prooving.
So the answer is: No, you can't do this. The square wave, which drives the ultrasonic transducers, is generated by a hardware circuit and is not meant to be changed. To output a chirp wave you would need to rebuild the signal generation and measurement hardware (leaving only the transducers unchanged). At that point you may just buy the pure ultrasonic transducers and build the rest yourself.

Ok thank for the help

Ok, i also want to translate the distance data into a 3D image, how do you propose i do that ?

That depends on how you want to represent the image and how exactly you are measuring. Are you moving the sensor over a surface, or are you turning the sensor ro look in different directions?

source: Stack Exchange

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

sort: votes


text:
Ultrasonic Sensor - JSN-SR04T 2.0
I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?

#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}
void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);

  delayMicroseconds(5);
 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance:
  distance = duration*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(100);
}

What is the approx depth of the water? That sensor seems to be good to about 20 ft. Also since you didnt post your code, or anything about how your using the sensor, its hard for anyone to give you an answer.

Sorry. Here is the code.

@ChadG the body of water im testing has a depth of 50 cm

According to the data sheet the minimum target distance is 20cm in the open air at a 343 m/s
The speed of sound in water is 1481 m/s so the minimum distance would be 20cm x 1481 / 343 = 86cm.

You cannot measure distances under 83cm in water.

Thanks. I'll try the sensor out in a 4 foot deep pool.

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


text:
What is the difference between a Hall effect sensor and an inductive one?
From what I have read, when placed within a magnetic field, a current will flow in both sensors.
My goal is to use this kind of sensors to guide a robot thanks to an existing automower loop wire, such as suggested in DIY Perimeter Wire Generator and Sensor.
I am thus wondering what is the difference between a Hall effect sensor and an inductive one such as the one described in the link above?

First they physically work differently. In the Hall effect sensor the electrons flowing through a plate will be deflected. Thus there will be a voltage perpendicular to the current, which can be measured. The voltage will be proportional to the magnetic field strengh. So you can sense a magnet, that is near the sensor, even if it doesn't move.
For the inductive sensor you have a guiding wire, that has an AC current flowing through it. This also means, that a magnetic field ist constantly building up and collapsing again around the wire. This change of magnetic field will induce an induction voltage in a nearby wire loop (the actual sensor). The frequency of that voltage is the same as of the guidance wire and the strength depends on the distance between the wires. So you are not measuring the magnetic field strength directly, but you measure how much it is changing (mathematically you differentiate).
Two different measurement methods which can be used to do the same thing. To guide a robot over a predefined course I would use the induction method (as long as the situation allows laying out wires), since it can be made less susceptible to noise. For that you can filter out all frequencies except of the used guiding frequency with a LC circuit. Or even better (though maybe not important) a lock-in amplifier. The hall sensor is an analog device, which can be very noisy.

Thus, regarding the robot guidance over a guiding wire, both sensors can do the job but measurements from the inductive one are less noisy?

Yes and no. I cannot say, which one is better as, as long as you are not using additional hardware. Both of them can be distorted by noise. But when you filter out all but the used induction frequency, the noise to signal ratio gets way better. For both methods you would have to test the needed current/guiding wire layout, since the magnetic field strength or it's change must be strong enough to measure it with the given sensor. I haven't build such thing myself, so I only can talk about the theory here


text:
WiFi connection in loop function
What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:
setup(){
    wifi.mode(WIFI_AP_STA);
    setup softAP
    server.on("/",handleroot)
    server.begin()
}
loop(){
    server.handleClient()
    if(credential_submited){
        Wifi.begin(credentials);
        flag_connection_started =true;
        credential_submited = false;
        flag_for_internet_server=true;
    }
    if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
        server.on("/",handleroot)
        server.begin()
        flag_for_internet_server=false;
    }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

Is the esp in access point or in station mode? Probably it's possible, but I don't really understand the scenario. You could make it clearer by at least providing some pseudo code

Don't see problems there, since this is somewhat standard. Have you tried anything?

Take a look at https://github.com/tzapu/WiFiManager it does exactly what you want.

@Dougie I am trying to create it on my own to learn mostly.

WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.
You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().
BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.

Could you elaborate on the separate sketch part. You mean that I can upload two sketches on the eps and run one at the time and when the one is finished run the second program?

no. you run the configuration sketch and the esp8266 remembers the ssid and password. any other sketch uploaded after that will use this settings. the esp8266 will connect automatically even if you upload Blink

This is not a big deal...
You can do it vary easily, the most simple way is that you can use EEPROM to achieve this..
Simply pass the SSID and PASSWORD of new network to ESP8266 and save it in EEPROM and also create a new variable in eeprom that store the status that new network credentials is entered or not and check it in loop and then fetch new network credentials from the EEPROM and try to connect to it...
You can also check and connect to your desired network from the loop...
Or alternatively you can use the library that can help you in doing that [WiFiManager]: https://github.com/tzapu/WiFiManager

ESP8266 doesn't have an EEPROM but stores the SSID and password in flash automatically if you don't disable this feature. that is what WiFiManager utilizes


text:
Syntax for stopping loop until the condition has made false
I am taking reading from temperature sensor and from that data. I have to control 3 LEDs. Lets consider LED1, LED2, LED3.
If temperature range between 0-20
   I have to HIGH LED2.
   else if temperature range between 20-30
I have to HIGH LED1; HIGH LED3; LOW LED1;

my sketch is something like this:-
while(1)
{
if(temp>=0&&temp<=20)
{
digitalWrite(2,HIGH);
}
else if (temp>=20&&temp<=30)
{
digitalWrite(1,HIGH);
digitalWrite(3,HIGH);
digitalWrite(1,LOW);
}
}

The problem which I am facing is LED1 is continuously ON (which should be OFF), when temperature is between 20-30 because of continuously running loop so, how can I stop loop, once the statement under second condition has executed till the second condition has made false.

Don't understand your "I have to HIGH LED1; HIGH LED3; LOW LED1;" ? What do you want for LED1 ?

I want to first ON LED1 then ON LED2 then OFF LED1

when the condition2 is satisfied  and stop the loop till the condition 2 is made false

If the temperature is exactly 20, which LEDs should be on/off? Shouldn't LED2 be in this statement somewhere "I have to HIGH LED1; HIGH LED3; LOW LED1;".

yeah sorry brother  have to mention LED3 at the place of 2 ... as according to you

let me explain again if the temperature is between 20-30 condition2 will be executed as LED1 HIGH; LED3 HIGH; LED1 LOW . after execution i have to stop loop till the condition 2 is made false i.e temperature exceeds 30 or decrease below 20. while stoping the loop we also have to continuously taking reading from temperature sensor –

if the LED is supposed to be off, then why do you not turn it off?

Your code doesn't make sense. You have a while (1) statement, which will run forever. Inside the body of that statement, you never change the value of temp.
An Arduino sketch's loop() function runs continuously. You should not have a while (1) loop inside your loop function. You should have a loop function something like this:
void loop() {
  temp = //read a temp value somehow
  if(temp>=0&&temp<=20)
  {
    digitalWrite(2,HIGH);
  }
  else if (temp>=20&&temp<=30)
  {
    digitalWrite(1,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(1,LOW);
  }
}

With that loop function you would fetch a new value of temp on each pass through the loop, then decide what LEDs to light.

I have edited the code as u said     but  I am facing the problem i have to stop LED1 till the condition 2 is made false ...but it is continuously ON

I have to stop loop till the  condition 2 has made false along with  continuously taking reading of temperature

This is much better than the original question's sketch, but still very questionable: 2 will never be LOW, once it was set  HIGH; 3 will never become LOW, once it was set HIGH; 1 is considerably dimmed, if temp is between 20 and 30. (dimming depends on the time it takes to read temp)

@DataFiddler The OPs logic is incomplete, and I didn't attempt to address those issues. I was just trying to explain how to write code that gets called continuously.

"I have to stop loop..." No. Full stop. You should not write a sketch that freezes the loop until some condition occurs. That is a very bad idea. You need to come up with a different approach.

You don't want to stop the loop! You want it to run fast and often.
Eventually you want it to not change the current state of a LED, but in your case, I rather do not see enough defined states of LEDs.

I want to first ON LED1 then ON LED2 then OFF LED1"

if then means an amount of time, remember that loop runs fast and does not take time by itself. You will have to notice the starting point in time and compare that with the current time and your desired intervals. (And you do not mention what should happen to LED2 after the second then )
const unsigned int LED1_DURATION=500;
const unsigned int LED3_DURATION=1000;
bool c2 = false;  // true while condition2 is met
unsigned long start2;  // time when condition2 starts
void loop() {
  int temp = analogRead(A0); //read a temp value somehow
  if(temp<=20)
  {
    digitlaWrite(1, LOW);
    digitalWrite(2,HIGH);
    digitlaWrite(3, LOW);
    c2 = false;
  }
  else if (temp >20 && temp <= 30)
  {
     digitalWrite(2, LOW);

     if (c2 == false) { c2 = true; start2=millis(); } // detect start time

     if ((millis() - start2 < LED1_DURATION) ||
         (millis() - start2 > LED3_DURATION)   )
          digitalWrite(1,HIGH);
     else digitalWrite(1, LOW);

     if ((millis() - start2 > LED1_DURATION) &&
         (millis() - start2 < LED3_DURATION)    )
          digitalWrite(3,HIGH);
     else digitalWrite(3,LOW);
  }
  else
  {
    digitlaWrite(1, LOW);
    digitalWrite(2, LOW);
    digitlaWrite(3, LOW);
    c2 = false;
  }
}

This code contains a couple of guesses about states you did not mention, and a slightly different behavior (sorry), but I hope you get an idea...

LED2 has to be off if the condition1 is not correct...

let me explain again if the temperature is between 20-30 condition2 will  be executed as LED1 HIGH; LED3 HIGH; LED1 LOW . after execution i have to stop loop till the condition 2 is made false i.e temperature exceeds 30 or decrease below 20. while stoping the loop we also have to continuously  taking reading from temperature sensor

sorry i have a mistake at the place of LED2 it should be LED3

"while stoping the loop we also have to continuously taking reading from temperature sensor" So don't call it stoping You're simply in the part 'Condition2' but the time has exceeded both then times and your LEDs have a desired state.

i dont get what you said

suppose  then be delay of 1 sec

see my added sample code with 2 * 500 msec

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\ashwa\AppData\Local\Temp\cc3u0raS.ltrans0.ltrans.o: In function `main':
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino/main.cpp:43: undefined reference to `setup'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

its showing error

Don't try to copy/paste the code DataFiddler posted and complain when it gives compile errors It's intended to be a guide, not the exact code for your problem. Study the approach they're recommending and then apply that approach to your problem. The idea is that you don't "stop the loop", you use a combination of flags to keep track of state, and timers to track when events occur. You then write code that checks the current value of millis() on each pass through the loop, waiting for the desired amount of time to pass.

i am not getting code of datafiddler

is it possible to send compiler back ..back in the sense sending compiler 2-3 statement back

In the answer's code the function setup() is missing, where pinMode for output pins has to be set. You should be able to add this yourself. 2. You should know and understand the basic BlinkWithoutDelay principle, and be able to apply that principle to anything requiring an amount of time without "stopping" loop()

I do not understand " sending compiler 2-3 statement back "


text:
nodemcu GPIO6 clock
is there a way that i can declare gpio6 (CLK) as an input without getting a wdt reset?  I'm somewhat new to circuitry, but my boss wants to use it(GPIO6) to talk with external devices.  I have more pictures of the schematics if you think that it would help.

No. There is no way you can use it (or not without a lot of messing around...).
According to the ESP8266 GPIO Reference Guide:

GPIO6 to GPIO11 are usually connected to the flash chip in ESP8266 boards. So, these pins are not recommended to use.

If you mess with those pins you won't be able to access the flash chip - and that means that you can't run code. And of course that means that the watchdog then times out.
I say that you can't "without a lot of messing around", because theoretically it could be possible if you had a function resident in RAM which reconfigured the pins, then did whatever was needed with them (taking into account the fact that there's a flash chip connected there...), then afterwards reconfigure the pins back to working in XIP SPI Flash mode.  But that's not something I would like to even contemplate doing.

No you can't.
Refer to this: https://tttapa.github.io/ESP8266/Chap04%20-%20Microcontroller.html
However as that article states there is a dedicated SPI set of pins on the esp8266 so you should be able to use that?
From your circuit diagram I see this might not be an option for you as you seem to have most of the pins allocated to a different function.
Your best and most robust solution would probably be to have a separate microcontroller chip handling your I2C and SPI requirements, using the Esp8266 UART functionally to provide your wireless capabilities.
As a side note why do you have so many clock lines?

I think it has to do with the way the software was written previously.  The controller is supposed to run lights at 'belly', right, top-right, top-left, and left sides of the cabinet.  The lights they were using were rgb, but not individually addressable.  Now I have ws2812's and some other kind of ind. addressable lights and am not sure the clocks are necessary.  but i'm still a new guy to this.


text:
Reading Data from Google Sheets using Nodemcu
I want to read and writ data on Google sheets using ESP8266 WIfi Nodemcu and I'm able to do it but the time interval between two writing row is 3 seconds which is too much. I can read data but I am able to read only the first row not any other rows i am not able to read even changing the URL parameters.
Here is My Code -

#include "ESP8266WiFi.h"
#include "HTTPSRedirect.h"
#include "DebugMacros.h"

// Fill ssid and password with your network credentials

const char* ssid = "Leobotics";

const char* password = "leobotics123";

int sheetHumid = 1;

int sheetTemp  = 2;

int sheetaqu   = 3;

String readaqu = "";

const char* host = "script.google.com";

// Replace with your own script id to make server side changes

const char *GScriptId = "AKfycbyu_JnX7F29Ea5cZUy7HdsFbv9W5UmedmNbhTwt5tznwRUiQhYS";

const int httpsPort = 443;

// echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout

const char* fingerprint = "ED:83:75:6B:83:FE:01:DE:BA:72:84:05:71:FA:CE:54:FB:6E:23:CA";

//const uint8_t fingerprint[20] = {};

// Write to Google Spreadsheet

String url = String("/macros/s/") + GScriptId + "/exec?value=Hello";

// Fetch Google Calendar events for 1 week ahead

String url2 = String("/macros/s/") + GScriptId + "/exec?cal";

// Read from Google Spreadsheet

String url3 = String("/macros/s/") + GScriptId + "/exec?read";

String payload_base =  "{\"command\": \"appendRow\", \
                    \"sheet_name\": \"Sheet1\", \
                    \"values\": ";
String payload = "";

HTTPSRedirect* client = nullptr;

// used to store the values of free stack and heap
// before the HTTPSRedirect object is instantiated
// so that they can be written to Google sheets
// upon instantiation

unsigned int free_heap_before = 10;

unsigned int free_stack_before = 20;

void setup() {

  Serial.begin(115200);

  Serial.print("Connecting to wifi: ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");

//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());

  // Use HTTPSRedirect class to create a new TLS connection

  client = new HTTPSRedirect(httpsPort);

  client->setInsecure();

  client->setPrintResponseBody(true);

  client->setContentTypeHeader("application/json");

  Serial.print("Connecting to ");

  Serial.println(host);

  // Try to connect for a maximum of 5 times
  bool flag = false;

  for (int i=0; iconnect(host, httpsPort);

    if (retval == 1) {

       flag = true;

       break;
    }

    else

      Serial.println("Connection failed. Retrying...");
  }

  if (!flag){

    Serial.print("Could not connect to server: ");

    Serial.println(host);

    Serial.println("Exiting...");

    return;
  }

}

void loop() {

  datasend();

  static int error_count = 0;

  static int connect_count = 0;

  const unsigned int MAX_CONNECT = 20;

  static bool flag = false;

  if (!flag){

    client = new HTTPSRedirect(httpsPort);

    client->setInsecure();

    flag = true;

    client->setPrintResponseBody(true);

    client->setContentTypeHeader("application/json");

  }

  if (client != nullptr){

    if (!client->connected()){

      client->connect(host, httpsPort);

      payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

      client->POST(url2, host, payload, false);

    }
  }

  else{

    DPRINTLN("Error creating client object!");

    error_count = 5;

  }

  if (connect_count > MAX_CONNECT){

    connect_count = 0;

    flag = false;

    delete client;

    return;

  }

  Serial.println("GET Data from cell 'A1':");

  if (client->GET(url3, host)){

    ++connect_count;

    payload = payload_base + "\"" + readaqu + "," + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

    Serial.println("RECIEVED DATA IS GIVEN BELOW   ");

    Serial.println("                              ");

    Serial.println("1");

    Serial.println(readaqu);

    Serial.println("2");

    Serial.println(sheetaqu);

    Serial.println("3");

    Serial.println(sheetTemp);

    Serial.println("4");

    Serial.println(sheetHumid);

    Serial.println("                              ");
    Serial.println("RECEIVE DATA PRINT IS OVER  ");

    sheetaqu ++;

    sheetTemp ++;

    sheetHumid ++;

  }
  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  Serial.println("POST append memory data to spreadsheet:");

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  if(client->POST(url2, host, payload)){

    ;
  }

  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  if (error_count > 3){

    Serial.println("Halting processor...");

    delete client;

    client = nullptr;

  }

  delay(4000);

}

void datasend()

{
   // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  // Note: setup() must finish within approx. 1s, or the the watchdog timer
  // will reset the chip. Hence don't put too many requests in setup()
  // ref: https://github.com/esp8266/Arduino/issues/34

  Serial.println("\nGET: Write into cell 'A1'");

  Serial.println("=========================");

  // fetch spreadsheet data

  client->GET(url, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nGET: Fetch Google Calendar Data:");

  Serial.println("================================");

  // fetch spreadsheet data

  client->GET(url2, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nSeries of GET and POST requests");

  Serial.println("===============================");

  // delete HTTPSRedirect object

  delete client;

  client = nullptr;
}

Why the 4s delay at the end of loop?

Actually that code is copied from a website, I don't know the specific function of that delay of 4 second

I think you'll need to modify your Google Script for that Sheet so that whatever function you are invoking to GET row data takes in an additional parameter for the row value.
Then just add the Javascript logic within that function for retrieving the data at that passed-in row index to be returned.
Does that make sense?


text:
Attiny85 Watchdog fires only once
I build something like a flashlamp with different modi. From the hardware site it's quite simmilar to the Nanjg105c.
There is a Attiny85 which generates a PWM signal to an AMC7135.
I have one push button, if I click it the Attiny go to sleep, if I hold the button the Attiny changes his mode.

For checking the battery voltage I use the watchdog timer to make the ADC conversion every 8sec.
    #include "OneButton.h"
#include <avr/sleep.h>               // Sleep Modes
#include <avr/power.h>              // Power management
#include <avr/wdt.h>              // Watchdog Timer
#include <util/delay.h>

#define mid 4000                // BAttery Level Mid
#define low 3200                // Battery Level low, flash and start dimming the Led
#define crit 2600               // Battery Level critical, shut down

const byte LEDr = 1;              // pin 1
const byte LEDw = 4;              // pin 4
const byte ModeNr = 3;
volatile bool WDR_flag = false;
bool PWR_flag = false;

OneButton button1(2, true);
int count = 1;
int flag = 0;
long Vcc;
int PWMr = 255;
int PWMw_l = 50;
int PWMw_h = 255;

ISR(PCINT0_vect)
{
    // do something interesting here
}

ISR(WDT_vect){
  WDR_flag=true;
 }

void setup()
{
    pinMode(3, OUTPUT);
    pinMode(LEDr, OUTPUT);            // turn the LED on (HIGH is the voltage level)
    pinMode(LEDw, OUTPUT);
    digitalWrite(LEDr, HIGH);           // turn the LED on (HIGH is the voltage level)
    digitalWrite(LEDw, HIGH);
    delay(1000);
    button1.attachClick(sleep);
    button1.attachLongPressStart(changeMode);
    WDT_on();
}

void loop()
{
  uint8_t i = 0;
    button1.tick();               // keep watching the push buttons:
  if(WDR_flag == true){           // do every 8s
    WDR_flag = false;           //reset WDT Flag
    digitalWrite(3, HIGH);      //debug with third LED
    delay(250);
    digitalWrite(3, LOW);
    WDT_off();
    //ADC_on();
    /*Vcc = readVcc();            //read Battery voltage
    if(Vcc < low && count == 3){
      if(PWMw_h <= PWMw_l){       //change Mode to low when PWM output is smaler then low PWM
        count = 2;
      }else
    {
    i = 0;
        while (i++<3 && PWR_flag == false) {         //flash 3 times the red LED befor dimm the white LED
          analogWrite(LEDr, PWMr);
          _delay_ms(500);
          digitalWrite(LEDr, LOW);
          _delay_ms(250);
      PWR_flag = true;
        }
      PWMw_h = PWMw_h / 2;        //halve the PWM output of the white LED
      }
      if(Vcc <= crit){          //go to sleep when Battery is empty
        sleep();
      }
    }
    if(Vcc < low && count == 1){
      i = 0;
      while (i++<3) {
        digitalWrite(LEDr, LOW);
        _delay_ms(250);
        analogWrite(LEDr, PWMr);
        _delay_ms(500);
        }
      PWMr = PWMr / 2;
      if(Vcc <= crit){
        sleep();
      }
    }*/
    //ADC_off();                //save power
    WDT_on;                 //start watchdog again

  }
  switch (count) {
    case 1:                 //Mode red LED
    analogWrite(LEDr, PWMr);
    digitalWrite(LEDw, LOW);
    break;
  case 2:                   //low Mode white LED
    digitalWrite(LEDr, LOW);
    analogWrite(LEDw, PWMw_l);
    break;
  case 3:                   //high Mode white LED
    digitalWrite(LEDr, LOW);
    analogWrite(LEDw, PWMw_h);
    break;
  }
}

void sleep()                  // This function will be called when the button1 was pressed 1 time
{
    digitalWrite(LEDr, LOW);
    digitalWrite(LEDw, LOW);
    //prepare sleep
    WDT_off();
    GIFR |= bit(PCIF);              // clear any outstanding interrupts
    GIMSK |= _BV(PCIE);             // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT2);             // Use PB2 as interrupt pin
    ADC_off();
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

    sleep_enable();               // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                    // Enable interrupts
    sleep_cpu();                // sleep

    cli();                    // Disable interrupts
    PCMSK &= ~_BV(PCINT2);            // Turn off PB2 as interrupt pin
    sleep_disable();              // Clear SE bit
    WDT_on();

    flag = 1;                 //set flag, uc was in sleepmode before
}

void changeMode()               // This function will be called once, during pressed for a long time.
{
    if (flag == 1) {
        flag = 0;
    }
    else {
        if (count < ModeNr) {
            count++;
        }
        else {
            count = 1;
        }
    }
}

void WDT_on() {
  // Setup watchdog timer to only interrupt, not reset
  cli();                    // Disable interrupts
  wdt_reset();                // Reset the WDT
  WDTCR |= (1 << WDCE) | (1 << WDE);       // Start timed sequence
  WDTCR = (1 << WDIE) | (1 << WDP3) | (1<<WDP0);      // Watchdog cycle = 8 s
  //WDTCR = (1 << WDIE);             // Watchdog Interrupt enable
  sei();                    // Enable interrupts
}

void WDT_off(){
  cli();                    // Disable interrupts
  wdt_reset();                // Reset the WDT
  MCUSR &= ~(1<<WDRF);            // Clear Watchdog reset flag
  WDTCR |= (1<<WDCE) | (1<<WDE);        // Start timed sequence
  WDTCR = 0x00;               // Disable WDT
  sei();                    // Enable interrupts
}

void ADC_on() {
  ADCSRA = (1 << ADEN );            // ADC power on
}

void ADC_off() {
  ADCSRA &= ~(1<<7);              //ADC off
}

long readVcc() {
  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference

  ADMUX = _BV(MUX3) | _BV(MUX2);
  delay(2);                  // Wait for Vref to settle
  ADCSRA |= _BV(ADSC);              // Start conversion
  while (bit_is_set(ADCSRA,ADSC));        // measuring

  uint8_t low_adc  = ADCL;              // must read ADCL first - it then locks ADCH
  uint8_t high_adc = ADCH;              // unlocks both

  long result = (high_adc<<8) | low_adc;

  result = 1126400L / result;           // Calculate Vcc (in mV); 1126400 = 1.1*1024*1000
  int x = 0;
  /*while (x++<2) {         //debug with third LED
          digitalWrite(3, HIGH);
          _delay_ms(500);
          digitalWrite(3, LOW);
          _delay_ms(250);
        } */
  return result;                // Vcc in millivolts
}

my problem is that the watchdog fires only once. after putting the attiny to sleep the watchdog fires also only once.
I think the problem is in the WDT_off() function...

The line below lacks parens () to make it a function call; as it stands, it's not actually calling WDT_on.
WDT_on;                 //start watchdog again

should be:
WDT_on();                 //start watchdog again


text:
NodeMCU max draw
1) what is the max draw I can draw from NodeMCU V3 logic and 5v pins?
2) Also, I heard i draw with it more than 500mA, the PC USB port stops working. Is that information actual? Because USB 3 port has 900mA and USB 2 had 500mA max

it is unclear what you are asking ... is what actual?

for ESP8266 (which your NodeMCU is based upon) , the maximum current is about 20mA sinking and 12mA sourcing per [single] pin. so the maximum current of all GPIOs together is a lot lower than the 500mA USB limits.
you have to use external drivers (transistors, MOSFETs) for that purpose.
Sink current: the current which is provided when you pull the pin LOW. e.g. when you provide GND for the cathode of an LED. (the Anode is connected to VCC).
Source current: the current which is provided when you pull the pin HIGH. e.g. when you provide VCC for the anode of an LED. (the cathode is connected to GND).
the difference is for different internal resistance for identical N-MOS/P-MOS, due to their structure. that's why many devices like 7segment drivers, or motor drivers supply GND for the Load (common anode drivers) instead of VCC.

I would guess the question is not about the esp8266 io pins, but about the 3.3 V pin and the NodeMcu 3 on-board regulator

@Juraj it is said "logic" and 5v pins. It seems he means both of them

In that case, the Vin pin (which provides the 5 V from the USB cable) will be limited by the power source or cable and the 3.3 V rail provided by the NodeMCU i wouldn't draw more than about 300 mA from it. I don't know the rating of the actual component but looking at the package and amount of board area for heat dissipation i think that'd be a safe value for most ambient conditions.


text:
Arduino stops working when servo makes a few rotations
The sketch rotates servo back and forth with buttons.
When I rotate servo MG 995/996R 2-4 times Arduino stops working. Its voltage step-down transformer switches from ~9V to ~3.7V which is not enough for Arduino. To make it work again, I must turn off-on the device.
There is no such a glitch with smaller servos such as SG90.

Show us your sketch. Throwing an exception in the code has very similar symptoms. I also don't like that your servo ground is connected to the Arduino. It's much safer for it to be completely disconnected and using an optoisolator to send the PWM to it safely. Are you certain that your 12V power supply keeps at 12V when the problem happens?

" a few rotations" sounds strange, as such a servo can't rotate much more than 180°
And I do not see nor understand your term "3.7 V". Please clarify.

@FilipFranik There is no any exception. As I said, everything perfectly works with smaller servo. Therefore the problem not in the sketch.

@DataFiddler I haven't said any about the angle. The bottom transformer set to 9V. After rotations it becomes set to ~3.7V which is not enough to power-up the arduino via VIN pin. And btw, your're wrong about angles. There are servors with greater that 180 rotation.

So the problem is the transformer, because it outputs a too low voltage

@chrisl , I'm afraid it is not. The question is what produces such current to send the transformer to protection mode.

Test for eventual clarification: What if you don't connect the servo control line (orange) to Arduino D9 ? What if you don't use the two different GND connections (already mentioned)

Ground loops can be bad.  Do follow up as suggested in the comments regarding ensuring the power supply grounds are the same. To be specific, connecting the power supply grounds through the Arduino is a bad idea! The trace size should not be assumed adequate for the unknown amount of current passing between the ground outputs of the power supplies.  And a voltage potential can develop causing the processor to behave unexpectedly or worse burn out components.
Also, consider that some Arduino platforms regulate power to 5 volts on the board and that many servos run fine at 5 volts. If this is true here, you could greatly simplify and possibly solve the describe problem by using a single 5 volt power supply.
Lastly, ensure there is a pull up on the 2 inputs connected to the (assumed) normally-open-momentary-contact switches.  There are none in the diagram.  So it is assumed pull ups have been activated in the code such as explained here.


text:
I cant seem to form a code to read both DHT11 and pulse sensor
I combined both the heart pulse sensor code and the DHT11 code. I can get a decent reading from the pulse sensor however an error is given from the DHT11 sensor. I am able to get them to function normally when i set them up individually however when i combine the 2 setups, I am unable to get a reading from the DHT11 although i can get one from the pulse sensor.
I am using ArduinoUNO, DHT11 humidity and temp sensor, and the Pulse Sensor.
THE CODE:
#include <SimpleDHT.h>
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

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

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

void setup() {

  Serial.begin(115200);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pinMode(2,INPUT);
pinMode(A0,INPUT);

  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

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

void loop() {

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

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

  delay(20);                    // considered best practice in a simple sketch.
}
 Serial.println("Sample DHT11...");

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

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

  // DHT11 sampling rate is 1HZ.
  delay(1500);
  }
}

The code can be improved, but I don't see an obvious reason why this should not work. It is likely the 2 Arduino libraries are using the same processor resource. You might have to read through the code for the DHT and PulseSensor to determine and fix the problem.  Or you may blindly try to simplify your sketch until more features work. For example, it appears unnecessary to enable interrupts as the basic PulseSensorPlayground example does not use interrupts.

Hint: Try using the PulseSensor library without interrupts.

currently i have edited my code. the DHT11 works now but the pulse sensor still does not work. I have found that the pulse sensor requires interrupts in order for the code to work but DHT11 does not need interrupts in order for it to work. is there some way that i can detach the interrupts for DHT11 code and attach the interrupts for the pulse sensor??


text:
how can I program my sound sensor and pir motion sensor in 1 arduino uno
int pirPin=2;
int buzzerPin=12;
int soundSensor = 19;
int LED = 3;
int statusSensor=0;
int pirVal=0;
void setup()
{
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(soundSensor, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(LED, OUTPUT);
}
void loop()
{
pirVal=digitalRead(pirPin);
if(pirVal==HIGH)
{
Serial.println("Motion Detected");
digitalWrite(buzzerPin,HIGH);
delay(150);
digitalWrite(buzzerPin, LOW);
}
else
{
digitalWrite(buzzerPin, LOW);
 }
statusSensor = analogRead(soundSensor);

  if (statusSensor == 1)
  {
Serial.println("Sound Detected");
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
  else
  {
    digitalWrite(LED, LOW);
  }
}

Please align your code (select code, press ctrl-k) and align { and } blocks,  what is currently wrong/not according to your expectations? what do you expect?

I expected to run both of them at a time

And what exactly it is not doing now? (we cannot look at the result or expect us to create the circuit you built to check it). How should they interact with each other?

Is your sound sensor analog or digital?

@EmanAli, the body of the question should have more than just the code.  It should also explain your problem.  Remember, the goal is to have a collection of questions and answer that everyone can later use.  If you make an effort to create a good question, then everyone with a similar question will benefit.

First of all there is no pin with pin number 19 (as you defined a soundSensor on it), and there is no problem you can use my sound sensor and pir motion sensor in 1 arduino uno.
But in order to do that please use millis instead of delay so that your arduino doesn't wait to read reading of other sensor during the reading of first sensor.
Here is a link which shows how to use arduino for multitasking..
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview


text:
MPU9250 with Arduino Nano and Arduino Nano 33 BLE
I am trying to read sensor data from two MPU9250s with both one Arduino Nano and a Arduino Nano 33 BLE using SPI. As for the Arduino nano, I was successful to acquire the sensor data and output it in the serial monitor. However, unlike the old Nano device, the new Nano 33 BLE does not output any sensor readings in its serial monitor. Sometimes and very rarely though, I do receive a couple of readings (usually not more than 1-2 readings), after which no readings are received. Apparently, at least the sensor initialization seems to be always working on the 33 BLE device as my code runs past the Sensor OK messages in the setup routine.
I have been using bolderflight's MPU9250 library for talking to the sensors.
I've also tried reading only one sensor at a time, but that didn't really help, as I still didn't receive sensor readings. I didn't try I2C so far, mainly due to a lack of time.
Any ideas of what to try or why things might have gone wrong are appreciated.
Here's my code:
#include "MPU9250.h"

MPU9250 SENSOR1(SPI, 9);
MPU9250 SENSOR2(SPI, 10);
int status1, status2;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status1 = SENSOR1.begin();
  if (status1 < 0) {
    Serial.println("Sensor 1 error!");
    Serial.println(status1);
    while(1) {}
  }
  Serial.println("Sensor 1 OK");

  status2 = SENSOR2.begin();
  if (status2 < 0) {
    Serial.println("Sensor 2 error!");
    Serial.println(status2);
    while(1) {}
  }
  Serial.println("Sensor 2 OK");
}

void loop() {
  // read the sensor
  SENSOR1.readSensor();
  SENSOR2.readSensor();
  // display the data
  Serial.print("X: ");
  Serial.print(SENSOR1.getAccelX_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelX_mss(),6);
  Serial.print("Y: ");
  Serial.print(SENSOR1.getAccelY_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelY_mss(),6);
  Serial.print("Z: ");
  Serial.print(SENSOR1.getAccelZ_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelZ_mss(),6);
  delay(100);
}

Can the library used with the Nano 33? Old Nano and Nano 33 are not the same

To be honest, that is what I am not really certain of. But from what I understood, it should be... but I might have missed something.


text:
Did I kill my ESP8266?
So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a
The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.
If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)

Did you connect 5V power source and 3.3V power source to the ESP8266?

@FilipFranik Yes I did indeed

Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.
I found this document. It states:

VBUS pad and jumber can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

3.3V. Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.
Sorry.

Hmm alright that's a bummer, would this also mean that I killed my Usb Host Mini? Or did I just kill the esp8266? I'll find out tomorrow, once I get a new esp8266, but I thought maybe you know. It would suck if I had to buy another Usb Host Mini, since they're quite expensive.

I'm pretty sure that the chip on the mini is fried (if it wasn't then PC would detect an unknown device plugged in) The USB Host Mini  clone is just 4 USD on Aliexpress with free shipping.


text:
Arduino accepting only alternate characters
I am writing an Arduino code to receive SMS from a SIM800 module and then send the same message back to the sender. My code is as follows:
#include<SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);//Connect to pin 9&10 on GSM module

const byte numChars = 128; //character size
char receivedChars[numChars]; // Store data read from SMS
boolean newData = false; //flag to check if new data has arrived

void setup() {
 Serial.begin(9600);
 mySerial.begin(9600);
 Serial.println("<Arduino is ready>");
 mySerial.println("AT");
 mySerial.println("AT+CMGF=1"); //text mode
 mySerial.println("AT+CNMI=1,2,0,0,0");
 mySerial.println("AT+CSQ"); //Check signal strength
   while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void loop() {
  //code for checking sms
  scanSMS();
  //Print if a new data arrived
  showNewData();
  delay(25000);
}

void scanSMS() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '#'; //Start and end markers. Eg. SMS body will be sent as #status#
    char endMarker = '#';
    char rc;
    while (Serial.available())
    {
      mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
    }

    while (mySerial.available() > 0 && newData == false) {
      Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port

      rc = mySerial.read();

      if (recvInProgress == true) {
        if (rc != endMarker) {
          receivedChars[ndx] = rc;
          ndx++;
          if (ndx >= numChars) {
            ndx = numChars - 1;
          }
        }
        else {
          receivedChars[ndx] = '\0'; // terminate the string
          recvInProgress = false;
          ndx = 0;
          newData = true;
          }
        }
      else if (rc == startMarker) {
        recvInProgress = true;
      }
    }
}

/*PRINT IF THERE IS A NEW DATA*/
void showNewData() {
 if (newData == true) {
   SendMessage(receivedChars);
 newData = false;
 }
}

/*SEND BACK WHATEVER SMS IS RECEIVED*/
void SendMessage(String receivedChars)
{
  Serial.print("here");
  mySerial.println("AT+CMGS=\"+xxxxxxxxxx\"\r"); // Replace x with mobile number
  mySerial.println("Humidity Alert!");// The SMS text you want to send
  mySerial.print(receivedChars);
   mySerial.println((char)26);// ASCII code of CTRL+Z
}

The issue is that the module seems to receive only alternate characters instead of the whole message. For example, if I send the text #program#, the Arduino will only print porm or rga. Am I missing something here? Any help is highly appreciated.

You wrote:
Serial.write(mySerial.read());
rc = mySerial.read();

Here you are calling mySerial.read() twice, and thus reading two
characters from the port's input buffer. You then forward the first
character through Serial, and process the second one. Note that you
should normally not read two characters unless you have tested that
mySerial.available() >= 2.
You probably want to forward and process one character at a time, thus
only call mySerial.read() once within this loop:
rc = mySerial.read();  // read from mySerial
Serial.write(rc);      // forward through Serial
// now process rc


text:
Multi dimming led - figuring out which led is available for dimming
TL;DR: I tried to have a random fading pattern on several leds and it leads to flickering.
Edited following @chrisl answer.
I am in the process of creating a simple lamp that show some light patterns using 6 led and an arduino uno. The goal is that depending on some inputs and a bit of randomisation, the patterns will change. For instance, only 2 lights at the same time but fading up and down randomly on all 6 led. Or 4 lights fading up and down randomly on the 6 leds.
I decided to create a struct that would be a light pattern named a particle, and this particle have a variable named led_position that shows which led it is on at a certain moment. The particle can change its position to light up an other led.
I know this is not the clearest of explanation but I hope my code will be more straightforward:
Main code
        #include "MyTypes.h"
int led1 = 9;    // the PWM pin the LED is attached to
int led2 = 10;
int led3 = 11;
int led4 = 6;
int led5 = 3;
int led6 = 5;

//int led;
int brightness;
int fadeAmount;

// Definition of the different particles
particle_type particle[]={
  { 0,led1,0, 2,   false },
  { 1,led2,50, 2,   false },
  { 2,led3,100,  2,   false },
  { 3,led4,80,  2,   false },
  { 4,led5,30,  2,   false},
  { 5, led6,70,  2,   false},
};

led_type led[]={
  { 3,false },
  { 5,false },
  { 6,false },
  { 9,false },
  { 10,false },
  { 11,false },
};

//initiation of the particles

void initiate_particle(particle_type& particle_example,led_type led[]){

 //take a random led from list of led
  int number=random(5);
  led[number];
  if (led[number].busy == false){ //if led non-occupied
    particle_example.led_position=led[number].led_position;
    led[number].busy = true ;//take this led as output
    }

  else{
//    particle_example.led_position=particle_example.led_position; //keep same led
  }

  particle_example.reset = false; //reset turned off
 // delay(30);

}

void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness

  analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness
  if (particle_example.brightness >=  160) {
    particle_example.fadeAmount = -particle_example.fadeAmount;

  }

  if (particle_example.brightness <=  160 && particle_example.brightness >=  100 ) {
    particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;

  }

  if (particle_example.brightness >= 50 && particle_example.brightness <=  100){
      particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

  }

  if (particle_example.brightness >= 0 && particle_example.brightness <=  50){
      particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;

  }

  if (particle_example.brightness <= 0){
    particle_example.reset= true;
    int number = particle_example.led_position;
    led[number].busy=false;
    particle_example.fadeAmount = -particle_example.fadeAmount;
  }

}

void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

  if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
    initiate_particle(particle_example, led); //initiate it again
  ;}

  else {
   update_light(particle_example,led); //update its brightness
  }
}

void setup() { //create led outputs

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  Serial.begin(9600); //serial for debug

}

void loop() {

  activate_particle(particle[0],led);
//  activate_particle(particle[1],led);

//  activate_particle(particle[2],led);
//  activate_particle(particle[3],led);
//  activate_particle(particle[4],led);
//  activate_particle(particle[5],led);
//

 delay(5); // 20-17-15-12-10-7-2

}

Mytypes.h
typedef struct {
    int id;
    int led_position;
    int brightness;
    int fadeAmount;
    bool reset;
} particle_type;

typedef struct {
    int led_position;
    bool busy;
} led_type;

This seems to work more or less but I still have the problem of particles "choosing" the same led to light up and it make the led flickers.
I am struggling on this. I have tried to add a data field for busy and create a new struct for led to no avail.
Even when only one particle is on, the different leds seems to deactivate after a few rounds.
Let me know if you figure it out, thanks!
EDIT 2:
    #include "MyTypes.h"

int led0 = 3;    // the PWM pin the LED is attached to
int led1 = 5;
int led2 = 6;
int led3 = 9;
int led4 = 10;
int led5 = 11;

//int led;
int brightness;
int fadeAmount;

// Definition of the different particles
particle_type particle[]={
  { 0,led0,0, 4,   false },
  { 1,led1,50, 4,   false },
  { 2,led2,100,  4,   false },
  { 3,led3,80,  4,   false },
  { 4,led4,30, 4,   false},
  { 5,led5,70,  4,   false},
};

led_type led[]={
  { 3,false },
  { 5,false },
  { 6,false },
  { 9,false },
  { 10,false },
  { 11,false },
};

//initiation of the particles

void initiate_particle(particle_type& particle_example,led_type led[]){

 //take a random led from list of led
  int number=random(6);
  Serial.println(number);
  led[number];
  if (led[number].busy == false){ //if led non-occupied
    for (int i=0;i<6;i++){
      if (led[i].led_position==particle_example.led_position){
      led[i].busy=false;
      Serial.println("success");
      Serial.println(led[i].led_position);
      }
    }
    particle_example.led_position=led[number].led_position;
    Serial.println(particle_example.led_position);
    led[number].busy = true ;//take this led as output
    particle_example.reset = false; //reset turned off
    }

  else{
//  initiate_particle( particle_example,led);
}

  delay(30);

}

void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness
      analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness

  if (particle_example.brightness >=  160) {
    particle_example.fadeAmount = -particle_example.fadeAmount;
    particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;
  }

  else if (particle_example.brightness <  160 && particle_example.brightness >=  100 ) {
    particle_example.brightness = particle_example.brightness + 1.5*particle_example.fadeAmount;

  }

  else if (particle_example.brightness > 50 && particle_example.brightness <=  100){
      particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

  }

  else if (particle_example.brightness > 0 && particle_example.brightness <=  50){
      particle_example.brightness = particle_example.brightness + 0.25*particle_example.fadeAmount;

  }

  else if (particle_example.brightness <= 0){
    particle_example.reset= true;
    particle_example.brightness =0;
    int number = particle_example.led_position;

    if (particle_example.fadeAmount<0){
      particle_example.brightness = 0;
      particle_example.fadeAmount = -particle_example.fadeAmount;
    }
    else{
      particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;
    }

  }

}

void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

  if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
    initiate_particle(particle_example, led); //initiate it again
  ;}

  else {
   update_light(particle_example,led); //update its brightness
  }
}

void setup() { //create led outputs
  pinMode(led0, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);

  Serial.begin(9600); //serial for debug

}

void loop() {

  activate_particle(particle[0],led);
  activate_particle(particle[1],led);
  activate_particle(particle[2],led);
//  activate_particle(particle[3],led);
//  activate_particle(particle[4],led);
//  activate_particle(particle[5],led);
//

 delay(10); // 20-17-15-12-10-7-2

}

void loop() {

  activate_particle(particle[0],led);
  activate_particle(particle[1],led);
  activate_particle(particle[2],led);
  activate_particle(particle[3],led);
//  activate_particle(particle[4],led);
//  activate_particle(particle[5],led);
//

 delay(10); // 20-17-15-12-10-7-2

}

Now the code works well up to 3 particles but messes things up for 4,5,6 particles with flickering and absence of light.

That seems like a logic problem for me. You define a "particle", which is not bound to a special LED (like a particle, that is jumping from one position to another). Then you included a busy flag, that should prevent, that a LED is used by more than one particle at a time. But you included this flag in the particle. Being busy is a state of the LED, not of the particle, so including this in the particle won't do, what you want.
If you want to use this logic, you need to create a struct, which represents the individual LED. The struct's fields would be the pin number and the busy flag. You can create the LED list with instances of this struct. Then to choose a new position for the particle, you need to check if the busy flag of that position is set. If not, choose this position and set the busy flag. Clear the flag, when you remove the particle from the position.

After your edit I see more problems. First a general problem: Currently a new particle, that want's to change it's position, needs a free (not busy) position to move to. You have 6 LED positions, so with 6 particles, there won't be any move. You can change this by freeing a LED position (setting it's busy flag to false), when the fading of a particle is finished. Still there might be timing problems with this way, depending on the overall timing behavior of the sketch (The first particle to free a LED position will not find a different free position and has to wait. This might lead to 2 particles just exchanging there positions).
Then in void update_light() you have multiple if statements, which all test the particles brightness. But inside these statements you change the brightness. So it is possible, that multiple of the if statements will execute. You should use if else if instead, so that only one of the statements can execute.
And in void initiate_particle() you check for the chosen LED position to be busy. But if the position is already busy, you are setting the particles reset flag to false anyway. That means that activate_particles() will update the particles brightness despite the fact, that the particles does not have a valid LED position currently. You should not set reset to false, if the particles hasn't got a valid LED position. And the delay at the end of the initiate function does not serve a function in my eyes.

Hi chrisl, sorry for the flood :). Thanks for your answer, now the system works better with 1 to 3 particles but still has trouble with 4,5,6 at the same time.
Let me know if you have an idea.

@Guillaume_slize I added further explanations to my answer

Hi Chris, thanks a lot for the long explanation. It makes things much clearer, I changed the code according to your advices but it is now experiencing some weird behavior (some led lighting just a little).
Two led exchanging their positions or staying in the same when 6 lights/ particles are up is fine, I was hoping for a system that could sustain all configuration from 1 to 6, but might have to code another one for 6.

Ok, I corrected a few mistakes and now it seems to work fine up until 4. I think 5 and 6 is too unstable for so few leds.


text:
Which sensors to choose to detect movement direction
So I'm planning to build a sort of light switch for my Philips Hue bulbs with an Arduino. This project will be mounted on a shelf next to my door to the room, parallel to the walking direction. In order to detect the movement direction to either turn on or off the lights when a person is entering or leaving the room, I need one or two sensors. I've tried HC sr04 before but got inaccurate results which resulted in random changes of the lightstate.
So what sensors will be best for my application? I was thinking about the Sharp IR sensors (i.e. Sharp GP2Y0A60SZLF) but I'm not sure about any possible interference that comes with it when I mount to of these right next to each other. Any ideas?
Thanks in advance!

What "Sharp IR sensors"? Please provide a link or a part number

@chrisl yeah I forgot to add the part number, edited my question

Usually for "light" applications you use cheap PIR movement sensors. Two of them with some paper guards that limit their field of vision in two locations. You can check which is triggered first to deduce direction.

@FilipFranik wait, the PIR are based on infrared aren't they? So they won't detect a moving door when there is no human or ir emitting source nearby? Is it possible to mask the sensor in such a way that there is only a vertical line where the sensor detects a movement? Because that would be great to avoid any light changes when only the door moves but no person is nearby

The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.
The raw sensor looks like this:

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.
Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read this article and look at the sensor response graph.

I guess you want to use 2 IR sensors with a little distance, so that you can check the direction by checking, which one detected an object first. You surely can do this with the mentioned sensor. To avoid interference, you can measure by one one, deactivating the other over it's enable pin during that time. It should be fast enough, so that you can do this sufficiently.
I would say using a distance sensor is overkill here. For checking, if someone comes in or out, you don't need distance information. Just 2 light barriers would be sufficient. For example a little laser pointer (could also be IR), a little mirror at the other side and a fitting photodiode. I think there are ready made modules to buy. Their output would only be digital, not analog.


text:
multiple graphs on serial plotter
I'm trying to  run an Arduino code that simultaneously:
1) blinks an led on-off every 3 seconds
2) gets a voltage input from an EMG sensor and positions a servo motor accordingly
While I run this program, I'd like to plot the following on the same graph
1) LED status on/off printed as 600 if on and 0 if off
2) EMG value being fed to the arduino
3) The angle the Arduino is sending to the servo motor
I wrote the following code which works to an extent but the problem I'm facing is, I only get two graphs on the plotter instead of 3, I think the EMG value and the angle have combined into a single line as seen in this picture:

However, if I remove the angle print statement, I get a proper graph for the other 2 as this:

How do I change my code so I can plot all three separately?
Thanks in advance.
#include <Servo.h>
Servo myservo;
const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 3000;
int led=0;
int servovalue=0;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(A0);
int angle = map(sensorValue, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print(sensorValue);
Serial.print(“ ”)
Serial.println(angle);
delay(15);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
      led = 600;
    } else {
      ledState = LOW;
      led = 0;
    }
    digitalWrite(ledPin, ledState);
  }
  Serial.print(" ");
    Serial.println(led);
}

Paste the code in a format that we can actually copy and test. And also embed the images instead of linking them. They will be removed from their current location some day, and this question will be useless to other people having similar issues as you have.

The part of your code that prints data to the serial looks like this:
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}

The bug is in the Serial.println(angle); line. The println method inserts a "newline" character at the end. Try changing it to Serial.print(angle); so there is only one "newline" character.
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}


text:
Need to know what USB cable to get for Arduino Nano-33-BLE-Sense
I have recently purchased an Arduino Nano-33-BLE-Sense with Headers and wrongly assumed that it would come with a USB cable with it. I was searching the online store for the cable but the only cable on the store that I see is for Type A to Type B which in its description does not mention my board.
Does anyone have any experience with this board and know which cable I need? Thanks in advance!

why don't you google USB connector types and compare pictures?

it is the most common USB cable. I am sure you have more then one at home. – Juraj Sep 26 at 9:02

Looks like this board

Is connected to the PC with connector commonly named simply "Micro USB". Wikipedia calls it "USB 2.0 Micro-B"
It's the same cable that all mobile phones used (before USB-C standard arrived). Check your phone charger.


text:
Library compilation error
Need help for this Tutorial. I tried to compile the code, but I'm getting compiling error.
I tried to ask on that forum too but got no answer, the error is:
In file included from C:\Program Files (x86)\Arduino\libraries\SD\src/utility/SdFat.h:32:0,
Multiple libraries were found for "SD.h"from C:\Program Files (x86)\Arduino\libraries\SD\src/SD.h:20,
 Used: C:\Program from D:\FEMV3FKI7YLJVQQ\FEMV3FKI7YLJVQQ.ino:1:
 Not used: C:\Users\IBNUM
C:\Program Files (x86)\Arduino\libraries\SD\src/utility/BlockDriver.h:31:10: fatal error: FatLib/BaseBlockDriver.h: No such file or directory
Multiple libraries were found for "SPI.h"
 #include "FatLib/BaseBlockDriver.h"
 Used: C:\Program
          ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this Arduino compile error?

you copied parts of the SD library to your sketch folder?

@Juraj no, i use import .Zip file in arduino IDE

@jsotola i'm sorry, i need to edit my question

delete the library from your sketches folder, which you installed with zip. it was already installed with the IDE

1.8.9 working fine for my sketch, but 1.8.10 said compiling error.

I have the same problem since version 1.8.10.
With a good running sketch I don't get any message "Multiple libraries were found" (and no warnings also)
But with every small compiler error I get a whole list of "Multiple libraries were found"
My custom libraries are in a sketchbook location
D:\DATA BACKUPPED\Documenten Albert\Arduino\Sketchbook-and-user-libraries

This answer is really pointing to a really easy but hard to notice reason for getting the duplicate library messages.  Just one compile error and this message can be thrown, however it has nothing to do with the actual problem with the code.


text:
What sensors to measure grass growth?
I would like to make a small project, which would allow me to recognize if the grass has grow enough to lawn. I don't know too much the ecosystem of available sensors for such problem. And I have a lot of grass and some irregular areas to clean once in a while.
Is that something I can do with an arduino and some sensors, or should I need to use more processing power and cameras/AI?
TIA!

measure the grass indirectly ... keep track of the weather and of the irrigation schedule

@jsotola that seems a quite complex model to implement, depending on a lot of variables, which in final terms is more expensive than using some cheap sensors.

My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.

That's an idea. In fact we could just need one that's not covered by the grass, to contrast the light of all others that could be at ground level...

I think having them in close proximity pairs would be better for detecting things like building shadow at the end of the day or a dog laying on the grass for an hour.

might not work in the real world because the lens will be dirty in a month or so.

Be sure not to mow only the gras not the sensors :D


text:
Variable updated in ISR is miscounting
I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a uint32_t variable is incremented.
In the main program, a while loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.
while(stepcounter <= threshold) {
}
disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to disablecounter() even though stepcounter has not reached threshold.
If I stack the while loop like this:
while(stepcounter <= threshold) {
}
while(stepcounter <= threshold) {
}
disablecounter();

it runs just fine. This also works:
while(stepcounter <= threshold) {
  while(stepcounter <= threshold) {
  }
}
disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a uint16_t for stepcounter, but after a higher number of cycles.
For analysis, I'm simply running this loop over and over again; setting stepcounter back to 0 and restarting the timer. With uint32_t, it usually fails after the 5th or so loop. For uint16_t, it fails after around 25 loops.
Using a tempstepcounter like this also seems to work, but only when comparing against both counters at the same time:
while(tempstepcounter <= threshold || stepcounter <= threshold) {
  tempstepcounter = stepcounter;
}
disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.
ISR code:
ISR(TIMER1_COMPA_vect) {
  PORTF ^= (1 << PORTF0));
  stepcounter++;
}

Hint: Please add the declaration of the variable. It is volatile? And it is protected by a critical-section (i.e. no interrupts) when reading and writing? Operations on 32-bit integers are not atomic on the AVR MPU. Not even 16-bit integers.

stepcounter is declared as volatile.
It it only written to (when the timer is running) inside the ISR, but not during the while()-loop - honestly not sure how I'd protect it there.

What does the ISR code look like?

@ElliotAlderson Updated the question

Possible duplicate of Can arduino interrupts occur in a middle of if statement?

You need to protect the read as well.

You need to declare it volatile in both places and shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.
'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.
An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.
If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.

Yep, that was pretty much the issue.
I implemented your suggestion of a single-byte flag, which the ISR sets and the while loop queries. If it has been set, tempstepcounter is updated while protected by cli() and sei().


text:
ultrasonic phased array
I have the following code for Arduino mega to output 40 kHz square waves at the analog pins. I need to apply specific phase delays for the signals at each pin though and am struggling to find out how to do this. Any help would be appreciated.
Thanks!
byte TP = 0b10101010; // Every other port receives the inverted signal

void setup() {

DDRF = 0b11111111; // Set all analog ports to be outputs
DDRK = 0b11111111; // Set all analog ports to be outputs
// Initialize Timer1

noInterrupts(); // Disable interrupts

TCCR1A = 0;

TCCR1B = 0;

TCNT1 = 0;

OCR1A = 200; // Set compare register (16MHz / 200 = 80kHz square wave -> 40kHz full wave)

TCCR1B |= (1 << WGM12); // CTC mode

TCCR1B |= (1 << CS10); // Set prescaler to 1 ==> no prescaling

TIMSK1 |= (1 << OCIE1A); // Enable compare timer interrupt

interrupts(); // Enable interrupts

}

ISR(TIMER1_COMPA_vect) {

PORTF = TP; // Send the value of TP to the outputs
PORTK = TP;
TP = ~TP; // Invert TP for the next run

}

void loop() {

// Nothing left to do here :)

}

Do you need multiple pins with linear growing phase delay?

Hi Chris :) I need multiple pins with different phase delays.

I suspect that you can't do that. The square wave output on AVR-based Arduinos is pretty crude, and relies on interrupt-driven counters and dividers to generate the outputs. I doubt if the hardware has enough precision to manage outputs with different phases. You might need to use external signal generator hardware for this.

hi Duncan :) thanks for the response. I am outputting the signals to the analog pins though not the PWM.

What phase delays do you need? Are they constant or variable? Will the program eventually grow and have something in loop() Could you use different pins?

I will calculate the phase delays in MATLAB depending on the desired focal point and apply the phases in the arduino code accordingly. yes it could have something in loop!  I could use different pins. open to suggestions. I have not used arduino before so am new to it :)


text:
Follow black and white line simultaneously
I have a line following bot which uses IR sensors (LSA08, more specifically) to detect the white line on black surface and stay on track. For the project however, there is a trick in the track. At a certain point, the line changes from white to black and the bot is expected to follow the black line on the white surface.
My question is, how would I design the algorithm which will make the bot recognise that the track and conditions have changed.

How many IR sensors do you use for detecting the line?

The LSA08 has 8 IR sensors

Assume the "road" line is narrower than the bot's width. Sense light/dark across the road-width by enough more that it can see both edges plus enough to regain the roadway at a sharp bend.
Now pretend we don't know what color the roadway is - which is in fact, true! But we do know that the sensors should see either:
[W, W, W, ... W, B, B, ..., B, W, ..., W] (black stripe), or
[B, B, B, ... B, W, W, ..., W, B, ..., B] (white stripe).
Call W(hite) a 1 and B(lack) a zero. The above conditions, stored in an unsigned int, might look (in binary) like:
1111110000111111, or
0000001111000000.
One is just an inversion of the other, right? So read your sensors (and I'm going to assume perfect robo-vision for a moment: no noisy signals and we know we're on the roadway), and if necessary, invert the result so it look like my second case, 0000001111000000, a group of ones surrounded by a group of zeros shows we're (somewhat) centered on the track. You no longer need to know what color the roadway is!
We assumed perfect signals - in reality you'll need some smarts to detect and correct an odd 1 in the midst of a bunch (technical term here) of 0s, or vice versa.
We assumed your bot is kind of centered on the track; able to see both roadway edges. In reality, sometimes you may be losing it - 111000000000000, or drifting to the right. If you can't ensure this won't happen, you'll need to be able to recognize it and correct it. And, here is where we need to know something about the roadway color. We knew what color it was recently, just before we started to drift off, so we'll just continue inverting (or not inverting) our stored sensor data - IF the color doesn't change until the bot re-centers itself (nasty track designers)! If your design criteria can include that the bot doesn't lose either edge of the track, you can always recover, even during a color change. Otherwise you'll have to recognize and respond to a color change even when you can only see one edge. Use the recent road-color to keep track of this.
Hope that helps.

It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.


text:
How to use external libraries in CLion
I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (~/Arduino/libraries/).
If you open Library Manager in Arduino IDE and if you install an external library (e.g DHT sensor library 1.3.7 and its dependency Adafruit Unified Sensor 1.0.3) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.
However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.
I have installed CLion and Arduino Support 1.4.4 Plugin and created a new Arduino Sketch Project.
Project Structure:
.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h

first_test_project.ino:
#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}

So I have copied over the downloaded libraries from ~/Arduino/libraries folder to the project folder under libs folder.
When I try to upload the code to Arduino Board I am getting the following in the log:
undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'

Could somebody please explain what is wrong here.
Thank you very much!

Are you sure you are using the correct method signature, it seems that this method signature of the constructor does not exist: dht = new DHT(7, DHT22); takes 2 args, versus what is the complain is 3 args, something is not right

In my opinion, the easiest way for the beginner is to use Platformio, it sets up CLion project automatically.
See docs for more info.

do you have any link to configure platform IO, I'm using CLion as an editor and arduino IDE to compile and deploy to microcontroller, if there is any guide available it would be helpful to share. thanks

@OmarS. see the edited answer. It also configures build tasks for uploading, so no need to use Arduino IDE. But read the docs carefully: remember pressing "build" hotkey for all tasks instead of "run".

Did you add your libraries to the cmake files?
I don't have any experience with CLion but undefined reference normally means that
the linker couldn't find the function/class your are using.
So make sure the libraries are compiled and the linker knows where to find the object files.


text:
I2C Wire.onRequest not detected
I want to know why Wire.onRequest can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)
I was able to read this part of the massage with wire.onReceive:

But I can not read this massage at all, which is requesting:

#include <Wire.h>
byte val = 170;
int sendv;

char c;

byte dataArray[16];

void setup() {
  Wire.begin(0x77);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() { }

void receiveEvent(int howMany) {
  Serial.println(howMany);

  if (howMany >= 2) {
    for (int i = 0 ; i < howMany; i++) {
      dataArray[i] =  Wire.read();
      Serial.println(dataArray[i], HEX);
    }

  } else {
    c =  Wire.read();
    Serial.println(c, HEX);
  }
}

void requestEvent() {
  Serial.println("REqEVENT");
}

So you mean in your code you are never seeing the REqEVENT in the serial monitor? Normally in the onRequest callback you would write data to the I2C buffer, so that it can be send

Yes, when I run the code I never goes inside of request event and I dont see REqEVENT, which it should becouse 0xEFm or 0xEE is correct address

Are the images from the transmission from your code? That would fit your code, since you don't send any data on request. Maybe sending over serial is not a good test here, since the function get's called from an ISR. Try to light an LED inside the function to test, if the code get's there. Also try to actually send data and see, if this data get's actually send, by watching your logic analyser.

I have tried sending massage which did not work, I just tried Led too and not turning on, Also you can see on logic analyzer is getting 0xFF

I was able to solve the issue with by adding  twi_stop(); to twi.c
base on this website
enter link description here


text:
HM-10 doesn't responde after RENEW
Today I finally got two HM-10 modules. I did flash firmware using this tutorial. It worked until I didn't send AT+RENEW command. Now, LED blinks, I see device in BT terminal(Android phone) but I can't connect to it. Terminal says Connection failed: write descriptor failed. I tried sending commands over COM port from PC, but it doesn't responde.
Also I connected pin 11 to GND, problem is still here. Strange thing - After firmware flash, AT+HELP doesn't exist, while AT+HELP? returns some website.
For second module, LED doesn't blink but I see module in BT terminal. It also stopped working after AT+RENEW. When I try to connect, I get same error.

it is unclear what you are doing ... the tutorial that you linked is NOT for flashing firmware to an HM-10 ... it is possible that you broke the device by flashing the firmware

change your COM serial baud rate to 115200. I had the same problem and the moment I change the baud rate on my Serial Com or Serial monitor. it works for me