text:
Servo motor and L298N motor driver don't work together with ESP32
I am using four servo motors for our robotic arm and one L298N motor driver for two motors for the base of the arm.
When I individually tested the robotic arm and controlled four servo motors it worked perfectly fine, and when I tested the linear motion with the motor driver individually it also worked fine.
When I combined them only the servos were working but the L298N doesn't. When I comment out the servos.attach() line, then the motor driver works again.
The pins are different, that's why I couldn't figure out why am I getting this issue.
#include <WiFi.h>
#include <WebServer.h>
#include <Robojax_L298N_DC_motor.h>
#include<Servo.h>

WebServer server(80);
Servo myservo, shoulder, elbow, wrist;
int grippos = 0, shoulderpos = 0, elbowpos = 0, wristpos = 0;

// motor 1 settings
#define CHA 0
#define ENA 19 // this pin must be PWM enabled pin if Arduino board is used
#define IN1 18
#define IN2 5

// motor 2 settings
#define IN3 15
#define IN4 2
#define ENB 4 // this pin must be PWM enabled pin if Arduino board is used
#define CHB 1

const int CCW = 2; // do not change
const int CW  = 1; // do not change

#define motor1 1 // do not change
#define motor2 2 // do not change

String prev="";

Robojax_L298N_DC_motor robot(IN1, IN2, ENA, CHA,  IN3, IN4, ENB, CHB);

void gripopen() {
  Serial.println("open");
  grippos += 30;
  if (grippos > 180) {
    grippos = 180;
  }
  myservo.write(grippos);
}

void gripclose() {
  grippos -= 30;
  Serial.println("close");
  if (grippos < 0) {
    grippos = 0;
  }
  myservo.write(grippos);
}

void wristleft() {
  wristpos -= 30;
  Serial.println("wristleft");
  if (wristpos < 0) {
    wristpos=0;
  }
  wrist.write(wristpos);
}

void wristright() {
  Serial.println("wristright");
  wristpos += 30;
  if (wristpos>180) {
    wristpos = 180;
  }
  wrist.write(wristpos);
}

void elbowup() {
  Serial.println("elbow up");
  elbowpos += 15;
  if (elbowpos > 180) {
    elbowpos = 180;
  }
  elbow.write(elbowpos);
}

void elbowdown() {
  Serial.println("elbow down");
  elbowpos -= 15;
  if (elbowpos < 0) {
    elbowpos = 0;
  }
  elbow.write(elbowpos);
}

void shoulderup() {
  Serial.println("shoulder up");
  shoulderpos += 15;
  if (shoulderpos > 180) {
    shoulderpos = 180;
  }
  shoulder.write(shoulderpos);
}

void shoulderdown() {
  Serial.println("shoulder down");
  shoulderpos -= 15;
  if (shoulderpos < 0) {
    shoulderpos = 180;
  }
  shoulder.write(shoulderpos);
}

void forward() {
  Serial.println("forward");
  robot.rotate(motor1, 100, CW);
  robot.rotate(motor2, 100, CCW);

Serial.println("end reached");
}

void backward() {
  Serial.println("backward");
  robot.rotate(motor1, 100, CCW);
  robot.rotate(motor2, 100, CW);
  Serial.println("end reached");
}

void left() {
  Serial.println("left");
  robot.rotate(motor1, 100, CW);
  robot.rotate(motor2, 100, CW);
Serial.println("end reached");
}

void right() {
  Serial.println("right");
  robot.rotate(motor1, 100, CCW);
  robot.rotate(motor2, 100, CCW);
  Serial.println("end reached");
}

void stopbot() {
  Serial.println("stopbot");
  robot.brake(1);
  robot.brake(2);
  prev = "";
  Serial.println("end reached");
}

void reset() {
  myservo.write(0);
  shoulder.write(0);
  elbow.write(0);
  wrist.write(0);
}

void handleRoot() {
  server.send(200, "text/plain", "Ready");
}

void handleGet() {
  if (server.hasArg("data")) {
    String data = server.arg("data");
    if (data == "gripper_open") {
      gripopen();
    } else if (data == "reset") {
      Serial.println("Reset");
    } else if (data == "Stop") {
      stopbot();
    } else if (data == "Forward") {
      // forward();
      if (prev != data) {
        forward();
        prev = data;
      }
    } else if (data == "Backward") {
      // backward();
      if (prev != data) {
        backward();
        prev=data;
      }
    } else if (data == "Left") {
      // left();
      if (prev != data) {
        left();
        prev = data;
      }
    } else if (data == "Right") {
      // right();
      if (prev != data) {
        right();
        prev = data;
      }
    } else if (data == "gripper_close") {
      gripclose();
    } else if (data == "elbow_up") {
      elbowup();
    } else if (data == "elbow_down") {
      elbowdown();
    } else if (data == "shoulder_up") {
      shoulderup();
    } else if (data == "shoulder_down") {
      shoulderdown();
    } else if (data == "Wrist_left") {
      wristleft();
    } else if (data == "Wrist_right") {
      wristright();
    }
    Serial.println("Data: " + data);
  }

  server.send(200, "text/plain", "Data Received");
}

void handlePost() {
  if (server.hasArg("data")) {
    String data = server.arg("data");
    Serial.println("Data: " + data);
  }

 // server.send(200, "text/plain", "Data Received");
  server.send(200, "text/plain", "Processing Data");
}

void handleUpload() {
  HTTPUpload& upload = server.upload();
  if (upload.status == UPLOAD_FILE_START) {
    Serial.println("Receiving data:");
  } else if (upload.status == UPLOAD_FILE_WRITE) {
    Serial.write(upload.buf, upload.currentSize);
  } else if (upload.status == UPLOAD_FILE_END) {
    server.send(200, "text/plain", "Data: ");
  }
}

void setup() {
  Serial.begin(9600);
  WiFi.softAP("ESP32");
  myservo.attach(13);
  shoulder.attach(12);
  elbow.attach(14);
  wrist.attach(27);

  myservo.write(0);
  shoulder.write(0);
  elbow.write(0);
  wrist.write(0);

  // motordriver pins
  robot.begin();

  server.on("/", handleRoot);
  server.on("/get", HTTP_GET, handleGet);
  server.on("/pot", HTTP_POST,handlePost);
  server.begin();
}

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

I am receiving the correct data from the app that I also cross-checked. Can anyone help me with this or guide me how can I solve this issue?

How do you power everything?

12v lithium polymer battery 2200mAh. @chrisl

And I guess you have connected the 12V from the battery directly to the L298N for powering the motor with 12V, am I right? I don't see an obvious error. Is the Serial output as expected? Have you checked the voltages (if they really stay as expected and not go down when running the motor)?

yes input voltage to l298n shows to be around 12v. also I have kept ground common with esp32. Serial monitor also gives correct output indicating that right function is being called. that's why I also don't understand where the issue lies. @chrisl

This tutorial states that you cannot use the standard Servo library for an ESP32. Honestly I would think that this isn't a problem anymore, but you could try the library, that is mentioned there.

honestly the library that I have used is for servo with esp32 only. library isn't a problem i guess @chrisl

I had it so that EnA from L298N was pin #10 and my servo was pin #2 and it wasn't working. But then I switch them up and it works fine.

Hi I have the same problem here, and everything is pointing the issue could be related with the channels shared for PWM. In the Robojax lib there is control of channels want to assign for each motor, but in the ESP32Servo the channels are assigned automatically by the library in consecutive order (see ESP32PWM.cpp). I would try use different channel when calling Robojax that doesn't make conflict with the amount of Servo controlled, maybe could help. For instance in my case I have one servo and 2 DC motors controlled by LN98. So the servo is using channel 0 for PWM, the other two motors on Robojax I will try CHA= 2 and CHB = 3. Maybe this could help.
There are timers shared is explained on the ESP32PWM.cpp, line 259, but I believe the channels conflicts is what is causing this issue.
I will try and let you know. Thanks
I already finished, and for me it is working now. Just need to change CHA and CHB to different PWM channel number (0-15), but > than the amount of servo you have. thanks

actually even I felt the same and I was going to try that today. I guess it will work. Thank you bro

I have faced same issue. But, after some R&D I have change PWM channel number of l298n motor. And now its working properly.
Thanks for share this.

Could you [edit] and expand upon, how you changed the PWM channel number, and what to?


