text:
Programming Servo How To Get -90 Degrees
as the question title states, how will I go about turning the servo opposite of 90 degrees?
I have written my code as such;
  // Turn servo to the right
  if(x > 520 && y < 510 && y > 490){
  servo.write(0);
  delay(50);

  //Turn left
  }else if(x < 490 && y < 510 && y > 490){
    servo.write(180);
    delay(50);

 //Turn backwards
} else if(y < 490 && x < 520 && x > 490){
  servo.write(-90);
  delay(50);

Obviously -90 isn't an actual degree on the servo, and it will only turn between 0 and 180. I was therefore wondering if there was any other way to code it?
The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. Every other command works, and when I replace -90 with 90 degrees, it works as well. So it is wired correctly.
Of course I would have to add another joystick and another servo later on, but at this stage I am simply testing my own coding skills.

There is no such thing as -90°. Just change your concept of what is "straight ahead"...

It is unclear, how the joystick is connected to the servo and which movements you exactly need on the joystick.

@chrisl In reality I wish for the servo to mimic the joystick.
But since this is first time I am programming with servos and a joystick, I simply wish for a simple up, down, left, right, upper- left and right corner and then lower- right and left corner.
I am basing this on a system, where the directions depending on whether or not x and/or y are above or below the middle value of 510-ish. As you move the joystick from vertical left to right it will increase from 0 to 1320, and the same for horizontal down to up. The x and y variables in my program are based on those values.

See my edited answer. You need two servos to control a 2 axis joystick.

Normal servos only have a range of 180°. You can give yourself an "offset", so you have -90° to 90°, but you only ever get 180° range. You can't go -90° to 180°.
Using mechanics (outside the scope of this site) you can multiply your movement (think gears) so that your range is bigger.

This seems too advanced for me in terms of the mechanical aspect.
Would it possible to use a DC motor for the base and a function, that replicates the movement of the joystick? Or do you see any immediate problems with that?

You can get special servos with wider ranges, and you can get "continuous rotation" servos that go round and round, but you don't specify an angle with those, but a speed. If you want to use anything other than a "normal" servo you will need some form of feedback to know what angle you're facing.

Thank you, are these "wide range" servos called anything special? When I google "360 degree servo" I simply get ads for regular servos.

@GeorgeWTrump, I'd recommend a stepper motor. Also look into motors with quadrature encoders and index pulses. They can be used to set position. Any of the above can rotate continuously in either direction while still knowing it's angle from 0 to 360 deg or -180 to +180 or however you want to think about it. With the proper control algorithm and PID loop, you can also command exact position. This is more advanced, however.

You say "The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. "
That doesn't make sense. How could a joystick rotate 360° in one dimension and 180° in the other dimension?
A joystick does not need an angle greater than 180°. It's mounted to a flat surface, and can only move 180° in two different dimensions, X and Y. (And actually probably more like 120° in each dimension.)
Use two 180 degree servos, one for the X axis and one for the Y axis.
Set the "neutral" position to 0
You can map the range 0 - 1320  to -90 to 90 using a map statement. (or adjust as needed since the range of motion of the joystick is probably less than 180 degrees - more like 120°, like  chrisl said in their comment.)
See this article for info on how a 2-axis joystick works. Specifically look at the section titled "Gimbal Mechanism" a little ways down in the article.

I am not sure that I understand?
The joystick itself already moves 360 degrees? What I need to move 360 is the platform for the turret.
Of course, I could always move it counter to what it should be pointing at, and then move the tilting backwards (i.e 180 degrees ) but that seems awkward to me personally.
But mapping it -90 to 90, will still only result in 180 degrees. This means the target can simply just move behind the turret.

What type of joystick do you have? A normal joystick (like on the controllers of game consoles) rotate maybe 120 degrees on the x and the y axis. The axes are independent. So you would need 2 servos, each moving 120 degrees. Where is your joystick moving 360 degrees?

You don't want one 360° rotation. You want to tilt it on separate X and Y axes by ±90° each (actually probably more like ±60 degrees, as chrisl said in their comment.)

Oh, but I would have 2 joysticks.
One normal joystick with a normal code, that will output the normal range of 0-180 degrees on the tilt.
Meanwhile, the other joystick will have a seperate "x" and "y" axis. Of course, I could just use the y axis for all backwards facing degrees by "y = y-output + 180". So that if y = 1, it will be 181, and therefore backwards. And for the forward facing degrees (i.e 0-180) I can simply output the x-value.

Now that is my train of thought, does this change your suggestion? As I understand it, you believe that I am limited to a total range of 180 degrees (in actuality 120 degrees), is that why you suggest using only 180 degrees of motion? Or am I mistaken?

Why are there now 2 joysticks? It is totally, what exactly you are trying to do. Maybe you should draw schematic pictures, how everything is connected and where your 360 and 180 degrees are

If I understand correctly, you only need to move your servo through 180 degrees total, from one limit to the other, but you want -90 to represent one of the limits and +90 to represent the opposite limit? If so, just add 90 to the servo angle before you send it:
servo.write(angle+90);

This turns -90 into 0, 0 into 90, and 90 into 180. You get to use the coordinates that you like (-90 - +90) and the servo sees the coordinates it needs (0 - 180).
This is a simple case of mapping; there is a map() function that can do this for you for all mapping all kinds of ranges, one into another. Mapping (-90 - 90) into (0 - 180) is so straightforward that the map function really doesn't add anything, but in other cases it's handy to know about.


text:
Arduino-compatible wireless technology which can be suitable for transmitting data
Introduction
I've been meaning to build a vehicle using arduino components and LEGO. I have a mechanical clamp built with arduino which will be locked on top of a custom LEGO build (It should be made out of LEGO blocks and arduino sensors). In my mind, it resembles a crawler.
Question
I've been looking for a way of controlling it remotely.
I only have experience with IR controllers but I'm not sure if this technology would fit for my project.
What I'm looking for is a technology wich could transmit data to an Arduino board (thus, an emitter and a receiver component) which, in my case, could comfortably handle a veichle.
Plus, it should have a range of action of at least 5 meters (15 ft).
If such technology exists, do you know any controller which could do the job for me?

You can use radio transmitter/receivers, they are typically called RF (Radio Frequency) modules.
Typical examples are nRF24L01+ (2.4 GHz), or RF 315/433 modules (on 315/433 MHz).
There are more possibilities, but these are the most used on Arduino and libraries are available.

Thanks for your answer, do you happen to know where to find these modules?

You mean where to buy them? AliExpress, or if you want genuine products, try Mouser, Digikey

Try a pair of Wixels (https://www.pololu.com/product/1336).  A pair of Wixels (one at the PC, one on the crawler) act as a fast USB cable emulator.  The PC-connected Wixel shows up as a USB port, and the one on the crawler (with a Wixel sheild) emulates the Arduiono end of a USB cable.  These are very easy to use, and in addition to remote control will allow you to wirelessly program the Arduino controller.
The ability to remotely program the crawler is a real god-send, as now you don't have to retrieve the crawler and connect it to a hardware USB cable for programming.
Just my $0.02
Frank

source: Stack Exchange

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

sort: votes


text:
How to connect RedBearLab BLE shield (Or how to find Nordic_nRF8001.h)?
I am trying to explore the possibilities of connecting an Arduino to Phonegap/Cordova. I have a RedBearLab BLE Shield, which I want to test the connection with. My MVP would be to get the value of a PIN to a Cordova app. Nevertheless, I couldn't make it even close.
The closest I got, it was using Don Coleman's Phonegap plugin.
I am trying his Simple Chat example.
With this example the sketch is attempting to include Nordic_nRF8001.h. Nevertheless, I can't seem to find this library. I downloaded it from various sources, but no matter what I do, my sketch still can't find the file.
The only way I could make it work was via CodeBender, but then the readings were a bit of a mess.
I'm not expecting anyone to do all the work for me, so if you can help me in one of the two directions, it would be awesome:

Figure out why I can't find that Nordic_nRF8001.h file.
Or help me find another method of BLE communication.

Later edit
Using the examples that come with RBL library, I figured out the name of the files I need to use. Now I'm running into another problem for which I opened a new question.
Thank you!

I tried using the web editor. There I could find the SimpleChat example, with the correct names of the libraries. They work perfectly.

The scrambled characters issue was because of the wrong Baud Rate.

I used Arduino Create Web Editor to load the SimpleChat example. It loads with these libraries, and it works perfectly:
#include <SPI.h>
#include <EEPROM.h>
#include <boards.h>
#include <RBL_nRF8001.h>

Thanks,
Andi

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


text:
Stuck in While loop!
I am using 4 LDR To track the sun for solar panels. Not using servos, but linear actuators(a little irrelevant but just to give scope)
my code gets stuck in this while loop as soon as it enters it, even tho the conditions are changed to break the loop. I want to leave the motors running in one direction until the "dvert"=Vertical difference is less then "tol"=tolerance. there are 4 of these loops. there is an if condition before each. so no adjustment is made if its already in tolerance.
Segment of code
  if (avgtop > avgbot)
  {  Serial.println("enter avgtop > avgbot");
    Serial.println( "");

   while (abs(dvert) > tol)
     {
      Serial.println("Enter While loop vert up....");
      Serial.println("Moving Vertical Axis begin...Moving UP  ");

                   digitalWrite(vrelay1, HIGH);              // Setting frame down
                   digitalWrite(vrelay2, LOW);              // Setting frame down
      delay(200);
      int topl = analogRead(ldrtopl);
      int topr = analogRead(ldrtopr);
      int botl = analogRead(ldrbotl);
      int botr = analogRead(ldrbotr);
      int avgtop = (topl + topr) / 2; //average of top LDRs
      int avgbot = (botl + botr) / 2; //average of bottom LDRs
      int dvert = avgtop - avgbot; // check the diffirence of up and down

      Serial.print("NEW DVERT:"  );
      Serial.println(dvert);

  }  ```

don't use a while loop .... use an if block .... the loop() function in the sketch already loops

Unfortunately, for delay reasons, i need to use the while loop. I want the system to delay at the end of the big loop after everything is aligned

why do you need a delay? .... if you really need a delay, then do a delay only when there is no motor position to be updated .... that is simple to accomplish with the use of a flag variable

The delay will allow the system to sleep for a set time to allow the sun to move a reasonable distance before tracking again.

just do something like this pseudo code  if (go left) {runMotor(left); moving = true;} else {moving = false;} ... if (go right) {runMotor(right); moving = true;} .... if (!moving) { pause 10 seconds} else {pause 1 second}

Thanks might give it a try.

But still lost as to why the while loop wont terminate

Your output of dvert should show you why the loop does not terminate.

The output dvert is initially >tolerance, but value is changed to < tolerance but the loop keeps looping. Im lost.

"delay will allow the system to sleep" WRONG. delay rather only blocks the system, and is nice for quick and dirty demo code. As loop() loops, just let it loop without actions, if no action is required.

You're masking your outer dvert variable (and potentially others that you want to keep) with local variables inside the loop:
  int dvert = avgtop - avgbot; // check the diffirence of up and down

If you're just assigning a new value to an existing variable you do not want to declare a new variable!
Instead it should be just:
  dvert = avgtop - avgbot; // check the diffirence of up and down

And the same for anything else inside the loop that you want to assign to a variable that you have created outside the loop.

you are the man. It works now.I nearly started fro scratch, Thank you so much


text:
Im having another problem with my code the error is "redefinition of 'AF_DCMotor motor'?
Heres the code
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor(2, MOTOR12_8KHZ);
AF_DCMotor motor(3, MOTOR34_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.printIn("Motor Test!");
  motor1.setSpeed(15); //set speed of motor
  motor2.setSpeed(15); //set speed of motor
  motor3.setSpeed(15); //set speed of motor

}
void loop() {
  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(9000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor1.run(RELEASE);
  delay(20000);

  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song stops
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick"); //first song stops
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(19000);
}

Here is the error:
   ^~~~~~

   motor

snowmanDC_Motor:13:3: error: 'motor3' was not declared in this scope

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:13:3: note: suggested alternative: 'motor'

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

   motor

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino: In function 'void loop()':

snowmanDC_Motor:18:3: error: 'motor1' was not declared in this scope

   motor1.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:18:3: note: suggested alternative: 'motor'

   motor1.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:47:3: error: 'motor2' was not declared in this scope

   motor2.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:47:3: note: suggested alternative: 'motor'

   motor2.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:115:3: error: 'motor3' was not declared in this scope

   motor3.run(RELEASE);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:115:3: note: suggested alternative: 'motor'

   motor3.run(RELEASE);

   ^~~~~~

   motor

exit status 1
redefinition of 'AF_DCMotor motor'

Do you have V1 or V2 shield? They have different library.

@Tommy, you are still at it ... congratulations for not giving up .... I can tell you right now, you will have a long battle until you tell us what hardware you have and how you connected it

You consistently fail to use libraries that you have installed. Or you are sure you have installed. Instead of repeatedly throwing the same code at us with a different library you should instead take a step back and look more into how you are going about installing libraries and why, maybe, the IDE can't find them.  https://www.arduino.cc/en/guide/libraries

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

Adafruit has a V1 and a V2 motor shield. They have different libraries too. AFMotor.h is for the V1 shield. From the error, I can tell you installed V2 lib. For that you need to include:
#include <Adafruit_MotorShield.h>

I needed to install the Adafruit v1 library Thanks for the help tho, Im new to all of this stuff. but now its saying another error "redefinition of 'AF_DCMotor'

I fixed the question to the new question, the new error is in there too

On line 3,4, and 5, you used same name "motor" for all three instances. Changed those to motor1, motor2, and motor3


text:
Return photo stacking rail to start
In isolation (73 years old) and trying to get my macro photo stacking rail to return to start without a limit switch.  I know the number of steps taken, so it is just a matter of reversing the motor.  My code (copied and pasted from other sites) works like a dream (10 steps, fire an IR camera trigger) and continues up to when I want to return (line 73) taking 100 shots or steps however many I want - no problem.
I started a void return loop (and terminated the loop) but the coding has me beat.  I have attached my code (might look terrible, but it works).  Can anyone help out this old guy and give me the code to counter clockwise 1000 steps?
Thanks fellas
David
[code]
#include <AccelStepper.h>
#include <MultiStepper.h>

int smDirectionPin = 2; //Direction pin
int smStepPin = 3; //Stepper pin
int Distance = 0; // records the number of steps we have taken
byte numRepeats = 0;
byte maxRepeats = 100;
int smFirePin = 13;  //Trigger pin
#define fire 13

 void setup(){
  /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
  pinMode(2, OUTPUT);  //Direction Pin
  pinMode(3, OUTPUT);  //Step Pin
  pinMode(13, OUTPUT);  //LED pin
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(13,LOW);
  pinMode(smDirectionPin, OUTPUT);
  pinMode(smStepPin, OUTPUT);

  Serial.begin(9600); //Open Serial connection for debugging
}

void loop(){
   if (numRepeats < maxRepeats) {
   move1Step();
   Distance = Distance + 1; //record this step to see if we are et the end of our move

  if (Distance == 10)
  {
 if (digitalRead(2) == LOW)
 {
  digitalWrite(2 , LOW);
 }
 else
 {
  digitalWrite(2, LOW);
 }
 Distance = 0;
 numRepeats ++;
 delay(3000);
{
    trigger();
}
   }
 }
}
void move1Step() {
  digitalWrite(3, HIGH);
  delayMicroseconds(750);
  digitalWrite(3, LOW);
  delayMicroseconds(750);
}
// Power on the IR trigger circuit to fire the camera
void trigger()
{
    delay(1000); // wait for vibration to settle
    digitalWrite(fire, HIGH); // take the picture
    delay(2000); // wait for that to happen
    digitalWrite(fire, LOW); // disable the IR circuit again
}

// Advance the motor by one step
void step()
{
  digitalWrite(step, HIGH); //Trigger one step forward
  delay(1);
  digitalWrite(step, LOW); //Pull step pin low so it can be triggered again
  delay(1);
}

  void return();

{
  digitalWrite(smDirectionPin, HIGH);
  /*Slowly turns the motor 1600 steps*/
  for (int i = 0; i <200; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
  }

  while(1) { }
}

[/code]

code, such as this, makes no sense ... if (digitalRead(2) == LOW) { digitalWrite(2 , LOW); } else { digitalWrite(2, LOW); } ... that whole block can  be replaced by digitalWrite(2, LOW);

return is a reserved word, so you should rename the function to, for example, returnHome. You also need to remove the ; at the end of that line of code.

Plus your indentation is a mess. Pick an indentation style and then follow it religiously.  As it is the code is quite hard to read.

Gerben has provided a solution, your observation have been noted and accepted, thanks

I cleaned up your code a bit. Removed duplicate and unused code. I used a for-loop to make it run for 100 repetitions.
Feel free to let me know if you have any more questions, or if there are things that aren't clear.
// You aren't using these libraries, so I commented them out
//#include <AccelStepper.h>
//#include <MultiStepper.h>

int smDirectionPin = 2; //Direction pin
int smStepPin = 3; //Stepper pin
int smFirePin = 13;  //Trigger pin

byte maxRepeats = 100;

void setup()
{
  /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
  pinMode(smDirectionPin, OUTPUT);  //Direction Pin
  pinMode(smStepPin, OUTPUT);  //Step Pin
  pinMode(smFirePin, OUTPUT);  //Fire pin
  digitalWrite(smDirectionPin, LOW);
  digitalWrite(smStepPin, LOW);
  digitalWrite(smFirePin,LOW);

  Serial.begin(9600); //Open Serial connection for debugging
}

void loop()
{
  digitalWrite(smDirectionPin, LOW); // set stepper motor to run forwards

  for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
  {
    //move 10 steps forward
    for( byte j=0; j<10; j++ )
    {
      move1Step();
    }

    // wait and take a photo
    delay(3000);// there is already a delay in the `trigger` function, so this like could be removed
    trigger();
  }

  // return the stepper motor to the starting position
  digitalWrite(smDirectionPin, HIGH); // set stepper motor to run in reverse
  for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
  {
    //move 10 steps backwards
    for( byte j=0; j<10; j++ )
    {
      move1Step();
    }
  }

  // Do nothing
  while(1){ }
}

void move1Step()
{
  digitalWrite(smStepPin, HIGH);
  delayMicroseconds(750);
  digitalWrite(smStepPin, LOW);
  delayMicroseconds(750);
}

// Power on the IR trigger circuit to fire the camera
void trigger()
{
    delay(1000); // wait for vibration to settle
    digitalWrite(smFirePin, HIGH); // take the picture
    delay(2000); // wait for that to happen
    digitalWrite(smFirePin, LOW); // disable the IR circuit again
}

Gerben, I will follow your advice on deleting the delay, you should publish this, many in micro photography would be grateful, works like a charm. Fantastic.

If you delete the delay, you might have to increase the delay(1000). As currently it waits 4 seconds to prevent any movement from vibrations. You'd have to see how short the values can be, or just be a bit more patient. Glad it helped you.


text:
Reading from SPIFFS - What's the best way to deal with a string (or char) array with undefined length?
I've read that it's best to avoid using String in Arduino so I'm ready to use a char array if it's better.
I'm reading the file names from an SD Card and my goal is to store them in an array and then be able to read that array. What I'm currently doing is:
String lib_arr[100];
int lib_arr_size;

and then
File dir = SD.open("/");
int c = 0;
while (true) {
  File entry = dir.openNextFile();
  if (!entry) {
    // If no more files
    lib_arr_size = c - 1;
    break;
  }
  if(strcmp(entry.name(), "SYSTEM~1") == 0) {
    continue;
  }
  lib_arr[c] = entry.name();
  entry.close();
  c++;
}

and then
for (int i = 0; i < lib_arr_size; i++) {
  if(i == pos) {
    tft.print("> ");
    tft.println(lib_arr[i]);
  } else {
    tft.println(lib_arr[i]);
  }
}

This is not a solution because, for my purposes, the String lib_arr[100] can be 1000 or 10000 or 100000... and I found out that by increasing that value the global variables use skyrockets and Arduino says that it's out of memory. My goal is memory optimization. I don't know how to go about this problem.

read and print/process in one go. don't store the list in memory. here I have a SD browser https://github.com/jandrassy/lab/blob/master/SDWebServer/SDWebServer.ino

@Juraj That's a great idea! But when I'm browsing, whenever I go up or down to select different files, I would have to each time go to the SD card and get the files. Wouldn't that be bad for the memory? Is it a good practice? Is it better than storing in array?

The SD library uses these old "DOS" file names in 8.3 format, with automatic renaming. This a) limits the required size and b) makes it useless to deal with 10,000 files at once, as they will have unrecognizable names...

you don't have the RAM to cache the names. but you have time to load them. on a MCU with more RAM you could cache some last seen folder, but this would be premature optimization and that is the root of all evil in coding. https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize

@Juraj So I should get and read the file names on every file select?

why not? it is not slow and doesn't consume anything

@Juraj Got it. Thank you!

Well, you cannot use more memory than you have. If the length of file names is (probably/possibly) too much, you just cannot store it in memory. Some alternatives:

Use some compression... This will save you a bit, but at the end if you don't know how much the maximum bytes you need to store is, it will not help much
Use external SRAM memory... You need to write your own memory functions. Also a slight performance hit.
Use SD card memory... As SRAM, but much slower. Also not sure if you can use the same SD card to write on.
The best solution, but could be a big performance hit, is not to store at all the file names, but go through the file names and process what you need along the way. This is not always possible or feasible though. In your solution you can print the file names directly without storing (but I guess you want to do some additional processing).

The user can create 10000 files with a single character in each for example.

I can imagine, but you still cannot put all those file names in memory. You need either external memory or process them as you go through each file (without storing inbetween data/results).

Please look into the SPIFFS/ LittleFS library. You will see that the length of a filename (in those file systems it includes the path and the root indicator "/" as well as the extension .XXXXX as in .shtml ).
The maximum length defined in the libs is 32 as max length this means 31 chars to use + 1 terminator. To all the wise guys claiming you can change that (Yes you can but you should not). Do not do it - there are reasons for that. Read more.The maximum files is defined by blocksize and howlargeyou defined your SPIFFS partition.
There is no difference between writing to SPIFFs or a SD card both have around 100.000 r/w cycles per individual physical "cell" Sometimes it is cheaper to get a new ESP than a SDcard.
The question of the OP: As long as you read its no problem to do it often if you do mass renames you might have a problem after some time. What you do is actually partly copying what the libs do - so utterly obsolete. Speed is the same because its the same flash memory anyway (+ your processing overhead). You do not really have directories its a flat table system, so searching for path beginning with or containing (combined with a clever read strategy) can be done on the fly without problems. If you need data elsewhere (browser) filter & stream it - do not make in between storage (=duplication) with the small memory
As a final thought from the tech specs:

The main complication writing spiffs was that it cannot be assumed
  the target has a heap. Spiffs must go along only with the work ram
  buffer given to it.  This forces extra implementation on many areas of
  spiffs. ....
SPI flash devices are physically divided in blocks. On some SPI flash
  devices, blocks are further divided into sectors. Datasheets sometimes
  name blocks as  sectors and vice versa.
Common memory capacaties for SPI flashes are 512kB up to 8MB of data,
  where blocks may be 64kB. Sectors can be e.g. 4kB, if supported. Many
  SPI flashes  have uniform block sizes, whereas others have non-uniform
  - the latter meaning  that e.g. the first 16 blocks are 4kB big, and the rest are 64kB.
The entire memory is linear and can be read and written in random
  access.  Erasing can only be done block- or sectorwise; or by mass
  erase.


text:
Update class attribute with attachInterrupt
I want to refactor this code
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");
   }
}

Originally found here: source
to an Class based solution:
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
class FlowSensor {
  volatile int flow_frequency;
  unsigned int l_hour;
  unsigned char pin;
  unsigned long currentTime;
  unsigned long cloopTime;
  public:
    void flow () {
      flow_frequency++;
    };
    void setup() {
      pinMode(pin, INPUT);
      digitalWrite(pin, HIGH); // Optional Internal Pull-Up
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(pin), flow, RISING); // Setup Interrupt
      sei(); // Enable interrupts
      currentTime = millis();
      cloopTime = currentTime;
    }
    void loop() {
      currentTime = millis();
      // Every second, calculate and print litres/hour
      if(currentTime >= (cloopTime + 1000))
      {
        cloopTime = currentTime; // Updates cloopTime
        // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
        l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
        flow_frequency = 0; // Reset Counter
        Serial.print(l_hour, DEC); // Print litres/hour
        Serial.println(" L/hour");
      }
    }
    FlowSensor() {
      setup();
    };
};
FlowSensor flowsensor_intake;
void setup()
{
   flowsensor_intake = FlowSensor();
}
void loop ()
{
   flowsensor_intake.loop();
}

But i get the following error in the Arduino IDE:

/tmp/087639235/water_flow/water_flow.ino: In static member function
  'static void FlowSensor::flow()':
/tmp/087639235/water_flow/water_flow.ino:17:19: error: cannot call
  member function 'void FlowSensor::update_flow()' without object
update_flow()
^
exit status 1

I understand that flow is not a static function and that i cannot make it static because it is midifying a non static member.
But i cannot think of an alternate solution to this Problem. My goal is to monitor multiple flow sensors by creating an object in the setup() function, and updating them with every loop() call.

You've run into a classic trap.  There are a couple of things to think about.  First off, if this is a singleton class (as in there will only ever be one instance) then you can just have a non-member function that you use with attachInterrupt and have that function just call the member function you want.  Normally what I would do would be to create the instance in the .cpp and put an extern declaration for it in the header so that it can just be used without creating it.  Look at how Serial works for an example.  Then put all the configuration type stuff into a begin or init method to call from setup.  That way the non-member function for the interrupt can be part of the header and the user never has to see or mess with it and it feels like it's part of the class.
If this is not a singleton class and you might one day have several instances of this in one program then you have to start asking yourself how will the interrupt know which instance to act upon.

Yes i want to have multiple instances. Thinking of a struct approach now.

Ok then you've got a problem.  How will each instance know which interrupt to attach itself to?  How will the interrupt know which instance goes with which interrupt?  That turns out to be a can of worms, and it's the reason it's not allowed.

I agree. Singlton or static member functions won't work.
My current work around is a member function which is called by a specific function for each attachInterrupt.


text:
smart coding possible?
Is there a way to clean up this code...or do some smart coding?
In this example I use 6 relays, in the final code it will be 10.
Also I now use 5 switches and that will be 8, each with an own led. Now I only stated 1 led.
The code reads a button, and a few relays will get a signal. Also the buttonled will go on.
I will add more cases later. But I was wondering, is it possible/easier/just another way of writing the high/low to the relays and leds.
Can I somehow combine the LOWs or HIGHs within a case?
int relay1 = A5;
int relay2 = A4;
int relay3 = A3;
int relay4 = A2;
int relay5 = A1;
int relay6 = A0;

int led1 = 3;

int sw1 = 5;
int sw2 = 6;
int sw3 = 7;
int sw4 = 8;
int sw5 = 9;

int sw1Status, sw2Status, sw3Status, sw4Status, sw5Status;
int order = 1; // default is to set all relays off.

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

  pinMode(led1, OUTPUT);

  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
  pinMode(sw5, INPUT_PULLUP);

}

void loop() {

  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);
  sw5Status = digitalRead(sw5);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) {
    order = 5;
  }
  if (sw5Status == LOW) { // button 4 toggle
    if (order != 7) { // if order is not equal 5 turn on relay 1 & 4
      order = 6;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, HIGH);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, HIGH);
      digitalWrite(led1, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(led1, LOW);
      break;

    case 6: // if order equals 5
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(led1, LOW);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

What? I really don't understand, what you are trying to ask.

haha..ow  sorry! What I am trying to ask....is this code OK? Or can it be simplified?
eg. Is it possible to combine LOW:  digitalWrite(relay1 relay2 relay3, LOW);

use arrays to hold variables ... also use arrays to hold the case relay values

If all are handled the same and they don't have individual names, arrays and for loops are what you are looking for.
const byte relayPins[] = { A5, A4, A3, A2, A1, A0};
const byte ledPin = 3;
const byte swPins[] = {5, 6, 7, 8, 9};

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  for (const byte relayPin: relayPins) pinMode(relayPin, OUTPUT);
  for (const byte swPin: swPins) pinMode(swPin, INPUT_PULLUP);
}

Even arduino C++ nowadays understands the foreach syntax.
BTW: for your final pin count you'll need other/additional hardware. Either a Mega or shift registers or port expanders.

I also figured out that I run out of pins on my UNO boards, that is also why my code is not yet complete.
Considering Arrays, it's completely new for my, and looks like a bit of magic to me.
Could you give me a example on how to use this. How would it look if; for example Button1 is pushed...and relay 1, 3 & 5 is HIGH and 2,4 & 6 are LOW

The simplest book on C or C++ should cover arrays in general. If your names are like relay1 you could as well use relayPins[0] instead, to deal with them individually.
BTW: your question was about "smart coding" :)

Arduino Uno has 3 ports.
You can read and write the ports as 1 byte.
With all the switches on one port, you can read them all at once.
For example, using D7 to D3 to read the switches:
switches = (PIND & 0b11111000) >>3; // read D7 to D0, mask off D2-1-0, move data to lower 5 bits

Then you could have case (switches): for the 0 to 31 cases that are possible.
With all the relays on one port, you can change them all at once.
For example, using D14 to D19 for the relays:
PORTC = 0b00110011; // Dxx, Dxx, D19,18,17,16,15,14 or A5,A4,A3,A2,A1,A0

to turn on relays 1,2,5,6, and 3,4 off.
The LED would still be on its own.


text:
Combining two scripts
I'm trying to combine two scripts I've found. One to get my remote control model to work via a controller and the other to enable 6 ultrasound modules I have. When I omit the code highlighted in "THIS SECTION" (for the ultrasound modules) the controller and model works fine but when I put it in (to enable to ultrasound modules), the controller becomes unresponsive and the wheels spin uncontrollably.
I'm assuming it's something to do with having what should be two seperate loop sections combined into one?
Any help is much appreciated,
Thanks

//This section defines all the pin data and  to be used within the program loop.

//The following four lines set the pin numbers for the PS2 controller.
#define PS2_DAT        11 //Data pin.
#define PS2_CMD        10 //Command pin.
#define PS2_SEL        9  //Attention pin.
#define PS2_CLK        8  //Clock pin.

//The following six lines set the pin numbers for the motor module.
#define IN1     33 //Positive polarity for the right sided wheels.
#define IN2     35 //Negative polarity for the right sided wheels.
#define IN3     37 //Positive polarity for the left sided wheels.
#define IN4     39 //Negative polarity for the left sided wheels.
#define ENA     31 //Jumper pin start.
#define ENB     41 //Jumper pin end.

//The analogue values read from the PS2 contoller.
int LX = 0;
int LY = 0;
int RX = 0;
int RY = 0;

//The following twelve lines set pin numbers for the ultrasonic sensors.
int trigPin1=7; //Front transmitter (Object ahead detection).
int echoPin1=6; //Front receiver.
int trigPin2=5; //Right transmitter (Lane keeping).
int echoPin2=4; //Right receiver.
int trigPin3=3; //Rear right transmitter (Right blindspot detection).
int echoPin3=2; //Rear right receiver.
int trigPin4=14; //Rear centre transmitter (Parking sensor).
int echoPin4=15; //Rear centre receiver.
int trigPin5=16; //Rear left transmitter (Left blindspot detection).
int echoPin5=17; //Rear left receiver.
int trigPin6=19; //Left transmitter (Lane keeping).
int echoPin6=18; //Left receiver.

// This section sets the modes of PS2 controller.
//#define pressures   true
#define pressures   false
#define rumble      true
//#define rumble      false

PS2X ps2x; //Creates PS2 controller class.
int error = 0;
byte type = 0;
byte vibrate = 0;

void setup() {

Serial.begin (9600); //Opens the sensor serial ports and sets data rate to 9600bps
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
  pinMode(trigPin4, OUTPUT);
  pinMode(echoPin4, INPUT);
  pinMode(trigPin5, OUTPUT);
  pinMode(echoPin5, INPUT);
  pinMode(trigPin6, OUTPUT);
  pinMode(echoPin6, INPUT);

  pinMode(IN1,  OUTPUT);
  pinMode(IN2,  OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);

  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);

  delay(300);  //Added delay to give the wireless PS2 module time to start up before configuring it.

  //Checks for errors determined by pin data: GamePad(clock, command, attention, data, pressures, rumble)
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);

  if (error == 0) {
    Serial.print("Found Controller, configured successful ");
  }
  else if (error == 1)
    Serial.print("No controller found, check wiring");

  else if (error == 2)
    Serial.print("Controller found but not accepting commands");

  else if (error == 3)
    Serial.print("Controller refusing to enter Pressures mode, may not support it.");
  }

void loop() {
---------------------------------------THIS SECTION------------------------------
long duration1, distance1;
  digitalWrite(trigPin1, HIGH);**
  delayMicroseconds(10); // Added this line
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
  }

  long duration2, distance2;
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  duration2 = pulseIn(echoPin2, HIGH);
  distance2 = (duration2/2) / 29.1;

   if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
  }
  long duration3, distance3;
  digitalWrite(trigPin3, HIGH);
  delayMicroseconds(10); // Added this line
  duration3 = pulseIn(echoPin3, HIGH);
  distance3 = (duration3/2) / 29.1;

   if (distance3 >= 500 || distance3 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor3  ");
    Serial.print(distance3);
    Serial.println("cm");
  }
  long duration4, distance4;
  digitalWrite(trigPin4, HIGH);
  delayMicroseconds(10); // Added this line
  duration4 = pulseIn(echoPin4, HIGH);
  distance4 = (duration4/2) / 29.1;

   if (distance4 >= 500 || distance4 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor4  ");
    Serial.print(distance4);
    Serial.println("cm");
  }
  long duration5, distance5;
  digitalWrite(trigPin5, HIGH);
  delayMicroseconds(10);
  duration5 = pulseIn(echoPin5, HIGH);
  distance5 = (duration5/2) / 29.1;

   if (distance5 >= 500 || distance5 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor5  ");
    Serial.print(distance5);
    Serial.println("cm");
  }
  long duration6, distance6;
  digitalWrite(trigPin6, HIGH);
  delayMicroseconds(10);
  duration6 = pulseIn(echoPin6, HIGH);
  distance6 = (duration6/2) / 29.1;

   if (distance6 >= 500 || distance6 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor6  ");
    Serial.print(distance6);
    Serial.println("cm");
  }
---------------------------------------------END----------------------------------------

  ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed

  delay(50);
  if (ps2x.Button(PSB_L1))
  {
    LY = ps2x.Analog(PSS_LY); //receive values from p22 joystick
    LX = ps2x.Analog(PSS_LX);
  }
  if (ps2x.Button(PSB_R1))
  {
    RY = ps2x.Analog(PSS_RY);
    RX = ps2x.Analog(PSS_RX);
  }
  if (LY > 200 || RY > 200) //check if the joystick pushed up side
  {
    REV();
  }
  if (LY < 100 || RY < 100)
  {
    forward();
  }
  if (LX < 100 || RX < 100)
  {
    left();
  }
  if (LX > 200 || RX > 200)
  {
    right();
  }
  if(LX == 128 && LY == 128 && RX == 128 && RY == 128)
  {
    waithere();
  }
LY = LX = 128;         //return to default vlaues
RY = RX = 128;         //return to default values
}

void forward()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}
void REV()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}
void left()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}
void right()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
}
void waithere()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
}

pulseIn() has a standard timeout of 1s. Try to reduce it and see, if it works better

you can simpify your code if you use arrays to hold variables ... trigPin[], echoPin[], duration[], distance[] ... then you can use a for loop to iterate through the six sensors, instead of repeating code


text:
SimpleChat BLE Example prints scrambled characters
I am trying to use the SimpleChat application to test my RedBearLab Shield.
If I send "Hello" and to to Serial.print or Serial.write the return what I see in my Serial monitor is stuff like "Fh`Fx**-H3r:AJb6# E0CbJ"
Any idea what I'm doing wrong?
Thank you,
Andi Stancu

try changing the baud rate in the serial monitor

That most definitely fixed it! Thank you! Please add it as a solution so I can mark it! Thank you!

If you are transmitting Hello and receiving Fh'Fx**-H3r:AJb6# E0CbJ, then the problem is most likely a baud rate mismatch.
The receiver is sampling the data signal 3 or 4 times faster than it should.
Start by lowering the baud rate of the serial monitor to 1/4 of the current baud rate.
If that does not produce correct data reception, then start at the lowest baud rate and work your way up.


text:
Potentiometer motor system is not working
I am setting up a potentiometer system that includes a motor that is supposed to spin with the potentiometer changing the speed of the spin and a button to reverse it. I checked the coding and it is correct, the potentiometer, button, and motor are all functioning, but the system does not run. Can anyone propose any solutions to this issue?
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int potPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
  int speed = analogRead(potPin) / 4;
  Serial.println(speed);
  boolean reverse = digitalRead(switchPin);
  setMotor(speed, reverse);

}
void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);
  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);

}

I think the problem is that your "code" is an image. You can't compile an image.

@Majenko if that is an issue, it is no longer an image... :D

It looks, in the first image, like you have edited the picture to wipe out the markings on the L239D. Maybe it's not an L239D and you're trolling us? I can't see anything immediately wrong at first glance...

Or maybe it's just that the JPEG compression is so high it's hard to make out details any more.

BTW you should really connect all the GND pins of the L239D.

@Majenko I have confirmed that the pins follow the diagram correctly and the controller is in fact an L293D.

@Majenko Could you clarify further on the GND pin statement, please? We are both somewhat new to Arduino and are following the diagram supplied to us. Is it wrong?

The L239D has four pins labelled GND. All four of them should be connected to the GND of the Arduino (through the GND rail of the breadboard of course). It shouldn't matter, and it's doubtful that it is causing your problem, but it's good practice.

Measure the voltage on pin D9, D10, and D11. Also, it looks like motor supply uses USB supply. That's bad idea, you can potentially damage the USB port. If you can, use an external supply.

Does it run, whem you introduce a delay(100) into the loop function? When the motor function is called too fast, the PWM signal will restart constantly


text:
Passing struct from main.cpp to a class
Sorry if this question been posted but I couldn't find the one that matches my issue. I couldn't pass my struct values from the main file to a class. Any ideas? I got this:
error: no matching function for call to 'ODriveArduino::SetParam(R_motor_params&)'

Main.cpp:
#include ODriveArduino.h
ODriveArduino odrive(Serial1);

struct L_motor_params{
 int axis=1;
 float vel_Gain= 2.5f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};
struct R_motor_params{
 int axis=0;
 float vel_Gain= 2.75f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};

void setup() {
  struct R_motor_params M;
  odrive.SetParam(M);
}

ODriveArduino.h:
class ODriveArduino {

private:

    struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
    };

public:
    ODriveArduino(Stream& serial);

    // Commands
    void SetParam(struct motor_Params M);

 }

ODriveArduino.cpp:
#include "ODriveArduino.h"
template<class T> inline Print& operator <<(Print &obj,     T arg) { obj.print(arg);    return obj; }
template<>        inline Print& operator <<(Print &obj, float arg) { obj.print(arg, 4); return obj; }

ODriveArduino::ODriveArduino(Stream& serial)
    : serial_(serial) {}

void ODriveArduino::SetParam(struct motor_Params M){
  Serial1 << "w axis" << M.axis << ".motor.config.pos_gain " << M.pos_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_gain " << M.vel_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_integrator_gain " << M.vel_Int_Gain << '\n';
}

you have 3 struct types motor_Params, R_motor_Params, L_motor_Params, but you want the L and R to be variables of type motor_Params

@Juraj R_motor_Params and L_motor_Params have slightly different values. I want to pass them to SetParam. I figured, to do that, I need to have an identical struct in ODriveArduino.h so that SetParam knows what to expect. Obviously that didn't work. I'm not sure what I'm missing.

motor_params L_motor_params; creates a variable of type motor_params1 named L_motor_params

It looks like you're trying to implement polymorphism without implementing polymorphism.
What you have done is create three completely independent structures and assumed that they will all work together just because they are the same size, with similar names, and fields named the same. That's not the case. They are all completely separate.
Instead you want just one structure but to use it multiple times to create different variables:
// from ODriveArduino.h, but move *outside* the class
struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
};

// in your code
struct motor_Params left_params = {
    1, 2.5f/10000.0f, 40.0f, 0.0f/10000.0f
};

struct motor_Params right_params = {
    0, 2.75f/10000.0f, 40.0f, 0.0f/10000.0f
};

// later
  odrive.SetParam(left_params);


text:
Reading bmp images from SD card, converting it and displaying it on serial monitor in Arduino
Can someone please help me write code that can read a 24-bit BMP file from an SD card, save converted to 8-bit BMP internally, and display the 8-bit BMP pixel values on Arduino terminal as a 2D matrix. The program should align the bytes as two HEX values on the Arduino terminal. I am new to this and not sure how to go about it. Your help will be much appreciated.
The image is present in the SD card and coded as:
include <SD.h>
include <SD_t3.h>

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

void loop() {
  if (!SD.begin (BUILTIN_SDCARD)) {
    Serial.println ("NO SDCARD");
    while (1);
  } else {
    Serial.println ("YES SDCARD");
  }
  delay (1000);
  if (SD.exists("filename.BMP")) {
    Serial.println ("filename.BMP exists");
  } else {
    Serial.println ("filename.BMP missing");
    while (1);
  }
  delay (1000);
  File hFi = SD.open ("filename.bmp", FILE_READ);
  if (hFi == false) {
    Serial.println ("File open failed");
    while (1);
  }

You have to writeyour own routines. To get you started Look at this source code Add view-source:https://javl.github.io/image2cpp/. Although it is javascript, it can be transferred to C++ to a working conversion routine. The important part are the conversion routines.A word of warning: As the memory os limited you will have to do a line by line read from SD card convert line and write line by line back or you use maximum 16x16 size.Thats the reason why most converters run in browser or PC and the result is used in Arduino. An ESP8266 with 4MB memory would make life easier. For an implementation of graphic routines on Arduino Teensy look into this gaming library


text:
Connecting a FireBeetle ESP32 to Arduino
I have a very basic question, because I struggle to upload files to my FireBeetle ESP32 Board.
When I try to upload to the board I get an
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

On other boards you have to press & hold the flash button, but this specific board just has a reset button.
What can I do?

The flash button is virtual and controlled by the RTS signal from the computer through the USB port (why are you trying to connect through an Arduino?). It should automatically enter bootloader mode when you go to program it. There should be nothing you need to do.
However, if you do want to manually enter bootloader mode, just connect IO0 (note: not D0) to GND and press the reset button.

I suspect you do not have the right drivers installed. That's the issue I just solved for myself. And it can be easy to think you installed the right driver, when in fact you didn't.
Have you followed the instructions on DFRobot's product wiki?
I'm not sure if you have the ESP32-E or the earlier ESP32-IOT Firebeetle, but here's the link to the drivers mentioned for the Firebeetle ESP32E and here for the prior version, the Firebeetle ESP32 IOT
But I would suggest double checking which board you have an very meticulously ensuring you have the right driver installed.


text:
Nokia 5110 LCD number display problem
I have a problem regarding a Nokia 5110 LCD display. I am currently building a soldering station based on a PID controller. The original code was using a 7 segment display and I adapted the code to the Nokia display.
The problem is that when I rotate the potentiometer, the "read temp" and "set temp" is showing the exactly the same number, and after I finish rotating the potentiometer, the values return to their normal number.
How can I solve this problem ?
This is my code: https://pastebin.com/inPtkniX
This is the original project: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/
//Soldering station Software using PID
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>
#include <PCD8544.h>

PCD8544 lcd;
unsigned long updaterate = 500; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;
int temperature = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup() {
  lcd.begin(84, 48);
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  lcd.clear();
  //Read temperature
  Input = analogRead(0);
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 450, 25, 350);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 350);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    //temperature = newSetpoint;
    lastupdate = millis();
  }
  double gap = abs(Setpoint - Input); //distance away from setpoint
  if (gap < 10) {
  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  } else {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature, newSetpoint);
}

void show(int value, int newspnt) {
  lcd.setCursor(0, 0);
  lcd.print("READ TEMP");
  lcd.setCursor(0, 1);
  lcd.print(value);
  lcd.setCursor(0, 2);
  lcd.print("SET TEMP");
  lcd.setCursor(0, 3);
  lcd.print(newspnt);
  delay(200);
}

Please include the code into your question, so that it stands alone, even, when the pastbin link becomes invalid

Look at line 55, where you are doing this
temperature = newSetpoint;

There is no reason to give temperature the same value as the set point. It does not make sense. And the temperature variable is the same, that you are using to display.
So, while you are changing the setpoint, the temperatur variable gets overwritten with the setpoint. When you are not changing it anymore, the measured temperature is still in this variable, when you are displaying it.
Just remove the mentioned line.


text:
Getting coordinates from a touch panel with I2C
Hello world (this is my first message in this forum).
I am quite a just-married-to-Arduino guy, I am very passionate about this platform that I kew since long time but never had the time to dedicate.
Now I have done several home projects that made me both feel happy and feel sooooo rookie... But hey, here I am trying more and more complex things.
I am trying to do something I haven't found information about: I have a 10" touch panel (I am not talking about a screen, just the touch surface) which is a capacitive 10 pin panel that communicates with I2C protocol (there are SCL and SDK pins). I have managed to scan the address and turns out it is in the #40.
However, other than that I do not have the knowledge to get the coordinates out of that panel. My question is: is there any library that can help me with that or will I need to code everything?
I am attaching some pictures of the panel and the pinout to have a clearer picture of what I am talking about.
I thank you all for your time reading my post, I hope some day I will be able to provide some answers rather than questioning!
Joan.

Have you googled for a datasheet of that chip?

Where did you get that panel? Don't they provide any identification or information? A datasheet is necessary to do anything with the panel (at least, when you cannot sniff on a working communication with it, when it is connected to a working master device)

Hi Chris, thanks for your comment. I have googled it and found nothing really interesting. The user hcheung found an interesting library, but I have hit a rock with a part of the code I can't deal with (look below). The panel came to me by somebody that purchased it on ebay, so not really easy to get the source... I have found the manufacturer of the chip though: FocalTech

There is a simple library that works for FT5xx6 display panel.
Other information available:
Application node - https://cdn-shop.adafruit.com/datasheets/FT6x06_AN_public_ver0.1.3.pdf
Datasheet - https://www.newhavendisplay.com/appnotes/datasheets/touchpanel/FT5x26.pdf
In case those links might be no longer available in the future, a quick search on FocalTech FT5xx6 should give you the relevant information.

Hi! Thank you so much for your help! I have started with the library and have come out with an issue when trying to compile. I am afraid I am very novice if I don't know where the problem is, but the error is in this line: FT5xx6 cmt = FT5xx6(CTP_INT);

It seems that you are trying to create an instance of FT5xx6 class, the line FT5xx6 cmt = FT500x(CTP_INT); is simply incorrect. If you want to create an instance called cmd, it should be FT5xx6 cmd(CTP_INT);.

Hi, thanks again for your comment. I tried your suggestion and it shows the exact same error. Maybe there is something wrong in the libraries? I had to make the library file myself copying the text from the Github repository, maybe I did something wrong...

Ah, I just realised that the github is not structured as a proper Arduino library that you could download and use it. You need to do it manually. 1) Go to your Libraries directory where your Arduino IDE located, create a directory called FT5xx6; 2) copy FT5006.cpp from the github and save it inside the directory you just created, do the same for FT5xx6.h; 3) create a new project from Arduino IDE, and copy the example code from capacitive_7in_panel.ino on github. It should works now. I just tried (compilation only, didn't run as I don't have a FT5xx6 module). Good luck.

Hi again. I believe that is what I did, however I couldn't copy the file, but copy the text and generate a plain text file as it is not downloadable. I did this from a MAC computer, I will try to do it with a PC... Is this how you did it? Or there should be a way I could download the files?

Yahoo! It works. MAC or something was making these files go wrong for some reason. I made all the process on a PC and turns out that I get data. Now the difficult thing will be to understand it. I would like to make it just give me a set of coordinates of a single touch, it looks like this script delivers a lot more information than that. I am only interested in a single point touch, now I need to understand all the data in the serial monitor and figure out which is good for me. I will post an image of what I get. Thanks for your help! It is much appreciated.

Hi hcheung, I have been struggling with the code and the panel, but something is wrong... the monitor shows weird data, like I am touching 15 points or even touching in the same spot gives different data every time. Until it looks like something "saturates" and starts giving coordinates of 4095x 4095y. I really am lost now. Do you have any idea why this happens? I think I will start a new thread with the exact issue. Thanks for your help!


text:
What are examples of large Arduino code bases and how are they organized?
I'd like to find out:

how big can an Arduino project get, is there some limit?
are there examples of large open source code bases? I did some research but find only example projects with single .ino file. Are there projects with multiple files e.g. functions, constants in separate files say to avoid a 10K+ .ino file?

check the source code for some of the libraries

here https://github.com/jandrassy/Regulator

and a new one https://github.com/jandrassy/IsgModbusTcpSG

Yes, there are limits--as with any programming environment. 3d printer apps tend to be super-tight wrt space.

Big projects are likely not developed with Arduino IDE. Arduino IDE was make for designers/inventors, not for programmers.

Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming.

Source
Programmers will use a fully-fledged IDE which has many features a programmer needs on a daily basis, such as:

handling multiple files efficiently
allowing to create libraries instead of just setup() and loop()
code completion (suggestions as you type)
debugging (inspection and changing of variables at runtime)
refactoring (modifying the structure of your code without changing the behavior)
integrated version control (like Git / Github)

Such an IDE could be Eclipse with an Arduino Plugin or Atmel Studio and perhaps Visual Studio.
So, what do you need to look for? Don't look for .ino files. Instead, look for .h and .cpp code, just like other non-Arduino C++ code.
Some examples:

SPI: 297 lines
Wire: 453 lines
SoftwareSerial: 486 lines
I2S: 533 lines
USBHost: several files, up to 1600 lines

Again im late to the party...
If you are planning on making a larger project and splitting things up you can take advantage of libraries. This will work even if you are married to the arduino ide for some reason. if your not married to the arudino ide platformio doesn't suck too bad, and makes libraries a bit less messy when your doing the grunt work of setting them up the first time.
The idea should be to break your problem into smaller testable pieces of  code into smaller testable libraries.  If your code doesn't depend on arduino features you may be able to use test your library fully on a bigger machine to make sure there are no bugs (for example abuse clangs static analysis tool to see if you made any dumb pointer errors https://clang-analyzer.llvm.org/)
I kinda set an example of  this (https://gitlab.com/mikealger/ExampleArduinoProjectStructure) up for students a while back but i still think its handy for anyone looking to build /manage the lifecycle of a project, I still use the basic ideas when i'm doing one off small projects based on others work to keep my notes straight i.e.  https://gitlab.com/mikealger/celstronhomebrewgps
yea its probably shameless promotion but i haven't logged in for like 2 years...

Each sketch uses Flash memory, you can see this when you compile your project.
You also can see how much percentually you have used.
And as jsotola explains, libraries are examples how multiple files can be used.
However, next to you .ino scene (in the same folder) you can put .h, .c and .cpp files which are automatically compiled (when used by the .ino file). However, if you use too many files, because tabs are placed horizontally in the Arduino IDE, it's better to use a decent editor. And while doing that, you use the Arduino IDE to compile (only).

Thats an example how to organize by function groups.Other good complex examples can be found when searching for Arduino esp8266 webserver site:github.com The limit is basically your IDE -If you use ArduinoIDE the limit is (without already tested and working lib files) around 20 files, more is a pain in the a** to handle. I keep the length of my files between 500 - max 1000 lines. For documentation and keeping relationship diagrams (valuable for debug) I use doxygen with the graph extension.When using an IDE like eclipse you can use more files, you have a good overview over your classes, but time to spend (and learn) configuring a project is initially much higher and there are sometimes (release dependent) breaking changes in the tool chain.


text:
Sound quality is poor using a piezo in TinkerCad
I did a quick search and couldn't seem to find this question posted already, but I'm sure it must have so forgive me if it's a repeat.
I'm using a piezo and Arduino on TinkerCad to produce notes using the tone function, and the quality is not great (it's as if I can hear beats while the note is playing). I vaguely remember a colleague telling me this was an issue with the way my computer speakers handle square waves (I have a Macbook Air if that makes any difference), but I'm not positive. Has anyone had success in using TinkerCad to produce nicer sounding notes? If not, can anyone explain what the issue is to me?
Thank you!

Seems to be more a Tinkercad problem, than an Arduino problem

Tinkercad is a simulation. It's merely an approximation of how an Arduino works. You can't expect it to be perfect. A bit of glitchiness in sound is nothing to even think about caring about.

To pack the comments into a proper answer to the question:
As Majenko stated in the comments, Tinkercad is a simulation. The codes doesn't get compiled and uploaded to hardware. Instead Tinkercad interprets the code on the fly. Simulations are not perfect clones of the real hardware, so you cannot expect the same performance from it as from the real Arduino. Also it is not build for producing high quality sound. The focus is entirely on simulating how the Arduino works.
If you are using this with a real Arduino you most likely will not have the glitches in sound.
What you are currently hearing is not a problem of Arduino, but of Tinkercad. You could file a problem with the developer, but probably they will not think this is an issue, or they will give it a very low priority.


text:
availableForWrite() function return error when compiling for Arduino nano 33 BLE
I used availableForWrite() function as below in my code. When I compile it for nano 33 IoT, everything is OK and compiles perfectly. However, when I change the board to nano 33 BLE, I end up with two scenarios:
1. using Arduino IDE as compiler > gives no error but the board doesn't after programming.
2. using the web-based compiler in Arduino website > give the following error:
error: 'class Arduino::USBSerial' has no member named 'availableForWrite'; did you mean 'available'?"

my code:
NoreplyTime=millis();
TimePassed= millis()-NoreplyTime;

         while(!Serial.availableForWrite()){
         TimePassed= millis()-NoreplyTime;
         if (TimePassed>1000){
         return false;
         }
        }

even simply having:
while (!Serial.availableForWrite());

generates error ONLY for nano 33 BLE board!
Thoughts?

"but the board doesn't after programming" What doesn't it? You need to describe further. "web-based compiler in Arduino website" which compiler site with which settings? Maybe the used core in that site does not implement that method

Sorry! I needed to clarify further. After programming nano 33 BLE it seems the CPU can't perform that command line and can't establish a serial connection. Surprisingly there is no problem when I program nano 33 IOT with the same code and it runs it perfectly. It sounds to me that the serial library does not include "Serial.availableForWrite()" command for BLE boards.

The new Arduino cores use a common API maintained in a separate repository. This was copied from AVR core long time ago and doesn't contain some function added later to other cores. The function Stream.availableForWrite was added to Arduino API repository 5 months ago.
For the Arduino Mbed core they created a branch in the Arduino API repository to move the Arduino core in C++ namespace 'arduino'. But this was before availableForWrite was added. So the API version used in Mbed core doesn't have the function.
I reported it as issue. Even if they add the function to API I doubt they add an implementation of it to Serial.

Thanks for the explanation. I am new to programming and have no idea how to help to fix this but in the meantime, I just removed it from my code,and trying to make sure always I have space to receive the data! I have a question, may sound silly, the link you provided for the repository provides installation instructions, should I install it or Arduino IDE did it itself?

@Afshin, the Arduino API is part of the boards package you installed for the Nano 33 BLE


text:
node mcu disconnect from mqtt server
/*
    Basic ESP8266 MQTT example

    This sketch demonstrates the capabilities of the pubsub library in combination
    with the ESP8266 board/library.

    It connects to an MQTT server then:
    - publishes "hello world" to the topic "outTopic" every two seconds
    - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
    - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off

    It will reconnect to the server if the connection is lost using a blocking
    reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
    achieve the same result without blocking the main loop.

    To install the ESP8266 board, (using Arduino 1.6.4+):
    - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
    http://arduino.esp8266.com/stable/package_esp8266com_index.json
    - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
    - Select your ESP8266 in "Tools -> Board"

*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "SepehrNet";
const char* password = "orangecoffee";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

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

    randomSeed(micros());

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

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

    // Switch on the LED if an 1 was received as first character
    if ((char)payload[0] == '1') {
        digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
        // but actually the LED is on; this is because
        // it is active low on the ESP-01)
    } else {
        digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
    }

}

void reconnect() {
    // Loop until we're reconnected
    while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect(clientId.c_str())) {
            Serial.println("connected");
            // Once connected, publish an announcement...
            client.publish("sepehr.ghasem.helloxxx", "hello world");
            // ... and resubscribe
            client.subscribe("inTopic");
        } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

void setup() {
    pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
}

void loop() {

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

    long now = millis();
    if (now - lastMsg > 2000) {
        lastMsg = now;
        ++value;
        snprintf (msg, 50, "hello world #%ld", value);
        Serial.print("Publish message: ");
        Serial.println(msg);
        client.publish("outTopic", msg);
    }
}

I'm beginner at IOT and I'm using NodeMcu ESP8266 board and I want to control it with Arduino IDE so I install everything necessary and also using PubSubClient library for that. I used example file of PubSub in arduino. The NodeMcu first connects to internet and after a second disconnects.
I also switched the server(I don't know internet connection) from home modem to my mobile internet but it doesn't worked. I installed MQTT android application and want to connect to test server"test.mosquitto.org" and publish a meassage from NodeMcu to MQTT dashboard on my android mobile.
what is the problem with this standard sample code?

I don't know how to add my sketch in a properly way. does anyone know?

One line: three back-apostrophes. Then paste your sketch. Then three back-apostrophes again on another line.

FYI: Return code -4 means: MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time. It looks like your NodeMCU connects to your Wifi but cannot reach the MQTT broker. Can you ping test.mosquitto.org from your PC?

@jsotola, this looks like the mqtt_esp8266 example sketch that's part of the PubSubClient library

@sepehr, Your code connected and ran without problems on one of my NodeMCUs (with my Wifi credentials). The problem is not in your code.

@StarCat yes I can ping. I could load the web page on test.mosquitto.org.so what do you think about the problem? is that my internet connection? what should I do for debugging?

Does your NodeMCU actually have access to internet? Check with an NTP client or HTTP client example sketch. You could also try one of the other public mqtt brokers for testing You can choose one from this list.

@StarCat thanks. I tried another testing mqtt broker and it worked.


text:
Slow refresh rate of 1.8 TFT display
I have 1.8 TFT display for Arduino Nano and it changes color very slow. When I try to change the color of the whole screen I see how it changes color line by line. I use "Adafruit GFX graphics core" and "Adafruit ST7735" libraries to change colors.
Question: Slow refresh rate of 1.8 TFT display is due to limited computation capability of Arduino or 1.8 TFT display itself or library used?

Well, it's 16012818 bits (maybe *24, if it's not packed). With 1MHz SPI clock that means about 2.7Hz refresh rate (but without anything else like setting pixel address and so).

@KIIV most small TFTs run in 16-bit mode. That's (16*(160128)) + (118) bits (+11 for the setup of a drawing window), or 327768 bits. At 1MHz clock that's about 3fps.

The ST7735 TFT uses SPI to communicate. That can never be particularly fast.
At 160x128 pixels with 16-bit colour depth that gives you 327680 bits that you need to transfer just for the colour data.  On top of that you have 88 bits to set up a drawing window (11 bytes of "set X coordinate and width" [5 bytes], "set Y coordinate and height" [5 bytes] and "start drawing" [1 byte]).
That's a total of 327768 bits that you need to transfer.
Now the transferring of that data is at the mercy of the SPI clock speed. How fast that can go depends on what the ST7735 can work at and the quality of your wiring (if it's a shield you can almost discount the wiring).  Assuming you can operate at the maximum 8MHz that the Arduino can run SPI at (which is probable) then you get:
8,000,000
---------   =  24.4 frames per second
 327768

That is the absolute maximum theoretical speed, and doesn't take into account any work done by the Arduino to actually send the data. The SPI library is completely blocking in its operation and each pixel has to be sent separately as one blocking transaction. So you can expect about half that rate in reality, if not less, while it loops around and sends each pixel, then blocks waiting for the pixel to be sent.
And of course that's assuming running at the maximum speed. In reality that probably isn't happening. Libraries that use SPI often choose the "lowest common denominator" for their SPI speed (if they actively choose a speed at all) so that the library "just works" in the majority of cases. So the speed the library is running at will most likely be considerably lower than the actual maximum speed you could run at.
For example, if it runs at 1MHz instead of 8MHz then you will get about 3 frames per second (which is more like what you are describing).
So examine your chosen library and see what it does in the way of configuring the SPI speed. If it doesn't do anything then consider adding code to increase the speed. If it does then consider increasing the speed it operates at (see the SPI library reference for more details).
TBH, though, a small Arduino is seldom a good choice to control a TFT screen. At the bare minimum you really need a chip with far more memory so you can draw graphics "off-screen" in a framebuffer, and then use DMA to transfer that off-screen buffer to the TFT screen over a 16-bit parallel connection at high speed while leaving the CPU free to do other jobs.  Or even better a microcontroller with a built-in TFT controller to directly generate the correct drive signals for a TFT panel and store the whole screen image in internal RAM.

Given you use the last library versions and have the cables right - it is hard to guess without your code.
So to check if it your code load one or two of the library examles and see if it works there.Another option is to set SPI speed the set with begin(freq) is not working, because its wrong see more in this issue.If the problem still exists come back with wiring and code used. The nano is not the best choice with TFTs but runs decently.


text:
Marlin g-codes applicable for a Melzi Sanguino board
How/where do I find a complete listing of "acceptable" Marlin g-codes applicable to a Melzi Sanguino board on a 3D printer (Zonestar). It appears that not all printer boards accept all available Marlin codes.

Then I was thinking incorrectly. I had assumed that not all g-codes (from a Marlin build) were, in fact, “implemented” the same way on all boards, and some would not even be recognized or interpreted. But I still don’t understand why that is.

It depends what software is installed on the board. The board doesn't define the codes, the software does.

What exactly don't you understand? G Code is a broad standard. The developers if a firmware might think, that some G codes are not needed for the purpose, that the firmware is meant for. Thus they might decide to not implement them. Implementing all possible G codes would be a time consuming task. As much of this is open source, the developers might want to save some resources for imortant stuff

Ok, thanks for the clarification.

As already written in the comments the software defines what G-Codes are taken by a (printer) boardBUT Even if the software has the same name (eg Marlin) it might behave different on different boards because of:

different release versions for different hardware
different release repositories being ahead or behind the master repo
hardware specific features a G-code triggers (most unlikely)

The clever way is to go from features I need to software supporting thosefeatures to boards supported AND useable for my hardware to controll (3d-printer/CNC-router/laser-cutter aso)
  -


text:
How to debug MIDI input?
I'm trying to receive MIDI messages on a Leonardo. To do that I used the circuit in the diagram below (only the top half for receiving). The only thing I did differently was using an 1N4148 diode instead of the 1N914. I connected GND to pin GND, 5V to pin 5V and RX to pin 0 (RX), and I used code below to see whether I do get any inputs or not. (I first started with some more complex code but it seems this is the minimal thing I can do.) As a MIDI source I used an Arturia Keystep which I tested on a midi instrument.
Unfortunately I don't get any input, and I don't know why. What I tried so far:

Verified the polarity of all cables, and made sure all connections work.
Swapped the Leonardo with a different one (both new).
Swapped out the 6N137 optocoupler with another one (both new).
Addded above the if-statement a Serial.println("test"); which then resulted in an endless avalanche of "test" in the serial monitor - just to check if the USB connection works.
Measured the voltage between pin 5 and 8 on the 6N137 and it is indeed 5V.

Is there anything obvious I'm doing wrong? What things do you suggest doing to try to find the bug? (I do have a multimeter but no oscilloscope.)
 (from this answer).
byte b;
void setup() {
  Serial.begin(9600); //USB
  Serial1.begin(31250); //MIDI
}

void loop() {
  if (Serial1.available() > 0) {
    b = Serial1.read();
    Serial.println((int)b);
  }
}

I don't see any obvious problem, but I used a similar circuit (long time ago though), and I used an 1N4148 without any problem. I had some trouble using the correct resistor value, and I added ferrite beads, but this should not be a problem on a breadboard.

Have you checked the plugs according to diagram => solder side.

perhaps you reversed pins 4 and 5

@Codebreaker007 I think that is it, it seems I have swapped pin 2 and 3 on my stripboard. I'll try to fix that and report back - it would be nice if it was that simple:)

https://learn.sparkfun.com/tutorials/midi-tutorial/all

@MichelKeijzers Thanks, that is good to know. What are these ferrite beads you mentioned?

They are for reducing EMI, shouldn't be any problem in a normal environment.

@Codebreaker007 It was exactly that, I swapped pin 2 and 3, thanks for mentioning that - with all the warnings about this I thought i wouldn't make such a silly mistake:)

The solution:
On the image is stated plugs are solder-side. So swapping pin 2/3 does the trick

Actually I should have clarified: The picture is a top down view on the component side - my mistake was that I misinterpreted the diagram:)

I think problem is in baudrate of your USB, message from usb is slow and this destroy MIDI message (timing of 31250 baudrate). Set little bit faster USB serial speed. And make buffer between.
Is only try, i dont know if its solve this problem.

Hi devbob, the problem was already solved and acknowledged.


text:
If condition not working as expected
In the last condition in else if (see code marked with ***), I am not getting my screen with the laser/specklke fail, if both failflag 1 and failgflag 5 is there,  however it shows me laser fail instead. Please help to solve my error.
#include <UTFT.h>
#include <avr/pgmspace.h>
#include <SPI.h>
#include <avr/wdt.h>
extern uint8_t Retro8x16[];
extern unsigned int virtek3[];  //display pic
UTFT myDisplay(ST7735, 11, 13, 3, 2, 4);

int buttonhold = 0;
int state = HIGH;
int tim = 0;
int tim1 = 0;
int tim2 = 0;
int button = 1;

float volt = 0;
float volt1 = 0;
float volt2 = 0;
float volt3 = 0;
float volt4 = 0;
float volt5 = 0;
float volt6 = 0;
float volt7 = 0;
float volt8 = 0;
float volt9 = 0;
float volt10 = 0;
float volt11 = 0;
float volt12 = 0;
float volt13 = 0;
float volt14 = 0;
float volt15 = 0;
float volt16 = 0;
float volt17 = 0;
float volt18 = 0;
float volt19 = 0;
float volt20 = 0;
float volt21 = 0;
float vcc = 0.0;
float temp = 0.0;
float r1 = 10000.0;
float r2 = 2200.0;
int failflag = 0;

//void(* resetFunc) (void) = 0;

void setup()
{
    pinMode(18, INPUT);   //For NEXT button
    pinMode(20, OUTPUT);  //For Relay power
    pinMode(21, OUTPUT);  //For Relay power
    pinMode(14, INPUT);
    Serial.begin(9600);
    myDisplay.InitLCD();
    myDisplay.clrScr();
    myDisplay.setFont(Retro8x16);

                                                                                digitalWrite(20, HIGH);
    digitalWrite(20, HIGH);
    digitalWrite(21, LOW);

    attachInterrupt(digitalPinToInterrupt(18), next, LOW);
    myDisplay.fillScr(255, 255, 255);
    myDisplay.drawBitmap(20, 1, 126, 126, virtek3, 1);

   while (1) {
    delay(100);
    if (state == LOW) {
    break;
    }
  }
}

void next() {
    state = LOW;
    Serial.println(buttonhold);
    buttonhold++;
    if (buttonhold > 500) {
    //digitalWrite(21, LOW);
    resetFunc();
    }
  }

void loop()
{
  digitalWrite(20, LOW);
 digitalWrite(21, LOW);   //Relay is ON.
  myDisplay.clrScr();
  state = HIGH;
  buttonhold = 0;
  while (1) {
    failflag = 0;
    float voltage_value = 0;

    myDisplay.setColor(0, 255, 255);
    myDisplay.print("1.Voltage Test", 35, 0);

    myDisplay.setColor(255, 255, 255);
    myDisplay.print("(V)", 0, 20);
    myDisplay.print("LASER",50,20);
    myDisplay.print("SPECKLE",100,20);

delay(1000);

      //FOR ANALOG A4 PIN
      //A4 pin connected to TP2 of speckle
      float volt_b = 0;
       float volt_c = 0;
       float volt_d = 0;
      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A4)));
      }
      volt_b = volt_b / 1000;
      volt1 = volt_b / (r2 / (r1 + r2));

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("TP2 :", 0, 38);

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 60, 37);

      Serial.println(volt1);                      //ANALOG A4
      if (volt1 >= 5 && volt1 <= 7.30) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt1, 2, 120, 38);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt1, 2, 120, 38);
      //myDisplay.print(" ", 150, 38);
      failflag = 1;
      }

      delay(2000);

      digitalWrite(20, HIGH);
      digitalWrite(21, LOW);
       delay(2000);

      //FOR ANALOG A4 PIN
      //A4 pin connected to TP2/L of SPECKLE

      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A4)));
      }
      volt_b = volt_b / 1000;
      volt2 = volt_b / (r2 / (r1 + r2));

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("TP2/L :", 0, 56);

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 60, 56);

      Serial.println(volt2);                       //ANALOG A4
      if (volt2 >= 5 && volt2 <= 0.05) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt2, 2, 120, 56);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt2, 2, 120, 56);
      //myDisplay.print(" ", 150, 56);
      failflag = 1;
      }

      //FOR ANALOG A1 PIN
      //A1 pin connected to J1_1 of SENSOR
      volt = analogRead(A1);
      volt3 =(volt * 4.8) /1024;

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("J1_1 :", 0, 74);

      Serial.println(volt3);                 //ANALOG A1
      if (volt3 >= 0 && volt3 <= 5.25) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt3, 2, 60, 74);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt3, 2, 60, 74);
      //myDisplay.print(" ", 150, 74);
      failflag = 5;
      }

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 125, 74);

      //FOR ANALOG A0 PIN
      //A0 pin connected to J2_2 of SENSOR

      for (int i = 0; i < 1000; i++) {
      volt_b =(volt_b + (4.99 / 1024 * analogRead(A0)));
      }
      volt_b = volt_b / 1000;
      volt4 = volt_b / (r2 / (r1 + r2));

    //volt4 = volt_c - 2.7;

      myDisplay.setColor(255, 255, 255);
      myDisplay.print("J2_2 :", 0, 92);

      Serial.println(volt4);                //ANALOG A0
      if (volt4 >= 5 && volt4 <= 8.82) {
      myDisplay.setColor(0, 255, 0);
      myDisplay.printNumF(volt4, 2, 60, 92);
      //myDisplay.print("  ", 130, 20);
      } else {
      myDisplay.setColor(0, 0, 255);
      myDisplay.printNumF(volt4, 2, 60, 92);
      //myDisplay.print(" ", 150, 92);
      failflag = 5;
      }

      myDisplay.setColor(0, 255, 255);
      myDisplay.print("NA", 125, 93);

      digitalWrite(20, LOW);
      digitalWrite(20, LOW);
      delay(2000);

      if (failflag == 5) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("LASER FAIL", 35, 108);
      delay(4000);
      state = 0;

      }

      else if (failflag == 1) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("SPECKLE FAIL", 35, 108);
      delay(40000);
      state = 0;

      }

 // *** Here the condition not working START
    else if ((failflag == 5) && (failflag == 1)) {
      myDisplay.setColor(0, 0, 255);
      myDisplay.print("LASER/SPECKLE FAIL", 15, 108);
      delay(40000);
      state = 0;
      }
  // *** Here the condition not working END

what is the program supposed to do? .... what are you expecting to happen? .... what actually happens? .... do you get any errors?

(failflag == 5) && (failflag == 1))

failflag can't be both 5 and 1 at the same time.

As you ask for two different assignments for the same var its never gone to work this way. Two quick options:
Do binary addidition
 failflag = 0;
 if(errorA) failflag += 1;
 if(errorB) failflag += 2;
 if(errorC) failflag += 4;
 if(errorD) failflag += 8;

//then you can decode combined errors as follows
else if (failflag == 13) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

The other quick one is defining failflag as bool array
bool failflag [5] = {00000}; // 5 elements

 if(errorA) failflag [0]= 1;
 if(errorB) failflag [1]= 1;
 if(errorC) failflag [2]= 1;
 if(errorD) failflag [3]= 1;

//then you can decode combined errors as follows
else if ( failflag [0] == 1 &&  failflag [2]== 1 && failflag [3]== 1) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

as we have failflag[i] as a bool we can condense the code to
else if ( failflag [0] && failflag [2] && failflag [3]) {
    Serial.println("Errors: A, C, D"); // 1 + 4 + 8 =13
}

Whatever suits your needs. As I said just 2 quick ones
Edit Cleaning up you question other things to change:
Get rid of the delay() (except in setup to initialize your hardware and in loop  during debuging.
The 21 float vars could be stores in a float array
 float myFloatVars [22]

and write the values to the position
 myFloatVars [11] = myMeasureFunction();

you can do this even in a timed for loop doing a recurring FIFO function (kind of circle buffer), the first saved value is dumped if the array is full to put the next one in. So you are able to produce a "gliding" average, which is what you want

bool data type is true/false, so the test is if ( failflag [0])  or if ( !failflag [0])   .... if ( failflag [0]== 1) equates to if ( true==true), which is redundant

Your right  copy & paste error. changed it to true so that the OP sees whats going on - the redundancy helps beginners to understand. Thanks for the eagle eye

note: null termination is used for strings, not for numerical arrays

this is for OP's benefit .... if(errorA) failflag [0]= 1; can be replaced by failflag[0] = errorA, but only if the failflag[0] is not set by multiple sources

Thank you so much . I use bool array and it works. Really appreciate you legend !

Please mark as solved/accepted Thanks