text:
Do interrupts block other interrupts?
If I have an interrupt attached to two pins and the handler of the first is still executing when the second interrupt fires, does it:
a) queue the second interrupt,
b) ignore the second interrupt (missing it altogether), or
c) pause processing of the first interrupt to execute the second?
I am writing code that logs the exact time the interrupt occurs. Quite lightweight, but have three pins and am logging the rise and fall of each, so there is the potential for collisions. If a) then the second interrupt timestamp will be late, b) there is no timestamp for the later interrupt or c) the timing of the first and second interrupts will be ambiguous.
b) is the worst case, the other two are manageable.

By default the compiler disables interrupts at the start of the ISR and re-enables them at the end. You can disable this, and enable interrupts inside other interrupts by adding the ISR_NOBLOCK attribute to your ISR. But you have to know what you are doing.

It sound like Timer Input Capture Mode might be useful for your specific problem.

Gerben expand on this. I've been working hard to get up to speed on interrupts, and have got as far as external interrupts on pins and internal interrupts. You might be suggesting something better for the task

Depending on your board it might not be possible to use Timer Input Capture Mode for your pins. With that mode you can let a hardware Timer capture the duration of a pulse (not its timestamp at the general timelime). But you would need one hardware Timer per pin. Most boards don't have that much timer left, especially, if you still want to use functions like delay(), millis() or micros(), which need Timer0 to be configured for them. Maybe a simple pin change interrupt would be the easiest. Though that depends on your timing requirements ( how accurate should the recorded timestamp be?)

@Gerben: On AVR, interrupts are disabled at the start of the ISR not by the compiler, but by the hardware. The ISR_NOBLOCK attribute is a way to ask the compiler to re-enable interrupts as early as possible within the ISR.

It depends on the architecture.
Assuming AVR (8-bit Arduino) then it will queue the second interrupt until the first is finished.
It works by setting a flag in a register at the moment the interrupt occurs. Then between instructions it checks that flag and executes the associated interrupt routine. If an interrupt is in progress at the time the flag still gets set, but it is unable to check the state of that flag until after the current interrupt is over and normal execution occurs, at which point after the next instruction is completed it checks the interrupt flag statuses and runs the second interrupt routine.

It depends on the specific MCU, not all are exactly the same.
Some have interrupt priority circuitry that you can use.  But in general, an ISR can be interrupted by another incoming IRQ, etc.  What you often do in an ISR is mask IRQ, handle the IRQ, and then unmask to let any pending IRQs be handled.
This is one reason why long-running ISRs should be avoided!


text:
Switch case (millis()) UPDATED
I want to create a sketch that counts the days from the moment the "project" start and send and osc message every two days (or more) for 3 weeks. So:

day zero : osc message -> 0
day two. : osc message -> 1
day four : osc message -> 2

etc.
I'm trying to create a state machine to send the messages when the millis reaches a certain time it should print message and so on for the other times.
I'm giving a small example:
I went with @jsotola's suggestion and tried out the BlinkWithoutDelay approach. It seemingly works because I get serial prints around the correct millis() they are printed in 4fold or 3fold the messages.
EDITED CODE:
int daytwo = 25920; // for testing purposes other numbers then the actual millis()
int dayfour = 44400;

void loop() {
  unsigned long currentMillis = millis();   // store current time

  if (currentMillis == daytwo) {
    Serial.println("daytwo");
  }

  if (currentMillis == dayfour) {
    Serial.println("dayfour");
  }
}

Serial output:

    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.926 -> daytwo
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour

declare a variable to hold the osc message number .... increment it every 48 hours and transmit message ... refer to the blinkWithoutDelay example sketch for the method of repeating an action in a non-blocking way

And comparison is == not =. What is your question?

Also, do not compare time with equality, that will never work reliably. (What if the test is not executed at that precise moment?)

If it “seemingly works”, what exactly is your question? The way you now test for the appropriate time (with a comparison based on equality) is really unreliable. Why do you not use the same logic as the “blink without delay” sketch (i.e. use  “equal or greater than”) so you cannot accidentally skip an event?

@StarCat if I use == then I thought it would create a single message (I only need 1 message per 2 days as described in the goal of the project before the question on how to achieve this. (first I got the millis() example then the statemachine example and know I tried the blinkwithoutdelay way as the comments advised me to do.))
The >= comparator  gives me an overflow of Serial.print (or osc messages) in this case. Any suggestions?

You have to remember: a millisecond lasts for an entire millisecond. That's an eternity for an Arduino.

You can calculate the day using int day = millis() / 86400000UL. Then use that inside you switch-case statement.

@LazyFatTree no, you did not use the blinkWithoutDelay approach .... please examine the blinkWithoutDelay sketch closely, read and understand what the comments say ... one thing that you should understand is that the if statement is true only once every interval, not multiple times like your code ... just increment a counter inside the if block ... use the counter value to print day

The following code is not very "clean" but easy to understand. Use a variable to hold the day, you have already printed and check in which interval you are. If you change the 2 day interval print a message and set the actDay variable to the number of the day you have already printed; to avoid repprinting it again.
int daytwo = 25920;
int dayfour = 44400;

int actDay = -1;

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis < daytwo)
  {
    if ( actDay != 0 )
    {
      actDay = 0;
      Serial.println("dayzero");
    }
  }
  else if (currentMillis < dayfour )
  {
    if ( actDay != 2 )
    {
      actDay = 2;
      Serial.println("daytwo");
    }
  }
  else
  {
    if ( actDay != 4 )
    {
      actDay = 4;
      Serial.println("dayfour");
    }
  }
}

Thanks your example was most comprehensible for so I'm going to vote this a solve. If others think the above answer is best please up vote that to then!  @Peter-Paul-Kiefer thanks again!

int day = 0;
unsigned long prevMillis = 0;
const unsigned long MILLIS_PER_DAY = 86400000UL;

void setup()
{
  prevMillis = millis();
}

void loop() {
  if( millis() - prevMillis > MILLIS_PER_DAY )
  {
    // one whole day has passed
    day++;
    prevMillis += MILLIS_PER_DAY;

    // do the things you want to do at the beginning of a new day
    if( day==2 ) {
      Serial.println("daytwo");
    }
    else if (day == 4) {
      Serial.println("dayfour");
    }
  }
}

This is a more generic version. It checks if 24*60*60*1000 milliseconds have past since the last time the day rolled over. When this occurs, it will increment the current day and update prevMillis to have the value of millis() when the day started.
This also has the advantage that is will only run your "daily code" once.
And will also run, when some other task takes a long time. I your old code, you might miss the exact moment millis() is the value you are looking for, if some other code takes more than 1 ms.

Myself, I would prefer a solution like your's. But, I thought, it would be better to explain the principple and still think the OP is smart enough to extend the example if only he/she have understood the basics. Again, your solution is the better one. Please let me point you to some issues': You used the undeclared variable dayfour instead of 4.

After about 50 days the millis() counter overflows and starts with 0. For about 50 days the if block will not be entered, Then after that period the prevMillis will overflow to a value ~25032704. If only "daytwo" and "dayfour" the is not an error (only if the day variable overflows ;-)). But if the OP tries to add more cases or eventual a more generic solution, this could be a problem.

In a comment above you mentioned a very good solution that would bring your already "good" answer to the next level. int day = millis() / 86400000UL. The use a switch statement. It also would be easy extendable. Only, it would make a changes like resetting the days to 0 or whatever a little bit complicate. I regrette not have given that solution. ;-)

@PeterPaulKiefer good catch. Changed dayfour to 4. Thanks.

source: Stack Exchange

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

sort: votes


text:
Help with ESP32-CAM "AI THINKER" module
I'm trying to make a RC car (with a surveillance camera if possible, using the web-cam code that comes with the ESP library) using a ESP-32 CAM as a wifi module to control the car using my computer. Problem is that I keep getting the "invalid head of packet" error whenever I try uploading anything. I've tried holding the boot button as I upload and I cannot use the capacitor simply because I don't have it and don't want to buy it and spend time getting it. I also have the GPIO0 pin connected to GND during the uploading process. Any other ways to get it working? My car consists of 2 DC motors powering only the back two wheels and a servo that steers the front wheels, and I want to use the ESP32-CAM to connect to wifi to connect to a webserver from my pc to control the car.

I suspect that the power supply you used to power the ESP-32 can't provide the sufficient current.

You don’t need a capacitor and you don’t need to hold any buttons while uploading, just connect GPIO0 to ground, +3.3V power to your ESP32Cam’s +3.3V input, ground from the power supply/USB to Serial to ESP32 ground, Serial TX to ESP32 RX and Serial RX to ESP32 TX. The entire procedure is outlined very clearly here. What kind of USB-to-Serial are you using?

@StarCat, I tried what you said but now I'm getting the "Timed out waiting for packet header" error.

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


text:
PubSubClient: Subscription working, but callback never called
I am using an ESP32 (https://heltec.org/project/wifi-kit-32/) with a AM2302 DHT22 and an LDR, talking to mosquitto on a Linux box.  Publishing data is working fine, other than the "exceeded timeout, disconnecting" lots of people seem to be having.  However, when a message is sent from another client to a topic I am subscribed to, my callback is never called, so I can't consume it.
In my reconnect function, I have
    boolean success = mqttClient.subscribe("sensors/basement/led");
    Serial.print("Subscribe returned ");
    Serial.println(success);

and it does return 1 which I believe is success (usually success is zero but I don't think that's the case here).  I also see the subscription in my mosquitto logs, which are currently cranked up to debug.
1610417274: New client connected from XXX.XXX.XXX.XXX as Basement1 (c1, k15, u'XXXXXXXXX').
1610417274: Sending CONNACK to Basement1 (0, 0)
1610417275: Received SUBSCRIBE from Basement1
1610417275:     sensors/basement/led (QoS 0)
1610417275: Basement1 0 sensors/basement/led
1610417275: Sending SUBACK to Basement1

When I send data to sensors/basement/led from the other client (mqttdash), the server receives it, and sends it to mqttdash, as well as Basement1, which is my ESP32:
It's definitely sending the message to the ESP32:
1610417546: mqttdash-3785c5ce 0 sensors/basement/led
1610417546: Sending SUBACK to mqttdash-3785c5ce
1610417578: Received PUBLISH from mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to Basement1 (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))

However, my callback is never called.  Here is the setup of the callback:
WiFiClient espClient;
PubSubClient mqttClient(espClient);
...
void setupMQTT()
{
    mqttClient.setServer(MQTT_HOST, MQTT_PORT);
    mqttClient.setCallback(mqttSubHandler);
    mqttConnect();
}
...
void mqttSubHandler(char *topic, byte *message, unsigned int length)
{
    Serial.print("Message arrived on topic: '");
    Serial.print(topic);
    Serial.print("'. Message: ");
    String messageTemp;

    for (int i = 0; i < length; i++)
    {
        Serial.print((char)message[i]);
        messageTemp += (char)message[i];
    }
    Serial.println();
...

Full code at https://github.com/djsegfault/arduino/blob/master/basement_monitor/basement_monitor.ino
Does anyone know why the callback is not being called?  Thanks in advance.

nknolleary, the owner of the library, correctly identified the problem:
You need to call mqttClient.loop() in you main loop. Without that, you are never giving the client a chance to check for any incoming messages.


text:
Using same GPIO pins to control multiple stepper drives
I have an Arduino Mega 2560 and I want to control four 23-frame steppers same speed/direction for a conveyor application. I want these to be synchronized exactly as possible for smooth operation.

Can four TB6600 drivers be daisy chained to the same Arduino GPIO pins?

Is there a limit to how many number of drivers I can daisy chain?

I'm wondering about current draw from the 5 volt Arduino GPIO, spread out over many drivers.

Thanks for your help!
Bob

daisy chain means connected in series, not connected in parallel ... https://irepo.primecp.com/2016/05/280836/Daisy-Chain-Flower-Crown_Large600_ID-1656864.jpg

Those devices use opto-isolated inputs. To all intents and purposes they look just like an LED with a resistor in series.
The built-in resistor looks like it sets the current to "between 8mA and 15mA" and typically 10mA, though it's impossible to say what it actually is.  So we'll take the worst-case scenario of 15mA.
The Arduino has an absolute maximum of 40mA, and a recommended maximum of 25mA from each IO pin, with a maximum of 200mA in total through all pins.
That means you ideally can't really have more than one TB6600 per IO pin, but you could get away with 2 per pin, certainly no more.
To run lots in parallel you would need a separate set of drivers that can "fan out" the low-current signal to either a single high current signal or a parallel set of low-current signals.
It looks like you provide 5V to one pin of each input (the anode of the opto-isolator) and sink the current through the other pin (the cathode of the opto-isolator) to ground through your IO pins. That means you could use a single large N-channel MOSFET to sink all of the cathodes in parallel and invert your IO logic in software.

So the MOSFET is acting like a relay keeping the IO signal intact (not too much draw on Arduino) while being able to sink the sum total of all tb6600 drivers involved?

@RobertBorn Correct, but also as an inverter, so a HIGH would turn on instead of a LOW as you would normally use for that device.

Please forgive me .. I'm more of a high power electrical guy. Actually I get into way too many kinds of projects :)
In order to not have to mess with my control SW and elegant GUI I paid a college kid to build for me .. could I simply reverse the common to the tb6600 inputs from +5V to ground?
I still need to study the connection of the MOSFET.
Another thought .. I've used these opto-isolated signal boards before. But maybe they are not high speed enough to handle the PWM signal?

@BobB You could use two N-channel mosfets, one as an inverter (as in an RTL inverter) or maybe a P-channel MOSFET to switch the 5V signal, sure. Or add an actual inverter chip to the outputs (74HC00 gives 6 inverters in one chip). There's lots of things you could do.


text:
Maximum baud rate for sending a byte of data via SoftwareSerial from master Arduino UNO to slave Arduino UNO
I am trying to read data from a Blynk widget via ESP8266 and Arduino UNO and trying to send it to another slave Arduino UNO.  But, the problem is the data is taking some time to reach to the slave Arduino for further processing and I need it to be fast as it is needed for controlling a drone.
If any one can help, please help. I am a tenth grader and a newbie. So, I don't have a lot of experience.
Here is the code for the master Arduino:
#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <SoftwareSerial.h>   //We are using software serial so as not to conflict with serial download and monitor

SoftwareSerial mySerial(5,6); // RX, TX

int of=0;
int throttle=0;

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "auth";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "wifi_name";
char pass[] = "wifi_pass";

// Hardware Serial on Mega, Leonardo, Micro...
//#define EspSerial Serial1
// or Software Serial on Uno, Nano...
//#include <SoftwareSerial.h>
//SoftwareSerial EspSerial(2, 3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&Serial);
WidgetLED l(V3);

void setup()
{
 // Debug console
 Serial.begin(9600);
 delay(10);
 // Set ESP8266 baud rate
 Serial.begin(ESP8266_BAUD);
 delay(10);
 Blynk.begin(auth, wifi, ssid, pass);
 mySerial.begin(9600);
}

void loop()
{
 Blynk.run();
 l.on();
 mySerial.write(of);
 mySerial.write(throttle);
}

BLYNK_WRITE(V1)
{
  of = 100+param.asInt();
}

BLYNK_WRITE(V2)
{
  throttle = param.asInt();
}

how do you know that the bottleneck is the baud rate? ... the slave code could easily be running slow

If the distance (wires) between the 2 processors is short enough, you might consider I2C or SPI.  Also, for speed you should make sure you are using all the hardware support available and not emulating serial ports using software.  If there are not enough hardware resources on the processors used on the Arduino boards you picked out - consider using a more capable processor on a different Arduino board.

A practical answer to the maximum baud of SoftwareSerial is non-trivial and probably not as helpful to you as you might expect in solving the fundamental problem of getting information from Blynk through to whatever in your project actually needs that information timely.  Typically in aerial (I presume) drone applications, people are concerned about weight as well.  So, I'm curious: are all three of these things going to be mounted on the drone?  (Why) do you need all three?

Yes all three are mounted on the drone...  but i have quite powerful motors and 10*4.5 blades @timemage

@jsotola yeah that was the problem....thank you for ur help but now there is another problem it is tipping over   :)

@st2000 i could not use spi because i could not understand how it works.... and i2c i did not use because already my arduino is communicating with the bmp via i2c i dont know if it supports two wires(Wire.h)....

I2C supports more than two devices on the same bus (same Wire instance) such that having multiple buses is often unnecessary.  The case is similar with SPI except that multiple select lines are typically needed. When using an UNO as a slave, you may find I2C easier because it has a built-in flow control mechanism (clock stretching).


text:
How can I get an Arduino Uno run the Feather9x_RX example?
How do I get this example to run on using an Arduino Uno. I've updated RFM95_RST, RFM95_CS & RFM95_INT to the relevant pins (2,4 & 3 respectively).
This is the output on the Serial Monitor when the sketch is loaded:
Feather LoRa RX Test!
ERROR: Failed to put device in LoRa mode.
RH_RF95_REG_01_OP_MODE: 0
LoRa radio init failed

I've followed this wiring set up:

#include <SPI.h>
#include <RH_RF95.h>

#define RFM95_RST     2
#define RFM95_CS      4
#define RFM95_INT     3

// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);

// Blinky on receipt
#define LED 13

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);

  Serial.begin(115200);
  while (!Serial) {
    delay(1);
  }
  delay(100);

  Serial.println("Feather LoRa RX Test!");

  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);

  while (!rf95.init()) {
    Serial.println("LoRa radio init failed");
    Serial.println("Uncomment '#define SERIAL_DEBUG' in RH_RF95.cpp for detailed debug info");
    while (1);
  }
  Serial.println("LoRa radio init OK!");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
  if (!rf95.setFrequency(RF95_FREQ)) {
    Serial.println("setFrequency failed");
    while (1);
  }
  Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);

  // Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on

  // The default transmitter power is 13dBm, using PA_BOOST.
  // If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
  // you can set transmitter powers from 5 to 23 dBm:
  rf95.setTxPower(23, false);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);

    if (rf95.recv(buf, &len))
    {
      digitalWrite(LED, HIGH);
      RH_RF95::printBuffer("Received: ", buf, len);
      Serial.print("Got: ");
      Serial.println((char*)buf);
       Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(LED, LOW);
    }
    else
    {
      Serial.println("Receive failed");
    }
  }
}

look at your while (!rf95.init()) code closely ... what happens if the radio is not ready when that code is executed?

so it gets stuck. I've replaced while(1); with delay(1000);  but now it just repeats the same error haha. I kind of thought the example would work out of the box, providing the wiring was ok.

Scrap that, i was looking at a different example. Your suggestion seems to have work! Thanks

Newbie here. I'm also getting same error after connecting RFM9x LoRa module with Arduino. What did you do to address this error? I can't seem to understand the suggested way in while (!rf95.init()) part of the code. Thanks in advance...


text:
USB FT232 driver on M1 mini
I've scored a couple Nanos with FT232RL chips but can't see them on my brand new M1 mini. Can someone point me at how to determine whether v11.1 supports this USB chip?
It appears that the device is being instantiated but the Arduino IDE gets no response to the Get Board Info.
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    AR0JT9YB
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02214000 / 20
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

Executing the ioreg mentioned by @st2000 gives;
+-o Root  <class IORegistryEntry, id 0x100000100, retain 31>
  +-o AppleT8103USBXHCI@00000000  <class AppleT8103USBXHCI, id 0x100000291, registered, matched, active, busy 0 (1676 ms), retain 328>
  | +-o Extreme SSD@00200000  <class IOUSBHostDevice, id 0x10000081d, registered, matched, active, busy 0 (219 ms), retain 132>
  +-o AppleT8103USBXHCI@01000000  <class AppleT8103USBXHCI, id 0x100000295, registered, matched, active, busy 0 (4 ms), retain 39>
  +-o AppleT8103USBXHCIFL1100@02000000  <class AppleT8103USBXHCIFL1100, id 0x1000006eb, registered, matched, active, busy 0 (1220 ms), retain 494>
    +-o Keyboard Hub@02100000  <class IOUSBHostDevice, id 0x10000071c, registered, matched, active, busy 0 (164 ms), retain 30>
    | +-o Apple Keyboard@02120000  <class IOUSBHostDevice, id 0x100000805, registered, matched, active, busy 0 (162 ms), retain 32>
    +-o 4-Port USB 2.0 Hub@02200000  <class IOUSBHostDevice, id 0x100000730, registered, matched, active, busy 0 (826 ms), retain 46>
    | +-o 4-Port USB 2.0 Hub@02230000  <class IOUSBHostDevice, id 0x100000785, registered, matched, active, busy 0 (11 ms), retain 42>
    | +-o 4-Port USB 2.0 Hub@02220000  <class IOUSBHostDevice, id 0x100000791, registered, matched, active, busy 0 (16 ms), retain 43>
    | | +-o Backup+ Hub@02223000  <class IOUSBHostDevice, id 0x1000007dc, registered, matched, active, busy 0 (6 ms), retain 41>
    | +-o 4-Port USB 2.0 Hub@02210000  <class IOUSBHostDevice, id 0x10000079d, registered, matched, active, busy 0 (776 ms), retain 43>
    | | +-o FT232R USB UART@02214000  <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
    | +-o 4-Port USB 2.0 Hub@02240000  <class IOUSBHostDevice, id 0x1000007b6, registered, matched, active, busy 0 (12 ms), retain 42>
    +-o 4-Port USB 3.0 Hub@02600000  <class IOUSBHostDevice, id 0x100000749, registered, matched, active, busy 0 (231 ms), retain 46>
      +-o 4-Port USB 3.0 Hub@02620000  <class IOUSBHostDevice, id 0x10000075e, registered, matched, active, busy 0 (170 ms), retain 43>
      | +-o Backup+ Hub@02623000  <class IOUSBHostDevice, id 0x1000007c3, registered, matched, active, busy 0 (155 ms), retain 41>
      |   +-o Backup+ Hub BK@02623100  <class IOUSBHostDevice, id 0x1000007ee, registered, matched, active, busy 0 (147 ms), retain 131>
      +-o 4-Port USB 3.0 Hub@02640000  <class IOUSBHostDevice, id 0x100000763, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02630000  <class IOUSBHostDevice, id 0x100000775, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02610000  <class IOUSBHostDevice, id 0x1000007a9, registered, matched, active, busy 0 (16 ms), retain 42>

Which does not appear to contain the device afai can see. Any know if this means a new device for Big Sur is indicated as per Majenko♦ ?

@Majenko - You've just added the answer to the edit which I did, which had already added, and formatted, the answer. I suggest rolling back to edit #2 :-) Also, w.r.t. my two declined flags, now RowanP's comments, on the (now deleted) answer, can't be seen. They should be moved to this question.

A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.
A (Linux) example of lsusb:
$ lsusb
Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

I would do this with and with out the Arduino FTDI chip connected and look for the difference. This stackexchange question/answer contains how to do this on a MAC or use other MAC commands to do the same.  As pointed out in the comments the more native MAC command is:
ioreg -p IOUSB

Note, if you have fake FTDI chips there was a time when the FTDI driver that Windows ran would brick the fake FTDI chip. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.

On OSX the equivalent command is ioreg -p IOUSB

Thanks @Majenko.

As an addendum to @st2000's answer, it's worth noting that OS X comes with a basic driver for FTDI built in. However if your device uses a non-standard VID or PID it will not work.  At the time of writing this, according to this forum thread, FTDI have not yet written an updated driver for Big Sur, and seem to be struggling to do so (they have been writing one for the past year and still haven't managed it).
This should not apply to an Arduino that uses an FTDI with default settings, but worth noting for some custom devices.

I run macOS Big Sur on M1 silicon (a new machine installed in the last month) and also  FT232RL interfaces (e.g., cheap HW-417-V1.2 unit). I just went back through my downloads used in setting up the machine, as far as I can recall I did not have to download the FTDI driver which I used to on the previous older machine. This supports @Majenko's answer regarding a built in driver. I read a little more about this here. If anyone can point to more information about the built in driver that would be awesome.
I use ls /dev/cu.* in a terminal window to check which USB devices are plugged in. Mine shows up as /dev/cu.usbserial-A5XK3RJT
On the macOS desktop, the [Apple Icon]\About this Mac\System Report\USB information (which I think is a GUI representation of the ioreg mentioned above?) shows the device as:
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    A5XK3RJT
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02240000 / 17
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

If non-standard PIDs or VIDs are causing devices to be blocked, then a possibility (which I have not tested) might be just to reflash the config on the FTDI device see: dangerousprototypes - how to get a nicely named serial device.
Use ls /dev/cu.* in a terminal window to see if the device is showing as a call-up USB device. Then in Arduino IDE rather than using "Get Board Info", just set Tools/Port to that USB port and try to upload a sketch. The port should show up as /dev/cu.usbserial-AR0JT9YB or similar.
The FTDR device is in the ioreg output you posted, I believe it's hiding there as:
FT232R USB UART@02214000 <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>


text:
Mac Big Sur don't recognize generic Wemos D1 MINI PRO based ESP-8266EX
I bought one of theses cheaps & generic Wemos D1 MINI PRO with ESP-8266 to make a system to connect my lamp with google home etc.
But the problem is to upload the code into wemos. The Arduino IDE do not recognize the USB port that is connected.

When I connect to my Mac the board flashes the blue LED, so I suppose that it's not dead or something.
I've tried 5 different cables e nothing. I've read some articles about drivers to install but is only for Sierra or High Sierra.
Also, uninstalled and installed the arduino IDE.
I installed the ESP8266 Boards in the Boards Manager.
I tested it out with an Arduino UNO board and it recognized normally.
I have no idea what to do. I don't have a windows PC in my house to test it out, as well.
Here the pics of the board:

Make sure you are using a proper USB cable, charging cables don't have the data pair wires

You need the CP210x drivers from here.

Just installed and didn't work. :( Rebooted the mac and checked for "systemextensionsctl list | grep -E '(silabs|cp210x)'" on terminal, it says that is activated enabled and the arduino IDE doesnt show the connected port.

@capanema, Do any new devices show up under /dev when it's plugged in?

@timemage yes, i have 1 arduino uno and 1 nano and both show up!

@capanema, so they show up under /dev but not in the Tools/Port menu?

@capanema Uno and Nano use a different interface chip. Does the D1 show up in /dev?

I'm wondering specifically what dev name is showing up.  In the past, at least, the IDE has been selective about what names it recognises as valid ports.


text:
What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser?
I found this code sample from the FSBrowser (Flash File System) example in the ESP8266WebServer library:
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));

I was a bit confused at what F() and FPSTR() do, so I looked up the source (WString.h) and found this:
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))

Which raised more questions. How does this code work and what does this added complexity gain over just using char* or String as is?
EDIT: Added Metrics
Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

With F()
Without F()
Difference

RAM Used
29,488 bytes (36.0%)
29,792 bytes (36.4%)
+304 bytes

Flash Used
355,312 bytes (34%)
355,188 bytes (34.0%)
-124 bytes

Total (uncompressed)
359,472 bytes
359,344 bytes
-128 bytes

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.

On the ESP32 (as well as most 32-bit boards), the macros are nothing but a cast, on AVR-based boards (i.e. Arduino Uno), special low-level functions are required to read data from flash. The macros are hiding this difference from the user, so that the code can be written such that it compiles and runs on both platforms.

@PMF thanks for clarifying the use case. Does that mean I don't need to use F() or FPSTR() in my own code if I only plan on using the ESP8266?

I think not, but it may still depend on the compiler (it may still do a copy from Flash to Ram on bootup). You can find out by adding/removing a few F()'s and check the resulting RAM usage (last line of the compiler output). If it doesn't change, you don't need it.

On the ESP8266 for sure, F() macros can save heap space.

@dandavis Thanks! I added an edit with some metrics. The code author sometimes uses F(), sometimes FPSTR(), and sometimes neither. What is a good criteria to decide when to use each approach?

it will save more ram with longer strings, like web page error messages for example. Use F() pretty much only on string literals.

The purpose of the PSTR() macro is to configure the string to be used directly from flash memory. The string is then not loaded to dynamic memory at runtime as it would be without PROGMEM specifier set by the macro.
The purpose of the FPSTR() macro is to cast a string to 'dummy' FlashStringHelper type to help compiler choose the right overloaded function if dynamic memory and flash memory version of a function is available. An example would be the print function.
The F() macro combines this two macros. It makes the string a PROGMEM string and casts it to FlashStringHelper.

Thanks for the reply! How does FlashStringHelper help function overloading? Does it cast itself to either a dynamic string or flash string depending on its input parameter?

@DV82XL, PROGMEM string is const char* too. in C there are functions like sprintf_P for PROGMEM strings , but Arduino decided to use a special 'dummy' type for the PROGMEM string and uses print(const char*) for normal string and print(flashstringhelper*) for PROGMEM string. there is no Serial.print_P in standard Arduino API (some cores have it). to use the right function the C++ compiler evaluates the parameters of functions with same name https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/cores/arduino/Print.h#L65


text:
How do I power a linear actuator at different speeds for specified periods of time
I am new to Arduino and wondering if anyone can help me get it programmed correctly. I am using two buttons to control a linear actuator to open and close a barn door. I want it to go a certain speed for a specified period of time... like 3 seconds. Then I want it to slow down and go another 2 seconds. The linear actuator does not have feedback which is fine for the application because it does not have to be precise. Below is the code I copied from the manufacturers website - it works well, but I can’t figure out how to make it go for specified periods of time. Please remember I’ve never used an Arduino before and this is literally a foreign language to me. I’m just hoping someone can tell me what to do. It’s for my house, not for a school project.
*** ADDENDUM - Thanks for the help. Wish I could post a video... Here is the final code:
/* Firgelli Automations
 * Limited or no support: we do not have the resources for Arduino code support
 *
 * Program enables momentary direction control of actuator using push button
 */

int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int RPWM2 = 5; //connect Arduino pin 5 to IBT-2 pin RPWM
int LPWM2 = 6; //connect Arduino pin 6 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 0; // Top speed you can change it between [0-255]
int speed2 = 0; // Low speed you can change it between [0-255]
int speed3 = 0; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(RPWM2, OUTPUT);
  pinMode(LPWM2, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM, 255); // rotate motor with top speed (with PWM set to 255)
    analogWrite(LPWM2, 236); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(LPWM, 185); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 181); // rotate motor with low speed (with PWM set to 150)
    delay(1600);               // wait for x sec
    analogWrite(LPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(LPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1400);               // wait for x sec
    analogWrite(LPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(LPWM2, 0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(LPWM2, 0);
    analogWrite(RPWM, 254); // rotate motor with top speed (with PWM set to 255)
    analogWrite(RPWM2, 255); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for x sec
    analogWrite(RPWM, 170); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 170); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 80); // rotate motor with low speed (with PWM set to 150)
    analogWrite(RPWM2, 80); // rotate motor with low speed (with PWM set to 150)
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(RPWM2, 0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM2, 0);
  }
}

you will need to implement a state machine sketch ... https://duckduckgo.com/?q=arduino+fsm&ia=web ... also, examine the blinkWithoutDelay example sketch to learn how to time events in a non-blocking way, so that the program can respond to button presses, and releases, while the door is moving

start by making a list if all possible states that the door has ... for example, closed, open, closing fast, closing slow, stopped in middle .... assign a number to each state ... draw a chart and indicate what happens at each state and what causes the transition from one state to another state ... https://www.instructables.com/Arduino-Traffic-Lights-Using-Finite-State-Machines/

You can do this easily by using Arduino built-in PWM function and using delay function. But remember that using delay in your code will block your code so if your program just want to sit and wait for 3 seconds at some speed then delay is ok for you else you need to implement Millis function.
first you need to define different speeds as per your requirement remember PWM function has value from 0-255 where 0 in min speed and 255 is top speed.
So here I will define speed1 for top speed and speed2 for low speed
So now your program will look like this
int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 255; // Top speed you can change it between [0-255]
int speed2 = 150; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(LPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(LPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
   // analogWrite(LPWM,0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(RPWM, speed1); // rotate motor with top speed (with PWM set to 255)
    delay(3000);               // wait for 3 sec
    analogWrite(RPWM, speed2); // rotate motor with low speed (with PWM set to 150)
    delay(2000);               // wait for 2 sec
    // analogWrite(RPWM,0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
  }
}

Excellent! Thanks for your help! Eventually I may want to use millis () but for now this works pretty dang well. Will post final code as addendum above.

Good to hear that chris.


text:
BLDC motor erroneous running with digital potentiometer
I am using this digital potentiometer http://www.farnell.com/datasheets/31917.pdf to control a BLDC motor with Arduino Mega. When I am running the below code, the motor runs at the lowest speed when I am setting i = 0 in forward() function.
const int CS = 10;
const int INC = 9;
const int UD = 8;

void setup() {
  pinMode(CS, OUTPUT);
  pinMode(INC, OUTPUT);
  pinMode(UD, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(INC, HIGH);
  digitalWrite(UD, HIGH);
}

void forward() {
  for (int i = 0; i <= 100; i += 10) {
    setResistance(i);
    delay(10);
  }
}

void loop() {
  forward();
}

void setResistance(int percent) {
  digitalWrite(UD, LOW);
  digitalWrite(CS, LOW);
  for (int i = 0; i < 100; i++) {

    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(UD, HIGH);
  for (int i = 0; i < percent; i++) {
    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(CS, HIGH);
}

The problem is when I set the value of i in the forward() function to 70 or 80 the motor runs sometimes at a much faster speed but other times when I upload the code with the 70/80/any value other than 0, the motor doesn't move at all. When i is set to 0, the motor runs every time at a super slow speed but for other values it sometimes moves at a faster speed, other times it doesn't move at all.
I am not sure what is causing this issue. Please help.

it is difficult to guess the information about the motor and about how it is connected to the arduino

BLDC describes a family of motors, it is (Brushless Direct current) motor. Some have the sensors internal, some supply communication signals, some supply just phase etc.  Anything at this point would be a SWAG until more information is supplied.


text:
Resolved: ESP8266 works when arduino UNO reset pin is grounded
I'm setting up PIR and esp8266 with arduino UNO.
First my esp8266 doesn't work after alot of research my esp8266 start working when I put arduino UNO reset pin to ground.
But now my arduino UNO does not run any program and I'm not able to use PIR with this wifi module.
Any help will be appreciated

Only one extra thing is that reset pin is set to GND pin.

Show how you have all of this wired together.

I've added wiring image to question please check. Only one extra thing is that reset pin is set to GND pin

Please check the specs on your ESP8266 module.  The IO pins are not 5V tolerant.  That would explain the problems you are having.  I see you are powering it from 3V3 but the Uno's GPIO pins are all 5V.

The RESET of the UNO puts the ATMega328P (the MCU of the UNO) into an electrically inert state when it is connected to GND.  It is not supposed to be running your sketch when it is being held in reset.  It is, roughly speaking, electrically disconnected from everything else on the board.  This allows you to use the UNO as though it were a USB to TTL serial cable.
If you want to be able to run a sketch on the UNO while it uses the ESP8266, you'll need to not hold reset to GND and you'll also, practically speaking, need to choose a different set of pins for communicating with it, as D0 and D1 on the UNO are the same signals used to for the ATMega328P to talk to the host and used for programming the UNO via its bootloader.  On the UNO, you'd instead need to use SoftwareSerial (or something similar) and pins other than D0 and D1.  [Update: see the original poster's own answer containing the guide they ultimately used, making use of SoftwareSerial on pins 10 and 11]
The ESP-01 can run Arduino sketches using the ESP8266 Arduino core and it may make a great deal more sense to not involve the UNO at all, and instead connect the distance sensor more or less directly to the ESP8266.

Thanks for the quick reply, can you send me any link to blog or youtube tutorial to setup it up like you said

I don't have any links for you offhand.  But you're likely to find some if you look for people using UNO together with the ESP-01.  You'll notice a lack of grounding reset, and the use of SoftwareSerial or something else to do the communication from the UNO to the ESP-01.  You should keep in mind that these parts do not run at the same voltage, so you need to be careful with interfacing them.

Ok, I tried few solutions with software serial as I remember and I got no response in my serial monitor. I'll check if can find something more similar. Thank you

If the only things connected to the UNO are PIR sensor and the ESP-01, I strongly encourage you to move the sketch code onto the ESP-01 and find a tutorial on using one of those PIR sensors directly with the ESP-01.  esp-01 and  "PIR sensor" as search terms turn up a number of probably useful articles.  If I get a look at them later to vet one, I may integrate it into the answer.

I've posted answer with link to blog that helped me resolve issue. Thank you for moving me in right direction

So, I got it working with this information on this blog
Few things, my serial.begin(115200) where as in blog its 9600
Thanks @timemage for moving me in right direction
[1]: https://medium.com/@cgrant/using-the-esp8266-wifi-module-with-arduino-uno-publishing-to-thingspeak-99fc77122e82


text:
DigiSpark attiny85 computer not detecting
I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.
I am trying on a Windows 10 machine.
I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip
I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.
I tried different cables. I tried to install the drivers on another computer and the same thing happens.
What should I try next? Am I missing other drivers?

You can make the Device Manager to show unconnected devices (or whatever term it uses, I don't have an English Windows). Check there for the device.

Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers.  You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't stay recognised or that it isn't recognized as a serial device.  If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.
I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is expected behaviour:

In addition remember the Digispark only shows up as a programmable
device for 5 seconds, after that it will start running its code (when
it is new and un-programmed this means it will blink) and disappear or
act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it would continually reconnect for 5 second intervals.  They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it.  But then you got this from ebay, so who knows what they did or did not put on it.  I haven't studied the micronucleous bootloader enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed.  If it is unprogrammed then it is probably nop-sliding, for lack of a more appropriate term, right back into the bootloader.
You're not going to see it recognized as a serial port device like a typical Arduino.  The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.
Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch.  After which it should blink the LED.  If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.

You are correct. I was following a youtube video and the video was showing something else. Went to another tutorial and the device behaves as it does with mine.


text:
ESP32 preferences. One error returned, all others work. SOLVED
I am using the Preferences.h library in my Arduino code. I initialize some values. I save them with the preference library. I then modify all the values, then read back the original saved values.
All the values, except one, are restored with the associated get instruction. The one still shows the modified value. I can't see why it is wrong.
Can someone point out my error with calibratedWeight? And if you see some other general errors with the code, please point them out. (I'm not a programmer)
#include <Preferences.h>

Preferences preferences;

int currentFile = 1;
int outputRate = 10;           // milliSeconds
float outputGain = 1.23;
int zeroWeight = 900;          // dac value to produce Zero on scale
int calibratedWeight = 2800;   // dac value equal to 100lb calibration weight.
float DACmultiplier = 20.1;

//---------------------------------------
void savePreferences() {
    preferences.begin("ScaleSetup", false);      // false for read/write
    preferences.putInt("currentFile", currentFile);
    preferences.putInt("outputRate", outputRate);
    preferences.putFloat("outputGain", outputGain);
    preferences.putInt("zeroWeight", zeroWeight);
    preferences.putInt("calibratedWeight", calibratedWeight);  // ???
    preferences.putFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//---------------------------------------
void getPreferences() {
    preferences.begin("ScaleSetup", false);        // false for read/write

    currentFile = preferences.getInt("currentFile", currentFile);
    outputRate = preferences.getInt("outputRate", outputRate);
    outputGain = preferences.getFloat("outputGain", outputGain);
    zeroWeight = preferences.getInt("zeroWeight", zeroWeight);
    calibratedWeight = preferences.getInt("calibratedWeight", calibratedWeight);  // ???
    DACmultiplier = preferences.getFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//============================================
void setup() {
  Serial.begin(115200);
  Serial.println();

  preferences.begin("ScaleSetup", false);        // false for read/write
  preferences.clear();
  preferences.end();
  delay(90);

  savePreferences();
  Serial.println("\n save preferences");
  Serial.println("\n Original asigned values. \n");

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n modify values. \n");

  currentFile = 5;
  outputRate = 50;           // milliSeconds
  outputGain = 0.45;
  zeroWeight = 1333;         // dac value to produce Zero on scale
  calibratedWeight = 2200;   // dac value equal to 100lb calibration weight.
  DACmultiplier = 12.34;

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n Get original saved preferences. \n");
  getPreferences();

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

//  Serial.println("Restarting in 10 seconds...");
  delay(10000);
//  ESP.restart();
}

//============================================
void loop() {}

The following is the result.
 save preferences

 Original asigned values.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2800
DACmultiplier: 20.100000

 modify values.

currentFile: 5
outputRate: 50
outputGain: 0.450000
zeroWeight: 1333
calibratedWeight: 2200
DACmultiplier: 12.340000

 Get original saved preferences.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2200
DACmultiplier: 20.100000

I don't see anything wrong with your code, but then I'm not familiar with this library.  begin() appears to return a success/fail and various put function can return short values on failure.  Just as a sanity check, I would make sure all these are returning expected values.

I wonder if I corrupted something earlier and it is messed up now. I thought the preferences.clear(); function might fix that if it was the problem. I will try and test for success/fail somehow. Thanks for looking at this.

i would debug this kind of a problem by renaming calibratedWeight to abc123 just to see if it is related to the name

When I change it to abc123 it returns the correct value. Then when I change all the abc123 back to calibratedWeight it then does not work, it returns the same result I originally showed. I think changing it to abc123 made a new entry rather than overwrite calibratedWeight. And when I went back to calibratedWeight the problem remains. But I thought preferences.clear(); should have cleared everything.

I changed preferences.begin("ScaleSetup", false);   to preferences.begin("Scale_Setup", false);   I was sure this would fix it, but I get the same result.

Maybe I need to Reboot Windows. :)

I'm sure I know what the problem is. 16 characters when 15 characters is the maximum allowed.

"Note: Namespace name is limited to 15 chars"  I don't understand Namespace, but I guess the same applies to variable names. It works with a 15 character name.

You're allowed to post an answer to your own question.

So, did this preferences.putInt("calibratedWeight", calibratedWeight); return 0?

I was about to try that but I had thought about the length. I still want to do a couple of tests, but at the time I was more concerned about getting the rest of my code done. I will post more later.

At the end of the comments above I said I thought the problem was with the variable name length.
Today I tried the debug option and then ran the code. And the following error message was included in the com output.
[E][Preferences.cpp:163] putInt(): nvs_set_i32 fail: calibratedWeight KEY_TOO_LONG
So I guess I was right. I didn't know anything about the debug option before.


text:
How to control speed of 28BYJ-48 stepper motor without using library?
Iam using 28byj-48 stepper motor and I want to know how to control its speed without using any library. I got to know that we need to add delays in between steps but I don't know how much delay I need to add and how delay effects the rpm. It is very much helpful if anyone suggest me how to do this.

start by examining the blinkWithoutDelay example sketch that is included with the Arduino IDE ... it will teach you how to execute events at intervals without blocking the rest of the code

A stepper motor always needs a driver. As the ULN2003 (or similar) driver is normally shipped together with the 28byj-48 motor, I will assume, that you have this driver.
The ULN2003 has 6 pins:

Vcc and ground need to be connected to your power source. Note, that it is risky to connect Vcc to the 5V pin of the Arduino. While that might work, when there is no load on the motor, a loaded stepper motor can draw rather high currents. Letting these current run through the Arduino might fry the voltage regulator or the power switching diode. High currents should always flow past the Arduino, not through it.

The other 4 pins (which are marked as IN1 to IN4 on my ULN2003 driver board) are for controlling the phases. You need to connect these 4 pins to 4 individual digital outputs on your Arduino. As these are the phases of the stepper motor, you need to activate them in the correct order. You have this pattern
  1000
  0100
  0010
  0001

for full steps, and this pattern
  1000
  1100
  0100
  0110
  0010
  0011
  0001
  1001

for half steps. Each digit of each number represents the status of the corresponding phase; 1 means activated/HIGH, 0 means deactivated/LOW. To move the stepper motor forward, you move in the list of phases down. To move backwards, you move up in the list.

When using a stepper motor, the speed is determined by the number of steps per time interval. Let's assume, we want to use delay(), which is really easy, though not recommended (see explanation below), we can do steps and delay() inbetween:
void loop(){
    step();
    delay(10);
}

This code would do a step and then delay for 10ms. Thus we have about 1 step every 10ms. With 64*64=4096 steps per revolution (the motor itself seems to have 64 steps; additionally there is a gear with ratio 64 mounted on it; this might be different for you) we get a full revolution every 4.096s. When you use half the delay(), the speed will be double: with 5ms delay we get a full rotation every 2.048s. So you can use the delay() to set the speed of the motor.
Now we need the step() function, that I used above. There are multiple ways of writing this in code. I would propose to put the pins and phases into arrays and iterate through them with a static variable, which holds the current position in our phase pattern. Something like this:
//in global scope defining the pins for the phases
int stepper_pins[4] = {2, 3, 4, 5};

void step(bool forward){
    const uint8_t phase_pattern[][4] = {
        {1,0,0,0},
        {0,1,0,0},
        ...
    };
    static uint8_t current_step = 0;
    if(forward){
        current_step = (current_step + 1) % 4;
    } else {
        current_step = (current_step - 1) % 4;
    }
    for(uint8_t i=0;i<4;i++){
        digitalWrite(stepper_pins[i], phase_pattern[current_step][i]);
    }
}

We hold the phase pattern in a 2-dimensional array. The variable current_step is declared static, so it will keeps its value between the executions of the function. Then - depending on the parameter forward - we increment or decrement the current step and take that value modulo 4 (the number of phase patterns). That ensures, that current_step stays in the index range of our phase pattern array and will wrap around from the end of the pattern to the start and vice versa. After that, we loop through the 4 stepper pins and set them according to the current element in the phase_pattern array. You can easily adept that code for half steps.
Note, that this code is totally untested. Also this can be reached with way less code (at least for full steps), but I think this code is better understandable.
Now: Why not using delay()? This function will block the execution of other code. In that time the Arduino is just fiddling thumbs. In general that is considered bad practice. It is good, when you only need that one functionality and no responsiveness. But lets assume, you want to add a button, so that the motor reacts to your button presses. Long delay() calls will impact the responsiveness of your code. So instead you could use a non-blocking coding style. In the Arduino world this is easily done with the millis() function, which returns the number of milliseconds since startup and thus acts like a clock. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, and to the many tutorials on the web, that you can find with search terms like "Arduino millis tutorial" or something like that.

EDIT:

how your code controlling the motor speed?

The delay() call is determining the motor speed. If you want to change the speed, you need to change the value of the delay. You didn't mention any input device, so I just leave the speed constant. But of course you can define a variable for the delay and change that delay based on some input device. How exactly that is done depends on your requirements, mainly what type of input you want to use.

if we didn't specify any delays in between steps, will it spin at its max rpm?

When you don't use any delay, then most likely your code will run too fast for the motor. The driver will set the motor phases very very fast. So fast, that the motor cannot follow that (because it has a specific inertia). (Much like the wheels of your car can loose the grip on the street and spin without moving the car, the stator of the motor can loose the magnetic grip on the rotor, which leads to further rotating phases, but a rotor, that is standing still) So you reach the maximum speed before that and it depends on the motor, the driver, how much load is on the motors and how much current your power source can give you (I once tried to provide 3 of these motors with a 1A power supply, but they moved very weak, until I upgraded to a bigger power supply, that can provide about 5A, I think). You need to test yourself, how fast you can drive your motors. So try to lower the delays step by step, until the motor cannot move in your setup anymore. Then you have the minimum delay, and the maximum speed.
Note: The delay() function won't be accurate for very low delays in the single digit milliseconds. In that case you might wanna use delayMicroseconds(), which is more accurate in that range and also can get in you in the microsecond range.

Your explanation is wonderful,but how your code controlling the motor speed

And one more question,if we didn't specify any delays in between steps, will it spin at its max rpm?

@Akashbabutammali I added explanations for both questions in my answer.


text:
Public variable in class not incrementing
I'm not sure what is wrong with my code, but whenever I call addNewLine, the linesInserted variable is not updating correctly. When I print the value of linesInserted inside of the addNewLine method, it shows as incrementing, but when I print the value inside of the draw method, it shows that it is 0.
I have tried different increment operators (linesInserted += 1 and linesInserted = linesInserted + 1). Oddly enough, when I do linesInserted = 99 instead of linesInserted++, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

Is char** lines; ever initialized?

@timemage - Yes, there's a method that sets lines to (char**) malloc(sizeof(char*) * Char.sizeOfLines);. I'm in the process of converting this from a struct to a class so I haven't gotten around to creating a constructor yet.

I suspect you'll eventually find this is a matter of corrupting memory.  Without the full code probably away to execute it, there's not much chance of me personally finding anything.  Generally to have a better chance of getting help with this, I'd say provide full code to a cut down example that still shows the problem.  If possible remove the display code entirely from the example, because that dependency will severely limit the set of people that can reproduce your problem.  That said, you're likely to find the answer in the process of doing that.

You should re-think your whole strategy. It looks like you're making a wrapper for some graphical symbols made out of straight line segments. It would be far better to store the data statically in flash and just provide a pointer to it to your class. Then use the pgm_read_* functions to access the data. No need for any dynamic RAM allocation. No limit on the number of lines in a symbol (that count could be static and part of the symbol data). No messing with malloc.

@timemage - I didn't want to make this question long by posting the entire code, but then realized that Git is a thing. I guess that's what I get for posting this at 11pm lol. I edited the question with the repo added.

@Majenko - To be completely honest, I was already thinking about that. Just trying to make some code as a proof of concept before I moved everything to flash.

It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.
First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a char type variable for linesInserted and had a commented-out println(linesInserted);, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a , DEC) parameter to it (rather than casting) to coerce println into treating it as an int.
I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling malloc()/new 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're new-ing tiny four-character chunks.
Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.
The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                                 [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the malloc that I ran this under checks to see whether or the the stack pointer is within 128 (__malloc_margin) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to addNewLine was enough to cause malloc() via new to fail.  So you are indeed right on the edge.  And you have no checks to see if malloc or new returning nullptr.
You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.
I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if malloc() fails, apparently the new statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  As it exists in ArduinoCore-avr version 1.8.3, the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here

However, there's no facility to do that in 1.8.3.  The master as of writing appears to have addressed this, but that's not shipping yet.

The short answer to this is basically: Don't do that. That is:

Avoid dynamic allocation altogether where possible.

This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into PROGMEM, you also have some string literals that can be moved into flash by way of F().

To the extent that you're doing dynamic allocation requests:

Check to see that they're actually succeeding

Make as few requests as possible.

Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you not use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call abort() if malloc() returns nullptr, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.

I probably should have pointed out that the register file is memory mapped into the start of data space.  So, when malloc() fails underneath new char[4]{...} the more immediate effect of it continuing to attempt initialization is that of screwing up the general purpose registers, which will do who-knows-what from there; nothing good or terribly predictable.

I didn't realize new called malloc underneath. That would explain a lot honestly. I always forget that you don't have a lot of memory to work with on Arduino, so I think I'm just going to move to using flash or an SD card to store the information for the symbols at this point. Seems like it would be less of a headache anyways.

Yeah, new (with the excepting the "placement" version) is dynamic allocation in any case.  That the it uses malloc is an implementation detail; it needn't strictly be done that way.  It typically that is what happens though.  So far, it doesn't seem like you need an SD card; just look into using PROGMEM and the rest of pgmspace.h.  You may find it a bit confusing at first.

Moving all the graphics data over to flash helped a lot! I'm no longer facing issues. Took a little getting used to PROGMEM but it was definitely worth it.

It would be good to see how this is used rather than just having a class with no context.
But I'd start by removing unnecessary parts, like the display pointer, and you could always use a simple program, like ideone.com to compile quickly and check for errors.
As I read through it I see 2 flaws with memory management.
This block is using the size of a char pointer instead of a character. I don't understand what you want this code to do.
(char**) malloc(sizeof(char*) * Char.sizeOfLines);

Try something more like:
(char**) malloc(sizeof(char) * <numberOfCharsPerLine> * Char.sizeOfLines);

But then even though you're allocating memory for a whole block of lines, then each time you add a new one, you're allocating memory for a new line.
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

Instead try something like:
lines[linesInserted - 1][0] = startX;
lines[linesInserted - 1][1] = startY;
...

what is wrong with assigning arrays to items in array of pointers?

Assignment isn't the problem. The problem is that he's using a malloc operation to alloc the entire set of lines, but then allocating again each line individually. It's like allocating an entire chessboard, and then ignoring your chessboard, and allocating each row independently as you fill it. You either allocate the board, or each row. Not both.

you say those are pointers what OP allocates and then you show how to allocate it at once. or am I reading it wrong?


text:
I Can't Connect to my MQTT server via arduino
I have mosquitto MQTT installed on my VPS server which I can subscribe and publish to it using paho client thorugh websockets. However when I tried to connect to it through Arduino, I get the following error:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I uploaded the following code to arduino:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "IOT";
const char* password = "11112222";
const char* mqtt_server = "burooq.com";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
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.mode(WIFI_STA);
  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("test", "hello world");
      // ... and resubscribe
      client.subscribe("test");
    } 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();

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

i checked my server mosquitto ports which shows
mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP 127.0.0.1:1883 (LISTEN)

I checked my conf file and it has
listener 1883 localhost

so how what's wrong within my code or settings that prevents me from connecting to my server?`

does it work from other computer then the server?  what is burooq.com?

@Juraj yes I can connect to using websocket from my computer. for burooq.com it is my server domain

is 'your' computer other computer then the server computer?

This is the problem:

mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP
127.0.0.1:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1.  That will accept local incoming connections only but nothing from another IP address.
The IP 127.0.0.1 is the LOCAL ONLY IP address.  You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.
Check your mosquitto.conf file and look for the line that begins with "bind_address":
listener 1883 localhost

change this to:
listener 1883 0.0.0.0

and restart your MQTT server.


text:
How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?
I'm trying to understand this circuit found here.

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

Your confusion lies in what can "supply" power.
Your assumptions are all correct for an IO pin. However the Arduino has more than just IO pins. It has power pins.
These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.
So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.
The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).

I thought that even the power supply circuit provides 40 mA. I guess I'm wrong there. I tried connecting the DC motor and the Arduino directly at first across the 5V and my Arduino got disconnected from the PC. I thought that this was some kind of current protection inside the Arduino which caused the disconnect and I didn't push it further,  which finally brought me to the article I linked. I understand my mistake now. Thanks!

Official Arduinos and most clones have a "polyfuse" in series with USB bus voltage.  Typical USB hubs including root hubs also have over-current protection as well; something usually more sophisticated than a polyfuse.  It's entirely possible that your motor uses more than the current Majenko states above, particularly when spinning up or stalled.  You may be tripping one or the other or both.  The instinct to not tax Arduino and USB port is a good one.

BTW, the 500mA for usb I quoted in my answer is the nominal rating of the polyfuse.


text:
Weak Arduino output pins
I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.
However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.
Should the basic digital output pins be able to run fairly small drone motors like mine?

"Should the basic digital output pins be able to run fairly small drone motors like mine?" -  lol, no, I don't think so. Before powering any electronic component, you should make really sure, that you don't exceed current limits. I guess you haven't checked, how much current your motors draw? It will save you a lot of frustration to be very careful and always check current limits first. And ocrdu is also right with the flyback diode.

The Absolute Maximum is 40 mA per pin, but you shouldn't go even close to that; max. 20 mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200 mA.
Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.
Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.

Time to purchase another Arduino or use the other pins. Before you connect the new one you need to get a method of driving the motors. Keep in mind they are inductive and will reverse polarity and kick back a voltage that will keep rising until adsorbed. If you will be reversing them pick a MOSFET bridge to drive them. If just on/off/PWM pick a Logic rated avalanche rated N-Channel MOSFET with a high enough voltage and current rating. If your Arduino is 3V3 you need to be sure the gate will be on at about 2.5V. Connect all the grounds together and connect the source of the MOSFET to ground as well. Place something in the 25-50 Ohm resistor from the Arduino pin to the Gate of the MOSFET. Then connect the motor to the drain and the appropriate + supply. No diodes need as it has one built into the MOSFET designed for this. If you want the MOSFET off place something like a 10K resistor from the Arduino pin to ground. Remember a Power Supply the Arduino is NOT! While you are waiting on the parts go through several tutorials on the arduino and motors. There are some good ones and some not so good.


text:
How can I execute two functions at the same time?
#include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}

When I run this code and send '2', the servo() functions start, but it includes a delay function.
Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts after the servo function. I want to start this at the same time.

then send 3 ...

You have to check for a new instruction in the servo function too, e. g. before and after delay(5000) and splitting it into a while loop running one thousand times delay(5) and checking if there's a new instruction.

Make little task using millis function.
// GLOBAL VARIABLE
uint32_t taskMillis = 0;

....

// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.
https://www.youtube.com/watch?v=v5SpPXMmHJE
I hope this anwser will help you.

The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)
The answer is to rewrite your code to use millis() instead of delay. You record the current millis() value, and compare the new time to millis() to see if enough time has passed.
For the most part you should stop using the delay() function and forget exists. It will get you into trouble.
Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.


text:
Peculiar relay behavior from POST
I am trying to toggle on/off between two separate HTTP request.
One submit button to turn it on, and another separate submit button to turn it off.
I expect the device to launch in the off/low 0V position
digitalWrite(switchPin2, LOW);
The first submit button would turn the device on/HIGH/sw1, the second submit button would turn it off/LOW/sw2.
But what it is doing is at first nothing when the first/sw1 submit button is pressed but when I press the sw2 submit, I get serial output telling me that sw1 was just pressed. Then if I press sw2 again, it will tell me sw2 was just pressed but will not repeat the cycle until i press sw1 again. Then sw2 becomes functional, just performing the wrong function.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

const char* ssid = "ssid";
const char* password =  "pass";
int switchPin2 = 4;

//counter variable
int switch2;

String inString;

void webpage() {
  server.send(200,
          "text/html",
          " \
           \

Air conditioner manager
 \n\

Turn air conditioner on for "+String(switch2)+" ms
 \
           <form name='frm1 method='post'> \
            <input type='text' name='sw1' value=8000> \
            <input type='submit' value='Submit'> \
           </form> \

Turn air conditioner off for "+String(switch2)+" ms
 \
           <form name='frm2' method='post'> \
            <input type='text' name='sw2' value=8000> \
            <input type='submit' value='Submit'> \
           </form> \
           \
          ");
}

void response() {
  //add additional switch/relay here if adding new plug
  if (server.hasArg("sw1") && (server.arg("sw1").length() > 0)) {
    Serial.print("Switch 1 entered:\t");
    Serial.println(server.arg("sw1"));
    digitalWrite(switchPin2, HIGH);
    Serial.print("\nUnit is on:\n");
    int num = server.arg("sw1").toInt();
    ++switch2;
    server.sendHeader("Location", String("/"), true);
    server.send (302, "text/plain", "");
  } else if (server.hasArg("sw2") && (server.arg("sw2").length() > 0)) {
    Serial.print("Switch 2 entered:\t");
    Serial.println(server.arg("sw2"));
    digitalWrite(switchPin2, LOW);
    Serial.print("\nUnit is off:\n");
    int num = server.arg("sw2").toInt();
    ++switch2;
    server.sendHeader("Location", String("/"), true);
    server.send (302, "text/plain", "");
  } else {
    server.send(400, "text/html", "
HTTP Error 400

Bad request. Please enter a value.
");
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(switchPin2, OUTPUT);
  digitalWrite(switchPin2, LOW);
  WiFi.begin(ssid, password);  //Connect to the WiFi network
  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.println("Waiting to connect...");
  }
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP()); // Print the local IP
  // server.on("/body", handleBody); // Associate the handler function to the path
  server.on("/",HTTP_GET, webpage);
  server.on("/",HTTP_POST,response);
  server.begin(); // Start the server
  Serial.println("Server listening");
}

void loop() {
  server.handleClient(); //Handling of incoming requests
}

I get no error, only erratic output.
How do I toggle on/off between 2 submit buttons?
UPDATE: Serial output.
Waiting to connect...
IP address: 192.168.1.9
Server listening
Switch 1 entered:   8000

Unit is on:
Switch 2 entered:   8000

Unit is off:

are you able to toggle the relay with simple code?

Could you add the Serial output to your question? I do not really unerstand what you are doing (why "POST" request?), so maybe there is something wrong with he communication.

@jstola do you mean like in the sample code where it turns on for a second and then turns off? Yes. That's the code I started with. I'm just splitting that function in half.

@ridgy Just added

Seems like you pressed three times Switch 1 and then once Switch 2... Btw., there is a typo in your HTTML; missing ' in <form name='frm1 method='post'> after frm1 - is this also true in your original code?

Depending on your web browser, there may be a browser console (in Firefox: Developer tools -> Console) where you can see what your browser does send and what answer it gets.

@ridgy That was it! Now it works. A missing quote. Yeesh


text:
Real range of long range transceptor LORA RA-02 SX1278 with Arduino UNO
I'm working in a project where I have to send data from long distances (about 1 km) between 2 Arduinos UNO which are powered by computer's USB ports. The place is a small city with no large buildings. I have bought two transceptors LORA RA-02 SX1278 at 433 MHz with an antenna for this frequency, like this:

The results are dissapointing. I can reach 300-350 meters with a stable communication (1 data send every 5 seconds). I was only able to, only one time, receive a data from a 1.4 km distance, but the message was corrupt, like this:

I have tried:

Different programs and libraries (Now, i'm working with this library)
Frequencies from 410 MHz to 525 MHz, according to the range inscriptions on the module

But the distance is still far away from 1 km for a stable communication. I have seen some people reaching 2-3 km with this module and some documents say that it is possible to reach 10 km.
The question is, what am I doing wrong or what I should change to improve the results?
Any help or related experience is very useful!

how are the radios powered?

more over with what @jsotola asked, are you sure the voltage is not dropping when it transmits?

Rather than using that stubby antenna, which is compact but non-directional, you might consider a gain antenna (i.e. a directional one) instead.

If you haven't already, you should probably make use of setTxPower.  I doubt it will make the difference you're looking for, but it won't hurt.  The selectable bandwidth might also have an effect on range.

@chad-g The voltage is not dropping, also I have tried with a difference source of power and it works ok.

I think it could be something related with the antenna, as @jwh20 commented, but i should try first

@timemage thanks, I will try it