text:
How can I do web hosting having all the code of the site stored on an SD?
I am carrying out this project in which the Arduino acts as a web server and hosts a website in which I show the constantly updated temperature of a laboratory.
The problem is running all this code in the Arduino: memory runs out easily.
void loop() {
  int value = analogRead(PIN_LM35);
  float temperature = value / 2.046;
  myFile = SD.open("temperature.txt");
  if (myFile) {
    Serial.println(temperature);
  }
  myFile.close();

  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString); //print to serial monitor for debuging

          client.println(F("HTTP/1.1 200 OK")); //send new page
          client.println(F("Content-Type: text/html"));
          client.println();
          refreshcounter = refreshcounter + 1;
          client.println(F(""));
          client.println(F(""));
          client.print(F("<meta http-equiv=\"refresh\" content=\"2\">"));
          client.println(F("<meta name='apple-mobile-web-app-capable' content='yes' />"));
          client.println(F("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />"));
          client.println(F("<TITLE>TEMPERATURE SENSOR LAB01</TITLE>"));
          client.println(F(""));
          client.println(F(""));
          client.println(F("
TEMPERATURE SENSOR LAB01
"));
          client.println(F("
"));
          client.println(F("
"));
          client.println(F("
Arduino with Ethernet Shield
"));
          client.println(F("
"));
          if (temperature < 24) {
            client.println("
");
            client.println(temperature);
            client.println("
");
          }
          else if (temperature >= 24 && temperature <= 26) {
            client.println("
");
            client.println(temperature);
            client.println("
");
          }
          else {
            client.println("
");
            client.println(temperature);
            client.println(F("
It is recommended to activate the air conditioner.
"));
            client.println("
");
          }
          client.println(F("
Date/Time:
"));
          client.println(F(""));

          client.println("<svg width=\"1000\" height=\"250\">");
          client.println("<rect width=\"150\" height=\"5\" fill=\"gray\">");
          client.println("<animate attributeName=\"x\" from = \"0\" to =\"10000\" dur=\"10s\" fill=\"freeze\" />");
          client.println("</rect");
          client.println("</svg>");

          client.println("
");
          client.println("");
          client.println("");

          delay(1);
          //stopping client
          client.stop();
          //clearing string for next read
          readString = "";
        }
      }
    }
  }
}

I put all the code of the web page on an external SD card to save memory. However, I don’t really know how to use it from the SD card.
The problem that stops me is the fact that the site is not static, but is constantly updated with new temperature data.
How can I do that?

why you don't use F() for every string? With Arduino Uno if you use the Ethernet library and the SD library you run out of flash and SRAM very fast.

I tried, but I was running out of flash memory, too

You wrote:

the site does not have to be static but constantly updated with new
temperature data.

A good option is to use Ajax.
The basic idea is to split the site in two parts:

a static part, potentially large, which contains all the user
interface, the styling, the bells and whistles...
a tiny, dynamic part that contains the data that is constantly updated
and nothing more.

The static part would be served from the SD card when the client sends a
GET / request. The dynamic part would be served from another endpoint,
for example as a reply to GET /temperature. Serving the dynamic part
should be very simple, something like:
client.println(temperature);

Yes, just send the number as ASCII, no HTML formatting. If you ever need
to send more than one number (e.g. multiple temperatures, or temperature
and humidity), format them in JSON. No need to use a library for
that, plain print() should be cheaper and good enough:
client.print(F("{\"temperature\":"));
client.print(temperature);
client.print(F(",\"humidity\":"));
client.print(humidity);
client.print('}');

On the client side, JSON.parse() gets the data back as an easy-to-use
data structure.
Here is a minimal example of what the static part could look like.
Notice the JavaScript code sent to the client. This code is responsible
for querying the temperature every 1000 milliseconds, and updating the
Web page with the new data;
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Ajax test</title>

Ajax test

Temperature: --- °C

A few notes:

This example is purposefully minimal. You may want to add some error
checking, some decorations, some CSS and the such. Handling a
temperature-dependent color also belongs to the client code.

The example uses good old XMLHttpRequest. You may want to try the
more modern fetch API instead:
setInterval(function() {
    fetch("/temperature")
        .then(response => response.json())
        .then(data => { data_field.innerText = data; });
}, 1000);

If you are sending updates frequently enough to significantly load
your Arduino, you may want to look at Server-sent events. This
is a technique that allows you to significantly reduce the overhead of
sending data updates. It is not as popular as Web-sockets, but has the
advantage of being simpler to implement server-side.

If you can put a reverse-proxy between your Arduino and the Internet,
the proxy can handle the static content. Your Arduino then only
handles the dynamic data and wouldn't need an SD card. If you
reverse-proxy Server-sent events, make sure the proxy doesn't buffer
the server response. See for example these tips on configuring
Nginx for this purpose.

The static data could also be served from a completely different Web
site. For this to work, you have to fulfill two conditions:

The Arduino server has to add the header
Access-Control-Allow-Origin: * to its responses.

On the client code, you have to provide the full URL of the Arduino
as an argument of request.open(), fetch() or
new EventSource().

The previous trick also allows you to open the Web page directly from
your local file system, which can be very handy for developing.

Once you get the basic scheme working, Web technologies allow you to
get as fancy as you want. You could create an analogue gauge (with SVG
transform rotate). You could even add a graph, updated in
real time, that shows the time evolution of the temperature, and is
entirely handled by the client.

source: Stack Exchange

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

sort: votes


text:
Why does the data I send to the server get rounded off and how do I send the entire float instead?
#include <Arduino.h>
#include <WiFi.h>
#include "WiFiManager.H"
#include <HTTPClient.H>
#include "ESPAsyncWebServer.h"
#include <AsyncTCP.h>

float version = 1.9;

uint32_t chipId = 0;
String chipId2 = "";
int i;

String serverName = "http://d";

// WiFiManager
// Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;

// Create AsyncWebServer object on port 80
AsyncWebServer server2(80);
WiFiServer server(80);

// variables to count the pulses of the meters.
int count1=0;
float prior_count1=0;
int count2=0;
float prior_count2=0;
int count3=0;
float prior_count3=0;
int count4=0;
float prior_count4=0;
int countgas=0;
float prior_countgas=0;
int countwater=0;
float prior_countwater=0;

String payloadpulse = "0";

unsigned long lastTime = 0;
unsigned long timerDelay = 6000;

String guifactor1 = "1000";
String guifactor2 = "1000";
String guifactor3 = "1000";
String guifactor4 = "1000";
String guifactorgas = "1000";
String guifactorwater = "1000";

String counter1 = "1";
String counter2 = "1";
String counter3 = "1";
String counter4 = "1";
String counter5 = "1";
String counter6 = "1";

// function to increment the meters value by 1.
void pulse1() {
  if (counter1.toInt() == 1) {
    count1 = count1 + 1;
  }

  if (counter1.toInt() == 2) {
    count1 = count1 - 1;
  }
}

void pulse2() {
  if (counter2.toInt() == 1) {
    count2 = count2 + 1;
  }

  if (counter2.toInt() == 2) {
    count2 = count2 - 1;
  }
}

void pulse3() {
  if (counter3.toInt() == 1) {
    count3 = count3 + 1;
  }

  if (counter3.toInt() == 2) {
    count3 = count3 - 1;
  }
}

void pulse4() {
  if (counter4.toInt() == 1) {
    count4 = count4 + 1;
  }

  if (counter4.toInt() == 2) {
    count4 = count4 - 1;
  }
}

void pulsegas() {
  if (counter5.toInt() == 1) {
    countgas = countgas + 1;
  }

  if (counter5.toInt() == 2) {
    countgas = countgas - 1;
  }
}

void pulsewater() {
  if (counter6.toInt() == 1) {
    countwater = countwater + 1;
  }

  if (counter6.toInt() == 2) {
    countwater = countwater - 1;
  }
}

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

  wifiManager.autoConnect("ss", "ss");

  pinMode(25, INPUT_PULLDOWN); // Set GPIO25 as digital output pin
  attachInterrupt(digitalPinToInterrupt(25), pulse1, RISING);

  pinMode(19, INPUT_PULLDOWN); // Set GPIO19 as digital output pin
  attachInterrupt(digitalPinToInterrupt(19), pulse2, RISING);

  pinMode(23, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
  attachInterrupt(digitalPinToInterrupt(23), pulse3, RISING);

  pinMode(18, INPUT_PULLDOWN);// Set GPIO18 as digital output pin
  attachInterrupt(digitalPinToInterrupt(18), pulse4, RISING);

  pinMode(21, INPUT_PULLDOWN); // Set GPIO22 as digital output pin
  attachInterrupt(digitalPinToInterrupt(21), pulsegas, RISING);

  pinMode(5, INPUT_PULLDOWN); // Set GPIO5 as digital output pin
  attachInterrupt(digitalPinToInterrupt(5), pulsewater, RISING);
}

//--------------------------------------------------------------------
void loop() {
  float new_count1  = static_cast<float> (count1) / guifactor1.toInt();
  float new_count2 = static_cast<float> (count2) / guifactor2.toInt();
  float new_count3 = static_cast<float> (count3) / guifactor3.toInt();
  float new_count4 = static_cast<float> (count4) / guifactor4.toInt();
  float new_countgas = static_cast<float> (countgas) / guifactorgas.toInt();
  float new_countwater = static_cast<float> (countwater) / guifactorwater.toInt();

  // keeps track of the amount of pulses of pulse meters
  if (new_count1 != prior_count1 ||
   new_count2 != prior_count2 ||
    new_count3 != prior_count3 ||
     new_count4 != prior_count4 ||
      new_countgas != prior_countgas ||
       new_countwater != prior_countwater) {
     Serial.println(new_count1, 4);
     Serial.println(new_count2, 4);
     Serial.println(new_count3, 4);
     Serial.println(new_count4, 4);
     Serial.println(new_countgas, 4);
     Serial.println(new_countwater, 4);
     prior_count1 = new_count1;
     prior_count2 = new_count2;
     prior_count3 = new_count3;
     prior_count4 = new_count4;
     prior_countgas = new_countgas;
     prior_countwater = new_countwater;
  }
  // sends an update to the web
  if ((new_count1 > 0 && ((millis() - lastTime) > timerDelay)) ||
   (new_count2 > 0 && ((millis() - lastTime) > timerDelay)) ||
    (new_count3 > 0 && ((millis() - lastTime) > timerDelay)) ||
     (new_count4 > 0 && ((millis() - lastTime) > timerDelay)) ||
      (new_countgas > 0 && ((millis() - lastTime) > timerDelay)) ||
       (new_countwater > 0 && ((millis() - lastTime) > timerDelay))) {
  {
      // checks if wifi is connected.
      if (WiFi.status()== WL_CONNECTED) {
        HTTPClient http;
        // preparation HTTP GET request.
         String serverPath = serverName + "?chip_id=" + chipId + "&count1=" + new_count1 + "&count2=" + new_count2 + "&count3=" +
         new_count3 + "&count4=" + new_count4 + "&countgas=" + new_countgas + "&countwater=" + new_countwater;
        // Your Domain name with URL path or IP address  with path.
        http.begin(serverPath.c_str());
        // Send HTTP GET request.
        int httpResponseCode = http.GET();
        // confirms the arrival of a response from the server or sends an error.
        if (httpResponseCode>0) {
          count1 = 0;
          count2 = 0;
          count3 = 0;
          count4 = 0;
          countgas = 0;
          countwater = 0;
          payloadpulse = http.getString();
          Serial.println(payloadpulse);
         }
         else {
          Serial.print("Error code: ");
          Serial.println(httpResponseCode);
         }
        // closes the HTTP connection.
        http.end();
      }
      else {
       Serial.println("WiFi Disconnected");
      }
    }
  }

  //reset timer when done sending data
  if (((millis() - lastTime) > timerDelay)) {
    lastTime = millis();
  }
}

The program is a pulse counter which should add 0.001 pulse everytime it detects one. I expect it to send 0.006 to the server, but instead it sends 0.01. How do I make sure it doesn't send rounded data?

It might be rounded by float to String conversion. You might want to use something like: String(someFloat, 3). Also you have to remember there are limits for the floating point numbers, but in this case it should be ok. Implicitly decimal points are 2 places only: String(double, unsigned char decimalPlaces=2);

@KIIV: This should be an answer.

There are too many String objects here, which are heavyweight and unfriendly to the Arduino memory. guifactor1 & co. should be int or float. counter1 & co. should be ints equal to ±1 that you add to the counters: void pulse1() { count1 += increment1; }.

@EdgarBonet this is not my entire code the guifactor for example is a string because i save it to the spiffs

Is this code run on a NodeMCU (or other ESP8266 or ESP32-based board)? If so, you could use the printf function i.e. Serial.printf("%.5f", someFloat); with "5" being the number of digits you need after the decimal point. The printf format is described here.

The constructor for the String object from float is this:
String(double, unsigned char decimalPlaces=2);

So if you don't want to have 2 decimal digits, you have to use String(someFloat, 3).
Also you have to remember there are limits for the floating point numbers, but in this case it shouldn't be the case.
And as Edgar mentioned, String objects are bit dangerous if they are overused, particularly building that serverPath is the worst way how to do it (every single level of it creates new temp object to be copied into next bigger one and released).
It would be cheaper to do it like:
String serverPath;
serverPath.reserve(100); // reserve space so it doesn't have to resize; should be proper estimate
serverPath += serverName;
serverPath += "?chip_id=";  // on AVR it should be F()
serverPath += chipId;
serverPath += "&count1=";
serverPath += new_count1;
serverPath += "&count2=";
serverPath += new_count2;
serverPath += "&count3=";
serverPath += new_count3;
serverPath += "&count4=";
serverPath += new_count4;
serverPath += "&countgas=";
serverPath += new_countgas;
serverPath += "&countwater=";
serverPath += new_countwater;

or you can use some c++ magic:
template <class T> inline String & operator<<(String & out, T const & what) {
    out += what;
    return out;
}

String serverPath;
serverPath.reserve(100); // reserve space so it doesn't have to resize

serverPath << serverName << "?chip_id=" << chipId << "&count1="
           << new_count1 << "&count2=" << new_count2 << "&count3="
           << new_count3 << "&count4=" << new_count4 << "&countgas="
           << new_countgas << "&countwater=" << new_countwater;

this code takes serverPath << serverName adds serverName into serverPath and the result is serverPath again, and then it continues as serverPath << "?chip_id=" and so on

thank you it works with String(someFloat, 3)

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


text:
Control LED strip via serial monitor
I've been struggling with writing a code for Arduino UNO so that I could use my phone and change the colour of the LED strip via terminal.
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {

  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
    if (btSerial.available())
    {
      a= (char)btSerial.read();

      if(a=="b")
      {
        btSerial.println("Turning LED blue");
        leds[0] = CRGB::Blue; // Turns 1 LED to blue
        FastLED.show();
      }
    }
}

So basically I'd like to be able to change LED colours with my phone. If you enter "r", the LEDS turn red, if you enter "b", leds turn blue etc. Maybe even add some patterns. Brightness controller would be nice too to save some battery.
EDITED. Serial works.
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

void loop(){
    if (btSerial.available())
    Serial.write(btSerial.read());
    if (Serial.available())
    btSerial.write(Serial.read());}

3.
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

void loop(){
    if (btSerial.available())
    Serial.write(btSerial.read());
    if (Serial.available())
    btSerial.write(Serial.read());}

    if (a=='b'){
      btSerial.println("Turning LED blue");
      leds[0] = CRGB::Blue;
      FastLED.show();}

RECENT:
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 28
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
  if (btSerial.available())
  {
    a= (char)btSerial.read();

    if( a == 'b' )
    {
      btSerial.println("Sinine"); //All LEDs are blue
      fill_solid( leds, NUM_LEDS, CRGB::Blue);
      FastLED.show();
    }

    if( a == 'r' )
    {
      btSerial.println("Punane"); //All LEDs are red
      fill_solid( leds, NUM_LEDS, CRGB::Green);
      FastLED.show();
    }

    if( a == 'g' )
    {
      btSerial.println("Roheline"); //All LEDs are green
      fill_solid( leds, NUM_LEDS, CRGB::Red);
      FastLED.show();
    }

    if( a == 'y' )
    {
      btSerial.println("Sinine"); //All LEDs are yellow
      fill_solid( leds, NUM_LEDS, CRGB::Yellow);
      FastLED.show();
    }

    if( a == 'w' )
    {
      btSerial.println("Sinine"); //All LEDs are white
      fill_solid( leds, NUM_LEDS, CRGB::White);
      FastLED.show();
    }

    if( a == 'o' )
    {
      btSerial.println("Väljas"); //All LEDs are turned off
      fill_solid( leds, NUM_LEDS, CRGB::Black);
      FastLED.show();}

    if ( a == 'z' ) //1 blue LED from start to finish
    {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Blue;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
    }

     if ( a == 'x' ) //1 red LED from start to finish
     {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Green;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
     }
  }
}

And what exactly is your question? Your code doesn't include much Serial stuff. Do you want to know, how to read from Serial? Then have you looked at the bunch of tutorials inside the Arduino IDE or on the web? Or do you have problems with the LEDs? Then, have you tried to use and understand the examples, that come with the FastLED library? Currently it is unclear, what exactly your problem is

You still didn't ask a real question, so we don't know, what the problem with your code is. Btw: You might want to try and replace the double quotes in your if statement by single quotes, since here you want to compare single characters (which are represented by single quotes around a single character) and not string literals (which are represented by double quotes around multiple characters).

I need to get the serial read working, right now it gives me nothing when I type on my phone.

I deleted some stuff and got serial working. Not sure like how I read what I type from the phone and then how I make them into if commands.

I can see the messages both ways. Not sure how to put that into code. "If this(specific text, for example "r" gets typed into serial via phone then leds change color to red)".

That depends on your needs. For very simple commands 1 byte/character is sufficient and your first code was a pretty good start for that. If you need more complex commands, you can look at the SerialEvent example in the Arduino IDE. It uses the newline character as message delimiter.

Updated code. How would you define that "a" as what gets typed into serial? Right now the code doesn't know what "a" is.

you ready have that in the first sketch .... btw, don't use variable names such as a because that is not a descriptive name .... use something like btData or btChar or btCmd or command etc.

You seem to lack the basic understanding, how Serial (UART) communication works. So I will explain the basic principles. From there you should be able to implement, what you want.
Serial (aka UART) transmits the data serially, byte after byte (thus it's name). When you type in a text in the Serial Monitor of the Arduino IDE and send it, you have no influence, when exactly each byte will be transmitted. As the UART interface doesn't know messages or "chunks of data", only bytes, it will transmit each byte, when it is ready. There might be a short pause inbetween the bytes. This is an important fact to know, if you want to implement commands longer than 1 byte.
The normal Serial interface is mostly implemented in the Uno's hardware, thus it doesn't depend on the running software that much. SoftwareSerial does all the hard communication work in software, thus it comes with some caveats (blocking write operations, more limited baudrate, only possible to receive on one SoftwareSerial interface at once, ...). But both mostly share the same code interface.
Serial.available() returns the number of received bytes, that are still in the internal buffer. You are already using this to only read from the buffer, when there is actually data to read in it (with the if statement). Then you read one byte from the buffer by Serial.read(). Currently you are giving the return value (the read data) directly to the other serial interface for sending. Thus the value is not saved anywhere in your sketch. Doing a Serial.read() will remove the read byte from the buffer and return it. Thus the read byte will no longer be in the buffer.
The code with the 2 if statements and serial functions is mostly used to forward the data between the two serial interfaces. For your use case you don't need this. Instead you should read the data into a local variable like you did in your first sketch:
if (btSerial.available())
{
  a= (char)btSerial.read();

  if(a=="b")
  {
    btSerial.println("Turning LED blue");
    leds[0] = CRGB::Blue; // Turns 1 LED to blue
    FastLED.show();
  }
}

Here you are first checking, if there is data to read in the btSerial buffer. If yes, you read it into the variable a. This variable now holds a single character. If you also want to forward this character to Serial, you can now use Serial.write(a); to do so. Then you want to check the value of the received character. Here we are doing a little excourse:

In C/C++ 2 different kinds of quotes are used: The double quotes " and the single quotes '. Double quotes mark string literals, which consists of a series of characters. Single quotes mark single character values - only one character. In your if statement you check for equality. If you think about it, you see, that checking if 2 single characters are equals is a lot easier, than checking if two strings are equal (checking 1 character on each side versus checking multiple characters on each side). Thus it is a difference, if you compare string literals or single characters. Comparing a single character variable with a string literal doesn't work - they are two completely different things. Instead you should compare the character variable to a single character:
if( a == 'b' )

As you are adding more commands for your project, you will see, that if statements don't order the code very good. In this case a switch statement is better:
switch(a){
    case 'b':
        // Doing what you want to do with the LEDs here
        break;
    case 'c':
        ...
        break;
}

This will execute the corresponding code part depending on the value of a. You can read more about this construct on the web (google something like "C switch").

Now you should be able to implement simple 1 byte/character commands in your code. Also review and understand the examples from the Arduino IDE about Serial.
If you need more complex commands (maybe with some payload data in addition to the command), you have to introduce a communication protocol onto the Serial interface. The simplest way is to define whole messages by using a delimiter character at the end of every message. Mostly the newline '\n' character is used for this purpose. You basically read the data from Serial and save it on a char-array/string until you received the newline character. Then you know, that you have received a complete message, and you can start to process it as a whole. When finished, you clear your message buffer and again wait for a new message. For this to work, you of course have to ensure, that the delimiter character is never part of your send data (as the code would think, that it marks the end of the message).
You can see this in the SerialEvent example in the Arduino IDE. Try to understand, what happens there. There are also many tutorials on the web.
I hope, I could enlighten you a bit. Good luck with your project.

Thank you so much Chris! Got it to work. Now currently working on different patterns and making a phone app. Got basic colours working.

If you think, that my answer was correct, you can mark it as tze correct answer. That way others know, that this question is solved. Thanks

Edited the code. So I can control the normal colours via phone app now which I made myself. Now I'm having difficulties creating more interesting patterns. I managed to make a while loop inside void loop() but the loop is not going to end. Got suggested to add another loop into while loop but not sure how that should look. Decided not to use switch statement since currently everything is working fine (unless it's needed to make the other patterns to work). Cheers, really appreciate the help so far.

Deleted the rows "int i= 2;" and "while (i > 0)", replaced it with "while (!btSerial.available())", it's working perfectly now. :)

So when I send anything to serial it stops the while loop.


text:
Arduino AT not working (Arduino UNO and HC-06)
Recently had issues with HC-06 AND Arduino UNO. Turned out that the last module was not working, this module keeps flashing and it appeared in the Bluetooth list.
I'm trying to work with some AT commands but for some reason this doesn't work. This module is brand new (ZS-040).

#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 3); // RX, TX
/*
 * Connect pin 2 Arduino to pin TX HC-06
 * Connect pin 3 Arduino to pin RX HC-06
 */
void setup() {

Serial.begin(9600);

Serial.println("Enter AT commands:");

btSerial.begin(9600);

}

void loop()

{

if (btSerial.available())

Serial.write(btSerial.read());

if (Serial.available())

btSerial.write(Serial.read());

}

I uploaded the code, went into Serial Monitor. When I type a command, I get no reply. I opened "Arduino Bluetooth" app,connected to my phone and when I type something in the terminal on my phone I see the text on my PC's Serial Monitor screen.
Any ideas what I should do next? Could it be something to do with the RX pin? Should I use voltage divider? I have 1k and 2k Ohm resistors, how should I connect them if that's the solution?

you did not say what happens if you type in the serial monitor after sending data from the phone to the serial monitor

https://i.imgur.com/cGkbeFz.gifv I can send data from the phone but not in the PC. I also got this reply from another platform but still not sure what I should do next. I need instructions, I'm new to all of this. Thanks.

the other reply: https://i.imgur.com/KLACLDD.png

Tried changing bt modules baud rate, that didn't work

SOLVED: Read this guide (http://chenthedesignmaker.com/how-to-use-hc-06-bluetooth-module-to-enable-communication-between-arduino-and-android-hc-06-zs-040-at-commands-texting-and-led-examples/), tried changing "No line ending" to "Both NL & CR". Now when I type AT command I get the reply OK and when I type on my phone I see the text in serial monitor (PC).

Not sure why but for example for changing name I had to type AT+NAME:Newnamehere (with ":"), for password AT+PSWD:"Newpswdhere".

Use a macro like this to send AT commands:
 #include <SoftwareSerial.h>

 SoftwareSerial btSerial(2, 3); // RX, TX
 /*
  * Connect pin 2 Arduino to pin TX HC-06
  * Connect pin 3 Arduino to pin RX HC-06
  */
 void setup() {

 Serial.begin(9600);

 Serial.println("Enter AT commands:");

 btSerial.begin(9600);

 }

 void loop()

 {

 if (btSerial.available())

 Serial.write(btSerial.read());

 if (Serial.available())

 btSerial.write(Serial.read());
 delay(1000);
 //btSerial.print("AT+PIN4321");
 //btSerial.print("AT+NAMEAlibaba");
 //btSerial.print("AT+BAUD4");

 }

You may have another port set on the HC 06 instead of 9600, like I had.
If so, try this code with all the possible port numbers and changing something like the password, and everytime you run the code - go check if it worked, this way you will find in wich port number you have your module.

good luck


text:
Cancelling state of code before going to interrupt
Currently, I have two loops in my Arduino code.
Certain cases take me from loop 1 to loop 2
I also have an ISR
When my ISR condition is met the code is executed and part of the ISR code is supposed to go to loop 1. Which it does but...
Then I close the ISR accordingly, but the service routine goes back to loop 2.
Any ideas why?
I've been surfing the web for the past couple hours and haven't caught a wave..
Thanks all.
//Physical variables
int eStop = 3;         // the number of the input pin
int eStopLED = 9;       // the number of the output pin

int dispenseButton = 6;         // the number of the input pin
int dispenseLED = 8;       // the number of the output pin

// have 789 for colors and 3456 for input only 3 ND 6 NEEDS TO BE USED

int eStopZone = HIGH;      // the current eStopZone of the output pin
int eStopScan;           // the current eStopScan from the input pin
int eStopPrior = LOW;    // the eStopPrior eStopScan from the input pin

int dispenseZone = HIGH;      // the current eStopZone of the output pin
int dispenseScan;           // the current eStopScan from the input pin
int dispensePrior = LOW;    // the eStopPrior eStopScan from the input pin

//Other Variables
volatile int vControl = 0;
int eVar;
int i; //Normal counting integer

// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void control(void);
void emergency(void);
//another coid for char ring

void setup()
{
  pinMode(eStop, INPUT);
  pinMode(eStopLED, OUTPUT);

  pinMode(dispenseButton, INPUT);
  pinMode(dispenseLED, OUTPUT);
  eVar = 0;
  Serial.begin(9600);  //Start Serial
  attachInterrupt(digitalPinToInterrupt(eStop), emergency, CHANGE);
}

void loop()
{
  eStopScan = digitalRead(eStop);
  dispenseScan = digitalRead(dispenseButton);
  //Serial.println(eStopScan);
  /*if (eStopScan == HIGH && eStopPrior == LOW && millis() - time > debounce) { //eStop control conditions
    switch (eVar) {
      case 0:
        vControl = 0;
        control();
        break;

      case 1:
        vControl = 1;
        control();
        break;
    }
    time = millis();
    }
  */

  if (dispenseScan == HIGH && dispensePrior == LOW && millis() - time > debounce) { //dispense control conditions
    Serial.println("in this loop");
    switch (eVar) {
      case 0:
        vControl = 2;
        control();
        break;

      case 1:
        vControl = 3;
        control();
        break;
    }
    time = millis();
  }

  eStopPrior = eStopScan;
  dispensePrior = dispenseScan;
}

void control () {

  switch (vControl) {
    case 0: //estop case put in another variable for showing last estop state
      eStopZone = HIGH;
      dispenseZone = LOW;
      digitalWrite(dispenseLED, dispenseZone);
      digitalWrite(eStopLED, eStopZone);
      eStopScan = LOW;
      dispenseScan = LOW;
      Serial.println("Case 0");
      //eVar = 1;
      break;

    case 1:
      for (int i = 0; i <= 2; i++) {
        eStopZone = LOW;
        digitalWrite(eStopLED, eStopZone);
        delay(345);
        eStopZone = HIGH;
        digitalWrite(eStopLED, eStopZone);
        delay(345);
        Serial.println("Case 1");
        //Serial.println(i);
      }
      break;

    case 2:
      dispenseZone = HIGH;
      eStopZone = HIGH;
      digitalWrite(eStopLED, eStopZone);
      digitalWrite(dispenseLED, dispenseZone);
      Serial.println("here 1");
      delay(1000);
      Serial.println("here?");
      eStopZone = LOW;
      digitalWrite(eStopLED, eStopZone);
      Serial.println("Case 2");
      break;

    case 3:
      dispenseZone = HIGH;
      eStopZone = LOW;
      digitalWrite(eStopLED, eStopZone);
      digitalWrite(dispenseLED, dispenseZone);
      eVar = 0;
      Serial.println("Case 3");
      // make led go green
      break;
  }
  time = millis();
  loop();
}

void emergency () {
  Serial.println("interrupt");
  vControl = 0;
  control();
}

Com window from debugging
in this loop
here 1
here?
Case 2
in this loop
here 1
here?
Case 2
in this loop
here 1
interrupt
interrupt
interrupt
here?
Case 2

Please show us the sketch you're using.

please explain what you understand about an interrupt and about ISR

It is difficult to understand, what you actually mean. Please include your code and a detailed description about what you expected the code to do and what it actually does.

My understanding is that the ISR will get completed and then go back to the state where it left off. However, I thought since im saying to go back into the loop where my variable is now changed it would nullify the previous case..

Your explanation of what you expect to happen is not very clear but I'll take a stab at your question.
First thing - Interrupt Service Routines (ISR) need to be short (execution time, not necessarily code length). Do the minimum necessary to save whatever status or data caused the interrupt and exit. Let the background (your main sketch) handle any further processing resulting from the interrupt.
That means the ISR has to leave some indication - a boolean flag, f/ex - that it did something, and your background has to check that frequently, act on it when it changes, and reset it for the next interrupt.
It looks like your ISR is calling into your background code, which effectively becomes part of the ISR, runs at interrupt level, prevents further interrupts while it is doing so, and (possibly) returns to your background code at a place or in a state that is no longer relevant by then.
Think about organizing your code so that the background does whatever ongoing, routine tasks you need it to be doing, but checking frequently for whether an interrupt has occurred yet. When one has, do whatever needs to done to handle it, reset the "interrupt has occurred" flag, and return to your background task(s).

I cannot see what actually goes wrong, but you're calling way too much stuff in your ISR. You're changing non-volatile variables with the control() call in your ISR, leading to undefined behaviour: You don't know when the ISR is being called, especially not whether it is called before or after the non-volatile variables have been transferred from memory to the registers or back in the routine started from loop(). Also: Never output anything from an ISR nor from code you call from that ISR. Serial communication is slooow (compared to what the processor could be doing in that time frame).
I'd say: The only thing your ISR should do is to add 1 to a volatile variable, then end. In your loop(), check whether that volatile variable is greater than 0, then reset the volatile variable back to 0 and run what you've got in your current ISR. To react to the interrupt in a timely manner, this also means that you should not use delay() anywhere in your code. This would put your code back into defined behaviour, at least.


text:
avrdude fuse error when programming ATMEGA328 without crystal
I built several boards with an ATMEGA328 and no crystal a couple of years ago. I programmed them successfully with a bootloader using usbasp, and with a sketch using the Arduino serial interface. I have now made some more, but I get an error message from AVRDUDE when I try to burn the bootloader:

***failed;
avrdude: WARNING: invalid value for unused bits in fuse "efuse", should be set to 1 according to datasheet
This behaviour is deprecated and will result in an error in future version
You probably want to use 0xfd instead of 0x05 (double check with your datasheet first).

I followed the instructions here and I am using the hardware configuration archive referenced on that page: breadboard-1-6-x.zip.
If I reprogram the bootloader on a device that does have a crystal, it works if I select Arduino Pro/Pro Mini (3.3V, 8MHz), but fails with the message above if I select the breadboard specified in the boards.txt from  breadboard-1-6-x.zip.
There are no other error messages, but... if I turn on verbose, it works.. turn verbose off and it stops working again. Maybe verbose mode modifies the timing enough to make it work.
I know that you can use the -B option to slow down avrdude when you run it from the command line: is there a way of doing the same thing from within the Arduino environment?

The above message is simply a warning, not an error.  I believe there is some other error showing earlier in your console that you have not shown.  Please check for that.

@jwh20 I did some more tests, and have added the results to my question.

Just FYI and in case you don't know it already: there's a very useful tool here: https://www.engbedded.com/fusecalc/

The ATMega328P datasheet has the following table in it:

The top 5 bits of the of the Extended Fuse Byte are default 1 and are reserved.  You're not really supposed to change them, since they might be used in the future for a 328P-like part and setting them to something other than 1 could have unexpected results.  In the 328PB variant bit number 3 is used for "Disable Clock Failure Detection".
The lower three bits of 0xFD and 0x05 are both 0b101.  In other words, taking into account only the bits you should be setting, for the BODLEVELn fuses, they would have the same effect.  But you are being WARNED that you should be using 0xFD rather than 0x05 for the above reason.
The boards.txt that comes in the breadboard-1-6-x.zip has a line that looks like this:

atmega328bb.bootloader.extended_fuses=0x05

You could change this yourself by editing the file, but really for what you're doing I'd recommend MCUdude MiniCore which is comparatively up to date.  If nothing else, its boards.txt file has been written with the correct fuse values.  You can see there for a plain 328P (not PB) which does not support clock failure detection, the CFD bit is just hardcoded to 1 in the file.
The message you're seeing is a "WARNING" through, rather than "ERROR".  The distinction being that warnings don't actually stop you from continuing.  It is likely that if you're having a problem isn't not really because they've incorrectly specified the high-order bits of the fuse.  If it's halting, it may be arduino-builder see a non-zero exit code for avrdude and thinking this means "ERROR" rather than "WARNING", in which case this problem will go away if you edit the boards.txt file (or adopt MiniCore) such that no longer produces the warning.
Unless you've brought the effective system clock below 1MHz, probably lower still, it's not likely that you'll need to change from the default ISP clock rate.  If you do though, that can also be done by editing board package files.


text:
Using digital rotary encoders for HID input using the Joystick library
I have been working on a small switch panel for flight sims, but I wanted to use  the CYT1100 Digital Rotary encoders to move instruments in-game. I have the code  set up to press a certain joystick button for each pulse. The code seems to work fine, but I might have some issues with hardware.
Components:

Arduino Micro
CYT1100 Digital Rotary Encoders
Acer Aspire E5 (Windows 10)

I get serial monitor outputs when I move the board, but the rotary encoders aren't plugged in. The values are around 2 to -2 but don't change depending on the encoders. The joystick buttons are getting almost randomly pressed with no certain pattern. I was wondering if anyone has had issues like this in the past or if I'm missing something.
Here's my code:
#include <Joystick.h>

#define outputA 2
#define outputB 3

int counter = 0;
int aState;
int aLastState;

void setup() {
  Joystick.begin();
  pinMode(2, INPUT);
  pinMode(3, INPUT);
}

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState) {
    if (digitalRead(outputB) != aState) {      // Clockwise
      Joystick.pressButton(1);
      delay(10);
      Joystick.releaseButton(1);
      counter ++;
    } else {                   // Counterclockwise
      Joystick.pressButton(2);
      delay(10);
      Joystick.releaseButton(2);
      counter --;
    }
    Serial.print("Counter:  ");
    Serial.println(counter);
  }
  aLastState = aState;
}

you have it partially backward ... wait for a transition in outputA in one direction only, either a rising edge or falling edge, but not both ... when transition occurs, read value of outputB and press joystick button depending on the value

Sorry I'm sort of new to C++ but not programming in general, so I the logic. I wait for a change in outputA, and directly after, if outputB is not down, I have a falling edge and vice versa?

no ... the rotary encoder probably has two outputs that are 90 degrees apart  ... read the state of B everytime A changes from LOW to HIGH .... A always changes in middle of B ... http://www.bristolwatch.com/ele2/img/Encoder.jpg ........ it has nothing to do with C++

Okay thanks! I'll try that and it should fix some issues.

I updated the code... Does that look about right?

definitely not ... the code does not check for a transition in the signal ... your previous code did ... it acted on both transitions instead of only one


text:
Setup loops: never enters loop - restarting?
I uploaded the following to my UNO with WiFi:
#include <SPI.h>
#include <Wire.h>
#include "Adafruit_CCS811.h"

Adafruit_CCS811 ccs; // The air quality sensor

String Dataline = "";

void setup() {
  Wire.begin();

  Serial.begin(115200);
  Serial.println("SET UP");
}

void loop() {
  // wait a second between measurements.
  delay(1000);

  Dataline = "";
  Dataline = Dataline + getTime();
  Dataline = Dataline + AIRSensor();
  Dataline = Dataline + "...";
  Serial.println(Dataline);
}

String getTime() {
  String OUT = "Tim::";
  OUT += String(millis());
  return OUT;
}

String AIRSensor() {
  if (ccs.available()) {
    if (!ccs.readData()) {
      float temp = ccs.calculateTemperature();
      String CO2 = (String)ccs.geteCO2();
      return "CO2::" + CO2 +"TAQ::" + (String)temp;
    }
  } else {
    return "CO2::-999,TAQ::-999";
  }
}

The output is simply "SET UP" repeated:
SET UP
SET UP
SET UP
...

It never enters the loop or prints anything else out. Does this mean the UNO is resetting? How do I troubleshoot?

how do you know that it does not enter loop()? ... you have no code that confirms that

You can tell that something is going wrong between your println. Some advice in this case: eliminate the String entirely and replace the println with a series of print. This would let you narrow down which function is causing the problem. It also can save some memory, which is a nice bonus in embedded programming.
I suspect in this case the problem is your use of C-style casts to String in AIRSensor(). (String)whatever and String(whatever) do very different things, and the former is not something you want here, or something you should be using very often in C++ code.
The code in loop is running, but it is crashing and causing the hardware to reset. Since it is crashing before it reaches the first visible behavior in loop, it just looks like setup is running over and over.

Thanks! Changing from '(String)' to 'String()' made a massive difference.
It now runs for about 6 loops, and then stops for a while. In the IDE, I get a 'Error while setting serial port parameters: 115,200 N 8 1' message. It then restarts again.
Is there any way to stop that?

'twas an issue with me not using 'ccs.begin()'. Thank you for your help!!


text:
Nokia 5110 LCD display doesn't work
Here is my circuit (all resistors are 10 kΩ, to lower the voltage, although I did try it without them with the same result):

The pinout on my display is (pin 1-8): RST, CE, DC, DIN, CLK, VCC, LIGHT, GND.
And here is my code:
#include <Nokia_5110.h>
#define RST 6
#define CE 5
#define DC 4
#define DIN 3
#define CLK 2
Nokia_5110 lcd = Nokia_5110(RST, CE, DC, DIN, CLK);

void setup() {
  pinMode(2, OUTPUT); //CLK
  pinMode(3, OUTPUT); //DIN
  pinMode(4, OUTPUT); //DC
  pinMode(5, OUTPUT); //CE
  pinMode(6, OUTPUT); //RST
  lcd.setContrast(60);
  lcd.setCursor(5, 2);
  lcd.print("Test");
}

void loop(){}

Problem is: nothing happens. I can only control the backlight via the potentiometer, but there is no text on the display. Now, this is my first attempt on this display so I might have just done something wrong; if you find it please tell me.
I'm using Nokia_5110.h library (https://github.com/baghayi/Nokia_5110)

Maybe show your actual display with its pinout. You have RST identified as Arduino pin 6 going to header pin 1 on the display.  RST is in the middle of the header on the one display I have that is like this. So, either your wiring is very wrong, or possibly more likely there's just no way to know because your display doesn't have the same pinout as mine.

@timemage the pinout on my display is (pin 1-8): RST, CE, DC, DIN, CLK, VCC, LIGHT, GND

Turns out I have a second one that's closer to that pinout, at least if old old pictures are to be believed. I don't see where you called lcd.begin().

@timemage I was reverse engineering one of the example sketches (specifically, this one: https://github.com/baghayi/Nokia_5110/blob/master/examples/Basic/Basic.ino) from the guy who made the library that I am using and there was nothing like that. I also tried different other examples from the internet with other libraries and they had the same results

LOL. Alright, edit your question to show which library you're using, since you're not using the common one.

@timemage I'm using Nokia_5110.h library (https://github.com/baghayi/Nokia_5110)

As said, [edit] your answer. This is not a forum, please don't put important information in a comment. -- Why did you insert serial resistors?

Welcome! A labeled schematic even hand drawn would be much better than the frizzy picture you are displaying. It would show all the connections and pin numbers along with power and ground connections. 20 seconds with that will convey much more information then the frizzy thing will in 5 minutes.


text:
Using pyFirmata with a 360° servo; how do I stop it?
I am testing out pyFirmata. I have a 360° servo, and know how to change its direction, but I dont't know how to stop it.
What command, like servo.write(), would work to make it stop moving until prompted to move again?

loop through all possible values

The "angle" is the speed, so set it to the angle that means 'don't move' - i.e., the middle.

You'll need to check datasheets for your servos but a PWM value of 1500 microseconds would generally be near neutral / no rotation. Decreasing values less than this should generate increasing speed clockwise. Increasing values greater than neutral should generate increasing speed counter clockwise.
See https://arduino.stackexchange.com/a/88650/71575


text:
Communication between two ESP32s using WiFi
I have two ESP32s. One is acting as webserver and the other is acting as a client that will send a GET request to the server ESP32. Both of the ESP32s are connected to the same WiFi AP.
For sending the request I need to know the server address, but I don't want to enter it into the code manually.
Is there any way with which I can figure out the IP address of the server ESP32 using the other ESP32?

Have a look into mDNS. I think there are already libraries for this on the ESP32

isn't that for esp32 and web browser?

What do you mean by that? mDNS is a way to give your device a name without having a dedicated DNS server. That way you can set the name of each device on the device itself. The client can then refer to this name of the device.

@chrisl In may case client is another esp32.

The other ESP32 also only does web requests, just like a webbrowser. mDNS just helps you to get the current IP address to the predefined name. Lets say Esp1 calls itself service1 and anounces that name through mDNS. Then Esp2 can ask mDNS for the IP address of service1 and then make a web request to that address. There should be examples and tutorials available online


text:
Blink LED without delay with stepper motor
Based on a previous question I modified the script to use blink without delay.
Unfortunately, it does not work, any idea why?
I am using SparkFun RedBoard Plus, Qwiic LED Stick - APA102C, Adafruit Stepper motor - NEMA-17 size - 200 steps/rev and Adafruit Motor Shield V2.
Modified code (based on @Michel Keijzers, see below):
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "Qwiic_LED_Stick.h" // Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_LED_Stick

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 500;           // interval at which to blink (milliseconds)

LED LEDStick; //Create an object of the LED class

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup() {
  Wire.begin();
  Serial.begin(115200);
  while (!Serial);
  Serial.println("Stepper test!");

  if (!AFMS.begin()) {
    // if (!AFMS.begin(1000)) {
    Serial.println("Could not find Motor Shield. Check wiring.");
    while (1);
  }
  Serial.println("Motor Shield found.");
  myMotor->setSpeed(50);  // 50 rpm

  //Start up communication with the LED Stick
  if (!LEDStick.begin())  {
    Serial.println("Qwiic LED Stick failed to begin. Please check wiring and try again!");
    while (1);
  }

  Serial.println("Qwiic LED Stick ready!");
//  LEDStick.setLEDColor(255, 0, 0);
  LEDStick.setLEDBrightness(1);
}

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    ledState = !ledState;
    // set the LED with the ledState of the variable:
    uint8_t intensity = ledState == HIGH ? 255 : 0;
    LEDStick.setLEDColor(intensity, intensity, intensity);
  }

  Serial.println("Single coil steps");
  myMotor->step(200, FORWARD, SINGLE);
}

Code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "Qwiic_LED_Stick.h" // Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_LED_Stick

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

LED LEDStick; //Create an object of the LED class
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup() {
  Wire.begin();
  Serial.begin(115200);
  while (!Serial);
  Serial.println("Stepper test!");

  if (!AFMS.begin()) {
    // if (!AFMS.begin(1000)) {
    Serial.println("Could not find Motor Shield. Check wiring.");
    while (1);
  }
  Serial.println("Motor Shield found.");
  myMotor->setSpeed(50);  // 50 rpm

  //Start up communication with the LED Stick
  if (LEDStick.begin() == false) {
    Serial.println("Qwiic LED Stick failed to begin. Please check wiring and try again!");
    while (1);
  }

  Serial.println("Qwiic LED Stick ready!");
}

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    LEDStick.setLEDColor(50, 50, 50);
  }

  Serial.println("Single coil steps");
  myMotor->step(200, FORWARD, SINGLE);
}

it does not work is a useless description of a problem ... what actually happens?

It does not blink properly

that is just as cryptic ... what were you expecting to happen? ... what actually happened?

You only set (assign) ledState, but you never use it.
I think the following fragment
// set the LED with the ledState of the variable:
LEDStick.setLEDColor(50, 50, 50);

Should be something like:
// set the LED with the ledState of the variable:
uint8_t intensity = ledState == HIGH ? 255 : 0;
LEDStick.setLEDColor(intensity, intensity, intensity);

This 'converts' the ledState into white (RGB values 255) when HIGH or black/off (RGB values 0) when LOW.
Also you can change the line
if (LEDStick.begin() == false) {

into
if (!LEDStick.begin()) {

and change the lines
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
  ledState = HIGH;
} else {
  ledState = LOW;
}

into
// if the LED is off turn it on and vice-versa:
ledState = ledState == LOW ? HIGH : LOW;

or even
ledState = !ledState;

Thanks a lot. I did the modified code and updated it in the question, it seems to blink but longer than 1sec. Can it be related to the board frequency. How can I control different light colors based on this code: uint8_t intensity = ledState == HIGH ? 255 : 0;
LEDStick.setLEDColor(intensity, intensity, intensity);

Please upvote and accept the answer if it helped and is the solution for your problem.  I don't see directly why it blinks longer than 1 sec, you can print out variables to find out the exact times. About the colors, you can transform LOW/HIGH into any value between 0 and 255 for both red, green and blue, just play a bit with the arguments inside the LEDStick.setLEDColor statement.


text:
Set control register to low in ds3231 rtc
I have been using ds3231 rtc module for keep tracking and make alarm along with backup battery. when I used it for first time it worked fine. but now it doesn't keep track my time when the power lose it from main power but I have checked that my battrey is in safe. So I search in lot of forums they said EOSC bit was set high that would be stoped the clock as it stops the internal oscillator. also want to set it into low then only rtc keep track of the time
but in another some forums they instructed that put this following code for set it to low
DS3231 RTC;

  Wire.beginTransmission(0x68);
  Wire.write(0xF);                            // Address the Status register
  Wire.write(0x00);                           //  Zero the Status register
  Wire.endTransmission();
  Wire.beginTransmission(0x68);
  Wire.write(0xE);                            // Address the Status register
  Wire.write(0x00);                           //  Zero the Status register
  Wire.endTransmission();

  RTC.setA2Time( ADay, AHour, AMin, 0x00, true, false, false);
  delay(100);
  RTC.turnOnAlarm( 2 );

in another place showed the following code
// clear /EOSC bit to ensure that the clock runs on battery power
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x0E); // select register
  Wire.write(0b00011100); // write register bitmap, bit 7 is /EOSC
  Wire.endTransmission();

but now problem is that where should I want to place this code and how  to past it in proper manner for keep tracking the time when ds3231 loses power too? please any know about this problem because I finded so many people are strugling with this issue when they come forward to use this ds3231 rtc module. if any body know about how to solve this issue plese consider to share your idea this will definately help full for evryone because there is no one properly answer for this issue

I would recommend you to go with this (RTClib) library to test your module. If it works fine than you can look in related function to check how things are working there and by that way you can fix your code.

To understand the DS3231 register structure you have to look here on page 11 https://www.analog.com/media/en/technical-documentation/data-sheets/ds3231.pdf. The example code fragment you gave Wire.write(0xE); . . . Wire.write(0x00); sets the control  register (0Eh) to zero which enables the oscillator by unsetting bit /EOSC. However, I guess your problem is somewhere else because nothing should normally disable the oscillator once it is enabled.

Which library are you using for the DS3231 and to set the alarms? It is so that the same DS3231 register which controls the oscillator (0x11) also controls the alarm interrupts. If the library is carelessly written, it could, as a side effect, disable the oscillator when changing the alarm configuration. Adding code to enable the oscillator may not help much unless you can guarantee to run it the moment the oscillator is disabled and would, anyway, only be a work around..

From the DS3231 data sheet:
Control Register (0Eh)
Bit 7: Enable Oscillator (EOSC). When set to logic 0, the oscillator is started. When set to logic 1, the oscillator is stopped when the DS3231 switches to VBAT. This bit is clear (logic 0) when power is first applied. When the DS3231 is powered by VCC, the oscillator is always on regardless of the status of the EOSC bit. When EOSC is disabled, all register data is static.
Status Register (0Fh)
Bit 7: Oscillator Stop Flag (OSF). A logic 1 in this bit indicates that the oscillator either is stopped or was stopped for some period and may be used to judge the validity of the timekeeping data. This bit is set to logic 1 any time that the oscillator stops. The following are examples of conditions that can cause the OSF bit to be set:

The first time power is applied.
The voltages present on both VCC and VBAT are insufficient to support oscillation.
The EOSC bit is turned off in battery-backed mode.
External influences on the crystal (i.e., noise, leakage,etc.).
This bit remains at logic 1 until written to logic 0.

I dug out an old D3231 board. It had a battery in it but was last set ~3 years ago and I am not sure how old the battery was when I first put it in the board. The battery cannot keep the clock running. When I attached it to an Arduino UNO and booted up, the clock’s registers read as follows (just pay attention to the time and the EOSC bit and the OSF flag):
CLOCK: 00:01:15 (24h clock) Sunday, 01/01/2000  Temperature=21C  Aging offset=0
Alarm #1: 00:00:00 (24h clock) DY/DT=18[DoM mode]   Alarm selection: when date, hours, minutes and seconds match
Alarm #2: 00:00 (24h clock) DY/DT=20[DoM mode]  Alarm selection: when date, hours, minutes match
CONTROL byte=00011100 /EOSC is ON /BBSQW is Disabled /CONV is clear /INTCN mode is Match /Alarm 1 is Disabled /Alarm 2 is Disabled
STATUS byte=10000000 /OSF is ON /EN32KHZ Disabled /BSY is OFF /A1F is OFF /A2F is OFF
The clock is now running because with VCC supplied by the Arduino, the oscillator will always run. When I read the clock, I can see the time advancing, but it started from 00:00:00
Now, I remove power and after a minute or so, power up the UNO and the clock, and read the clock. It is again running, but the time had not advanced – it simply restarted from 00:00:00. EOSC is ON. OSF is ON.
With no VBAT, the time was not preserved.
A fresh battery is inserted and I power up. The clock is again running, again, restarted at 00:00:00. EOSC is ON. OSF is ON.
After a couple of minutes, I power down (with the fresh battery still in the clock). When I boot up and read the clock, it is running AND it kept running on battery power, so the current time is accurate. EOSC is ON. OSF is ON.
EOSC was always enabled (read as 0) – that is the POR value. Unless your program explicitly sets the bit to 1, EOSC will reliably be enabled. If you do disable EOSC (set to 1), the oscillator will NOT run off of the battery backup (VCC off and VBAT on). With EOSC disabled, and if there is enough juice in the battery, it will hold the time (and other registers) when VCC is switched off and VBAT is on. When VCC is on, the oscillator will always run.
But, what about the OSF flag?
Reading the data sheet, you can see that the OSF flag gets set when the oscillator stops, which can occur from a number of conditions.
It is designed so that the software can legitimately suspect that the time is not accurate, But, OSF is set as the POR value.
You need to enable EOSC AND CLEAR OSF, every time you do a clean power up and every time OSF got set because you unplugged (no VCC) and changed batteries. Also, remember, that with VCC, the oscillator will run regardless of the state of the EOSC bit.
Do not ignore OSF, it is an important flag and it should not be getting set regularly. In fact, once you insert a battery and clear OSF, it should not be set again until the battery drains. If it is getting set regularly, you have problems elsewhere.
Some software reads OSF and if it is set, the software will balk and tell you as much, as it should. Since OSF is set on POR, it will be set whenever you remove VCC and VBAT and then power up again.
You need to explicitly clear OSF AND know why it got set.
This code snippet, enables EOSC AND clears OSF.
 // enable EOSC and clear OSF flag
 // *** The other bits in these two registers are writtten
 // with POR Values or '0' if POR value=X.
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x0E); // select CONTROL register
  Wire.write(0b000011100); // write register (bit 7 is EOSC)
  Wire.endTransmission();
  Wire.beginTransmission(0x68);
  Wire.write(0x0F); // select STATUS register
  Wire.write(0b00001000); // write register (bit 7 is OSF)
  Wire.endTransmission();

Hope it helps.

I also have a DS3231 RTC in my robot project.  Here's my complete setup code.  This can be placed anywhere in setup():  I don't think you have to mess with individual registers to get what you want.
    if (rtc.begin()) //02/19/19 this now returns FALSE if RTC doesn't respond
    {
        Serial.println("Found RTC...");
        delay(100);
        bRTCLostPower = rtc.lostPower(); //added 10/17/18
        mySerial.printf("rtc.lostPower() reports %d\n", bRTCLostPower);

        if (rtc.lostPower())
        {
            Serial.println("RTC lost power.  Setting RTC to last compile time");
            rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
        }

#ifdef FORCE_RTC_TO_LAST_COMPILE_TIME
        Serial.println("Forcing RTC to last compile time");
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
#endif

        DateTime now = rtc.now();
        char buffer[100];
        memset(buffer, '\0', 100);
        mySerial.printf("Retrieving Date/Time from RTC with rtc.now() =  %ld\n", now.unixtime());
        GetDayDateTimeStringFromDateTime(now, buffer);
        Serial.print("Date/Time: "); Serial.println(buffer);
        RTC_Avail = true;
    }
    else
    {
        Serial.println("Couldn't find RTC. Real-time clock functions won't be available");
        RTC_Avail = false; //use this instead
    }

    if (RTC_Avail && rtc.lostPower())
    {
        DateTime Comp_dt = DateTime(F(__DATE__), F(__TIME__)); //__DATE__ & __TIME__ are environment variables)
        uint8_t mydayofweek = Comp_dt.dayOfTheWeek();  //returns 0 for Sunday, 6 for Saturday dayOfTheWeek
        int mymonth = Comp_dt.month();
        int myday = Comp_dt.day();
        int myyear = Comp_dt.year();
        int myhour = Comp_dt.hour();
        int mymin = Comp_dt.minute();
        int mysec = Comp_dt.second();
        long unixtime = Comp_dt.unixtime();
        char* dayofweek = (char*)daysOfTheWeek[mydayofweek];

        Serial.print("day of week value = "); Serial.println(mydayofweek);
        Serial.print("day of week value = "); Serial.println(Comp_dt.dayOfTheWeek());

        mySerial.printf("RTC lost power - setting to datetime of last compile %ld (%s %4d/%02d/%02d at %02d:%02d:%02d)\n",
            unixtime, dayofweek, myyear, mymonth, myday, myhour, mymin, mysec);

        rtc.adjust(Comp_dt);
    }

what do you mean by an individual register?


text:
Real Time clock module error-DS3231
This is not a code error I have been using DS3231 RTC module with battery. When I bought this module It worked perfectly now when I get it to use, The time is running perfectly. when I set the current time of my location, it has been running along with that time but the problem is when I unplug the power of my Arduino Nano and again when I give the power I can see the time is running from its start, I could not see any current time value my location but I have attached CR2032 battery along with DS3231 module? what is the problem with this? I changed another battery too but It shows same problem my DS32321 haven't kept the time when I unplug and re-plug the power
This is the code I'm using for set the time
#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)
  delay (1000);
}

This is the code I'm using to make Interrupt
 #include <DS3231.h>

int Relay = 4;

DS3231  rtc(SDA, SCL);
Time t;

const int OnHour = 21;
const int OnMin = 46;
const int OffHour = 21;
const int OffMin = 48;

const int On2Hour = 14;
const int On2Min = 54;
const int Off2Hour = 21;
const int Off2Min = 48;

void setup() {
  Serial.begin(115200);
  rtc.begin();
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);
}

void loop() {
  Serial.println("Time:  ");
  Serial.print(rtc.getTimeStr());
  Serial.print('\n');

  Serial.println("Date: ");
  Serial.print(rtc.getDateStr());
  Serial.print('\n');

  t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (1000);
  //can be set lcd display alspo
  if(t.hour == OnHour && t.min == OnMin){
    digitalWrite(Relay,HIGH);
    Serial.println("LIGHT ON");
    }

    else if(t.hour == OffHour && t.min == OffMin){
      digitalWrite(Relay,LOW);
      Serial.println("LIGHT OFF");
    }
  if(t.hour == On2Hour && t.min == On2Min){
    digitalWrite(Relay,HIGH);
    Serial.println("LIGHT ON");
    }

    else if(t.hour == Off2Hour && t.min == Off2Min){
      digitalWrite(Relay,LOW);
      Serial.println("LIGHT OFF");
    }
}

Can you please share your code and which library are you using

I'm using Ds3231 library

yeah now I have uploaded the code

I will take a SWAG as I do not know what module you are having problems. Remove the battery, power it up and measure the voltage at the battery terminals. If you have about 3.2V the module is designed to charge the battery (thought you might like to know). Power down the module insert the battery, do not power it up, and measure the battery voltage at the chip. Be sure to also check the ground side. I believe you will find the same thing I did, the solder connection to the battery holder was open, just added some solder and that solved it. I also found the SCL line was  broken on the board so if I connected the other side it would not work. I added a jumper to fix it. I purchased several from azon but only the first one was bad.

I am posting a code please try it may be it can help you
    #include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

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

#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
     rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
  }

  // When time needs to be re-set on a previously configured device, the
  // following line sets the RTC to the date & time this sketch was compiled
  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // This line sets the RTC with an explicit date & time, for example to set
  // January 21, 2014 at 3am you would call:
  // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.print("Temperature: ");
    Serial.print(rtc.getTemperature());
    Serial.println(" C");

    Serial.println();
    delay(3000);
}

Upload the above code and then upload the same code just comment the following part
if (rtc.lostPower()) {
        Serial.println("RTC lost power, let's set the time!");
        // When time needs to be set on a new device, or after a power loss, the
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
         rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
      }

This will work and even if you plug and unplug it from power the RTC time will not reset

is it ok with Arduino

No,  it's not working, It shows the same problem that I have been facing. I mean my RTC module ds3231 does not keep time when it loses it power. but  I have attached timekeeping battery along with that

The same above code was working for me have you checked the voltage of the battery and also have you uncommented the part of the code and uploaded it again?

yeah , your  code is working fine , I changed the new battery too, but the problems is when it loses it power it starts from 2000/0/1 and the time is starting with 00.00.01

Okay 2000/0/1 is the starting time of ds3231, have you checked the voltage using multimeter check the polarity of the battery also before inserting it in the module and can you please share the picture of your module and also how have you inserted the battery

yeah I have to check the voltage using multimeter but the battery is new one and I have attached the battery in a proper way. I could not send the image through this platform because it is a large file

If you send your email I cand send it through that

Attach it in your above post everyone can answer then even if I am unable to answer it

yeah I tried that but it contains a large file size

Upload it over here

Use any software to reduce the size (resolution / bit depth / compression).

ok here is my ds3231 image https://gofile.io/d/9IkuBr

Now I checked my rtc module it shows 3.3v across the ds3231 module but it doesn't keep the time

I don't have access to my hardware right now will get back once I have access to my hardware, have you commented the part of the code which I have mentioned in the above code and tried again just want to know all the possibilities

2020/10/19 (Monday) 10:14:5
since midnight 1/1/1970 = 1603102445s = 18554d
now + 7d + 30s: 2020/10/26 22:44:11
Temperature: 33.75 C
This was the output when I upload your code as per your instruction

⸮⸮:b⸮⸮⸮{⸮8k⸮⸮⸮⸮⸮⸮2000/1/1 (Saturday) 0:0:5
since midnight 1/1/1970 = 946684805s = 10957d
now + 7d + 30s: 2000/1/8 12:30:11
Temperature: 33.75 C
this is the output message when I unplug and re-plug the power of my Arduino

Posting a schematic not a frizzy picture, as how you have it wired showing all connections could eliminate a lot of the problems. Perfect software with the wrong hardware configuration will not work perfectly.


text:
I cannot communicate using RS232 between Arduino and Lakeshore Fluxmeter. How do I get data back from the fluxmeter?
I am using an Arduino Leonardo and the DFrobot RS232 shield to try and communicate with a flux meter. I am trying to write "UNITS?", which would have the fluxmeter send back a single byte that would translate to which units it is using.
The problem is, I can see from the Arduino side it is writing those 6 bytes, but at the if (Serial1.available()), there is nothing there. I have the switch on the shield to on, and I did the tutorial on the DFrobot wiki to make sure my shield works.
I think it has to do with how the Serial1.write() is done. I don't think it is receiving the command correctly, so it does not respond.
Shown below is my code:
#include <Keyboard.h>

// Define pins, so you only need to change them in one spot
#define BUTTON 7

bool runner = 0;

void setup() {
  // Begin Serial communication at 9600 baud rate
  Serial1.begin(9600);
  pinMode(BUTTON, INPUT);
  // create an interrupt that will call send_command() whenever the button pin has a rising edge
  attachInterrupt(digitalPinToInterrupt(BUTTON), send_command, RISING);
  // start the Keyboard process
  Keyboard.begin();
}

// called when button is clicked
// will use Serial.write() to send commands
// then will write the data with the keyboard
void send_command() {
  runner = 1;
  return;
}

void loop() {
  if (runner) {
    char pkneg, pkpos;
    // This next section writes the commands to the 480,
    // then reads the data and prints it to the Serial Monitor
    int sent = Serial1.write("UNITS?");
    Keyboard.println(sent);
    if (sent <= 0) {
      Keyboard.print("Fort Myers we got a problem\n");
    }
    //Keyboard.print(marker);
    delay(5000);

    if (Serial1.available()) {
      Keyboard.print("Here!\n");
      pkpos = Serial1.read();
  }
  else pkpos = 'x';
  pkneg = 'x';

  char pkneg1[10], pkpos1[10];
  // dtostrf(pkpos, 4, 3, pkpos1);
  // dtostrf(pkneg, 4, 3, pkneg1);

  Keyboard.print(pkneg);
  Keyboard.print('\t');
  Keyboard.print(pkpos);
  Keyboard.print('\n');

  // for testing

  runner =0;
  }
}

You are lacking the line terminators from your serial writing. As it says in the manual:

Terminators are fixed to CRLF.

And in the example code (the Quick Basic is probably the easiest to follow):
CMD$ = CMD$ + TERM$
PRINT #1, CMD$;

(where TERM$ is "\r\n").
So changing your Serial1.write to include the terminators should help the device to recognize that you have finished sending the command and it should respond to it:
Serial1.write("UNITS?\r\n");

By the way, testing the return value of the Serial1.write is pointless. It will always return the number of characters in the string you supplied - serial data over the UART pins is always sent even if there is nothing there to receive it.

thank you for your continued help! The terminators did not work at first, but then I tried writing like this: Serial1.write('U');   Serial1.write('N');   Serial1.write('I');   Serial1.write('T');   Serial1.write('S');   Serial1.write('?');   Serial1.write('\r');   Serial1.write('\n'); and that worked. Just trying to get READ? to work now, because what it returns is gibberish lol


text:
SdFat.h pin selection ESP8266
This super simple code, that saves data to a csv file, works perfectly fine on my Arduino Uno (I am using the default SPI pins).
However, for my project I need to use an ESP8266. Does the library automatically use the default SPI pins for any other boards?
In my code I have tried changing the CS pin from 10 to 15 for the ESP8266. All I get is "Initialization failed"! I figure, I need to somehow change the other SPI pins like MOSI, MISO and SCK. Is there a way to do this? I'm an absolute noob so sorry in advance if I oversaw some kind of easy fix.
#include <SdFat.h>

SdFat sd;
SdFile file;

void setup() {
  Serial.begin(9600);
  if (!sd.begin(10, SD_SCK_MHZ(50))) {
    Serial.println("Initialization failed!");
    return;
  }

  if (!file.open("data.csv", O_RDWR | O_CREAT | O_AT_END)) {
    Serial.println("Error opening file!");
    return;
  }

  file.println("Sensor1,Sensor2,Sensor3");
}

void loop() {
  float sensorReading1 = 1;
  float sensorReading2 = 1;
  float sensorReading3 = 1;

  file.print(sensorReading1);
  file.print(",");
  file.print(sensorReading2);
  file.print(",");
  file.println(sensorReading3);

  file.sync();

  delay(1000);
}

So I just tried again and somehow I happened to replace the SD_SCK_MHZ(50), that worked on my arduino Uno, with SPI_HALF_SPEED. Now the same code as above works perfectly fine on my esp8266.


text:
Arduino code giving error while compiling
I am a beginner, and I'm trying to make code to control a servo using two ultrasonic sensors.
I've tried to make the code, but when I tried to compile it using my simulation app, it gives this error:
sketch.ino: In function 'void value2()':
sketch.ino:123:19: error: expected ')' before '!' token
 if((L < R)>=6 & L !> normal){
                   ^
sketch.ino: In function 'void value3()':
sketch.ino:131:19: error: expected ')' before '!' token
 if ((R< L)>=6 & R !> normal){
                   ^

Error during build: exit status 1

How do I go about fixing this?
I'm using the Wokwi simulator website, and here is the link to the simulation.
Here is where the problem is in my code:
void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}

And here is my complete code:
#include <Servo.h>
#include <Stepper.h>
#define STEPS 100 // stepper steps
#define speed 30 // stepper speed
#define Lechopin 10 // ultrasonic sound sensor left
#define Ltrigpin 11 // ultrasonic sound sensor left
#define Rechopin 12 // ultrasonic sound sensor right
#define Rtrigpin 13 // ultrasonic sound sensor right
long Lduration;
long Ldistance;
long Rduration;
long Rdistance;
int  L;
int  R;
int dt1 = 100; //delay
int dt2 = 1;   //delay
int dt3 = 2;   //delay
int dt4 = 10;  //delay
int serv = 9;  //servo pin
Servo servo;
Stepper stepper(STEPS, 5, 6, 7, 8);
/* Assuming distance of 4 feet measured by sensor is between 100 to 1000, let's set 750 as the normal distance between
sensor and object in which will be anything in 4feet upward far
away from sensor won't be detected by the code. you can edit it with real time measurement, I just assume this */
int normal=750;
int minn=250;

void setup() {
  Serial.begin(9600);
  stepper.setSpeed(speed);
  servo.attach(serv);
  pinMode(Lechopin,INPUT);
  pinMode(Ltrigpin,OUTPUT);
  pinMode(Rechopin,INPUT);
  pinMode(Rtrigpin,OUTPUT);
}

void loop() {
  get_L_dist();
  L = get_L_dist();
  get_R_dist();
  R = get_R_dist();

  normalp();
  value1();
  value2();
  value3();

  //bailout;
}

//print sensors
/*
Serial.print("L is:");
Serial.println(L);
Serial.print("R is:");
Serial.println(R);
*/

/* read left sensor and calculate the distance */
long get_L_dist() {
  digitalWrite(Ltrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Ltrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Ltrigpin, LOW);
  Lduration=pulseIn(Lechopin, HIGH);
  Ldistance=Lduration / 58.2;
  return Ldistance;
}

/* read right sensor and calculate the distance */
long get_R_dist() {
  digitalWrite(Rtrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Rtrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Rtrigpin, LOW);
  Rduration=pulseIn(Rechopin, HIGH);
  Rdistance=Rduration / 58.2;
  return Rdistance;
}

//normal position of servo
void normalp() {
  if (L >= normal & R >= normal) {
    servo.write(90);
    //goto
    loop();
  }
}

void value1() {
  if ((L < minn) >= 2 & (R < minn) >= 2) {
    int ran = random(2);
    if (ran == 0) {
      servo.write(30);
      //goto
      loop();
    }
    if (ran == 1) {
      servo.write(150);
      //goto
      loop();
    }
  }
}

void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}

Use <= instead of !>. The latter is not proper C++ syntax.
Also, if (L < R) >= 6 probably doesn't do what you want. Did you mean if (L - R) >= 6 maybe?

It really can't do what they want. Because L < R in C++ will be either true or false, which will be considered 1 or 0 when when evaluated against >= 6. Taken as a whole (L < R) >= 6 is always false. They also probably wanted && rather than & although it may not exactly matter in this case. Ancient C didn't actually have && and used & this way. Still probably not a good idea.

Please put these helpful answers as actual answers and not comments on the question. Thank you,

If you answer in comments, then this question will show up a year later with "no answers" because you answered in the comments. And that just annoys everyone.

@timemage See above.

@NickGammon, the bot bumps only answered questions (which have an answer without vote). We usually don't answer syntax error questions so let's see if this one gets closed.

@NickGammon it may be helpful. I'm not sure it constitutes answer. If I thought it did, it would be an answer.

@NickGammon let me put it this way. If you take what I'd written and posted it as an "answer", I will vote it down. Because it is not an answer to the question. For thing it's describing code that compiles. It also does not having to do with that they should do; it represents no part of a solution. It is hopefully dispelling some idea about what they think code is going to do. Anyway, you guys need to figure out what you actually want people to do. At a minimum, it would be helpful if you weren't calling people out for things they're not doing. Thank you.

@Juraj It's unlikely to get closed now. I'm not going to fault the answerer for doing what a mod was asking them to do. Particularly now that it's an accepted answer. It at least does attempt to address the compilation issue. I don't think addressing them is such a bad thing, particularly if there's anything arduino-related about either the question on answer, and is based on something that isn't just a typo. Either way, it would help to know what is supposed to be done. Or again, at a minimum, not to be getting crap for it.

@timemage it would be helpful if you weren't calling people out for things they're not doing - this is a Q&A site. People ask questions. You are supposed to answer them in the answer box. Comments under questions are for clarifying the question (eg. "what sort of Arduino do you have"). Not putting your answer into an answer box is a pretty big thing. I think I can occasionally "call it out". Personally I thought what you wrote was very good, and it deserved to be in an answer box. Then, people can vote it up or down. And you get credit for making the answer.

I'd be very surprised if Juraj considers what I'd said an answer to the question. Either way, I don't care what you decide, but you and he and whoever else needs to figure out what is and isn't an answer and what is and isn't off topic. If everyone wants to define "answer" as anything that is "good" (or "helpful" as I said) irrespective of whether it actually answers the question that was asked, then I'm okay with that.

Use <= instead of !>; the latter is not proper C++ syntax.
Also, if (L < R) >= 6 doesn't do what you may think: (L < R) evaluates to true or false, so the whole expression will always evaluate to false. Did you mean if (L - R) >= 6 maybe?
Also, you use & as an "and" in your if statements, which should be &&.

Thanks a lot @ocrdu , I have modified it I use <= instead of !>, and I also changed ((L < minn)>= 2) to ((minn - L)>=2) and it is working on my simulation exactly as I need it to. Thanks to you all for helping me.


text:
USB Power switch
Can an Arduino power a USB device like a tablet from one of it's pins or do I need a relay? I want to essentially have the Arduino turn on and off a USB charger. Thanks

USB is 5V, not 3.3V. Also, no. 40mA is nowhere near enough for a typical USB device.

do not use an arduino as a power supply

Any advice on how to do this then? Thanks

use a mosfet instead of a relay; simpler, cheaper, lower power waste. google mosfet as a switch

If you already have a 5V source then you can use a MOSFET as a switch to turn on/off the power to the tablet like this:

But if you want to turn on/off a USB charger that goes to an AC outlet, then you will need to control a relay to turn on/off the AC supply to the USB charger. You can use a relay module like this: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE