text:
Arduino and Processing- Conditionals only executing sometimes in response to IR codes
I am reasonably new to arduino and even newer to Processing so still struggle with trouble shooting my code.
The intention of my sketch is have Processing receive IR codes from the arduino and execute different AppleScript applications accordingly.
It works sometimes! However I would really love it to work all the time :)
-The AppleScript apps definitely work and have been successfully launched
-The processing monitor has been printing the 'Val' variable consistently
The issue is that even though processing is reading from the serial port and assigning the IR codes printed there to the 'val' variable, it only sometimes executes the conditional
I added a delay to my arduino sketch to slow down how much data was entering the port and make it easier for Processing to read but it's inconsistent.
Any help would be greatly appreciated!
Arduino code:
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>

int RECV_PIN = 10;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

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

Processing Code
import processing.serial.*;

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
String Down = "890";
String Up = "8188A2C8";
String CH1 = "E10";
void setup()
{
  // I know that the first port in the serial list on my mac
  // is Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  {
  if ( myPort.available() > 0)
  {  // If data is available,
  val = myPort.readString();         // read it and store it in val

   print(val);

    if(val.equals(Down) == true)
    {launch("/Applications/QlabDown.app");
  }
  if (val.equals(Up) == true) {
    launch("/Applications/QlabUp.app");
  }
  if (val.equals(CH1) == true) {
    launch("/Applications/CH1.app");
  }
}
}
}

what does this mean? Processing receive IR codes from the arduino .... how is Processing receiving infrared signals?

Assuming there are two Arduinos.  One running the "Arduino code" and the other running the "Processing code".  The "Arduino code" has the manditory setup() and a loop() functions.  But the "Processing code" only has the mandatory setup() function and is missing the loop() function.

Sorry for not being clear, the Processing sketch is being ran on my laptop and is receiving the IR codes via the USB serial port created when the arduino is plugged into the laptop.


text:
Serial communication from Arduino to ESP8266 NodeMCU works, but from NodeMCU to Arduino isn't working
My circuit connection is like: (I am following this tutorial)

Code uploaded to Arduino:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["data1"] = 100;
  root["data2"] = 200;
  if(s.available()>0){
    root.printTo(s);
  }
}

Code uploaded to NodeMCU:
#include <SoftwareSerial.h>
int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);
#include <ArduinoJson.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
}

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.parseObject(s);
 if (root == JsonObject::invalid())
   return;

 Serial.println("JSON received and parsed");
 root.prettyPrintTo(Serial);
 Serial.print("Data 1 ");
 Serial.println("");
 int data1=root["data1"];
 Serial.print(data1);
 Serial.print("   Data 2 ");
 int data2=root["data2"];
 Serial.print(data2);
 Serial.println("");
 Serial.println("---------------------xxxxx--------------------");
}

Arduino sends JSON data and NodeMCU parses it as expected.
--------Till this everything is fine. ---------
But my requirement is vice versa. When I create JSON object in nodeMcu and try to parse in arduino, JSON not received.
This time I wrote this code in nodeMcu:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

int D5 = 14, D6 = 12;
SoftwareSerial s(D6,D5);

void setup() {
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
}

void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.createObject();
 root["data1"] = 100;
 root["data2"] = 200;
 if(s.available()>0){
   root.printTo(s);
 }
}

And code in Arduino:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);

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

void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
  if (root == JsonObject::invalid())
    return;

  Serial.println("JSON received and parsed");
  Serial.print("Data 1 : ");
  int data1=root["data1"];
  Serial.println(data1);
  Serial.print("Data 2 : ");
  int data2=root["data2"];
  Serial.println(data2);
  Serial.println("---------------------xxxxx--------------------");
 }

This code doesn't work. I don't receive anything in serial monitor of arduino.
The circuit connection remains the same as before.
Anymore information should I provide ? What modification do I need?

maybe try a smaller buffer

you require a common ground connection

@jsotola, but I also tried that. Moreover, without ground connection : data comes from arduino to nodeMcu. Then why I need ground ?

@Juraj , how ? And , if data comes from arduino to  nodemcu without changing buffer, do I really need to change in case of nodeMcu to arduino ?

the 1000 bytes buffer is too large for 2kBytes RAM of Uno

@Juraj what is a allowable value ? Do I need to change SoftwareSerial.h or HardwareSerial.h ?

StaticJsonBuffer<1000> jsonBuffer

The problem may stem from Arudino boards being 5v logic pins while ESP boards are 3.3v logic pins.  3.3v high might not be enough for Arduino to see the data.

source: Stack Exchange

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

sort: votes


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

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

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

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


text:
Serial.read() doesnt work in IF statement
I am working with an XBee module, so naturally, I started my void loop with AT command testing.
void loop() {
    digitalWrite(Sleep_Rq,LOW);

A +++ with a guard time of 1 sec before and after it, sets xbee module in command mode.
delay(1000);
xbeeSerial.write("+++");              // Enter Command Mode
delay(1000);

This part of the code, puts the serial data into string variable x in the form of a String.
while(xbeeSerial.available()) {
    x = xbeeSerial.readString();
}

Serial.println() is returning OK onto the serial monitor.
Serial.println(x);

But when I compare x with OK nothing happens, 1 doesn't appear on the serial monitor.
if(x=="OK")
  {
   Serial.println(1);
  }
}

I tried swapping "OK" with 4F4B (ascii equivalent of OK), 20299 (decimal value). I also  tried changing datatype of x from String to word and compared x with 0100111101001011.
I also tried changing the IF condition as,
if(Serial.println(x)=="OK")
    {
     Serial.println(1);
    }

and many more techniques with no luck to be found.

X is probably not "OK" but "OK\n" or "OK\r" or even "OK\r\n".  Read: https://majenko.co.uk/blog/reading-serial-arduino

@Majenko, you should post that as an answer so the OP can accept it and everybody can tell that the question has been answered.

@DuncanC I don't know which of those is the actual fix... Also I'm busy...

Oh, sorry, I didn't mention. The correct one is "OK\r".

Possible duplicate of String compare when using Serial

Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".
However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (\r) and/or Line Feed (\n). Different devices use different combinations.
As it turns out the XBee uses '\r' as the line ending marker.
There are two ways of dealing with it:

Include the line ending in your comparison ("OK\r"), or better,
Incorporate the line ending in the reading.

The second point there involves the use of readStringUntil():
String x = xbeeSerial.readStringUntil('\r');

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.


text:
How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)?
The following source code is from the official ESP8266 website(Explanation provided): https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html
This .ino code returns the html code of the server name mentioned in "const char* server" declaration, on to the Serial Monitor.
And Yes, this code perfectly returned the html codes of wwww.google.com, www.arduino.cc etc. But when I try it with my 'led blinking.html' I am unable to find any luck. I guess it is because the website should be hosted on a live server.
Other Details:
1. uC Board: Wemos D1 mini (An ESP8266 Variant)
2. I am using Xampp to run Apache server and MySQL
3. Wemos board is set up as a WiFiClient
#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "xxxxxxxx";

I have put the html,php code of the website in the directory : C:/xampp/htdocs/LED BLINKING/led blinking.html
IP Address of my Windows PC: 192.168.100.9
const char* server = "192.168.100.9/LED BLINKING/led blinking.html";

I tried with just "192.168.100.9"; too.
I also unblocked the windows firewall for my ApacheHTTP Server. Now I can view the webpage on my mobile with the URL: 192.168.100.9/LED BLINKING/led blinking.html.
void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  WiFiClient client;

  Serial.printf("\n[Connecting ...");
  if (client.connect(server, 80))
  {
    Serial.println("connected]");

    Serial.println("[Sending a request]");
    client.print(String("GET /") + " HTTP/1.1\r\n" +
                 "server: " + server + "\r\n" +
                 "Connection: close\r\n" +
                 "\r\n"
                );

   Serial.println("[Response:]");
    while (client.connected())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');
        Serial.println(line);
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

The output on Serial Monitor is:
Connecting to ssid connected
[Connecting connection failed!]

Variable server is a hostname or IP address for TCP connection.
The /LED BLINKING/led blinking.html goes after HTTP GET. Now there is / and it worked for main page of servers.
You need
client.print(String("GET /LED%20BLINKING/led%20blinking.htm") + " HTTP/1.1\r\n" +
             "server: " + server + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

and you must escape the space


text:
The right way to find and understand the libraries
I am working on a project to send sensor values from esp8266's Wemos D1 mini to MySQL.
I tried using the library MySQLconnection.h but I couldn't make it to connect to wifi. So I uploaded a simple program to connect the board to WiFi using ESP8266.h but I got the error that Unable to compile for Wemos D1 board.
Please tell me the right procedure to select the right library for the problem defined.

are you trying to program the ESP or an AVR connected to an ESP? if ESP directly, modify the examples to get started, they are well-documented and easy to adjust.

https://gist.github.com/pudelosha/5a42092bbcf0bfc9ddab20e6093e68b7 is a good example that might help you.

see examples in IDE File menu.  the ESP8266WiFi library. ESP8266.h is an empty library that exists only for included examples.

You should break your problem down into simple parts, which it seems you are on-track to do. Your ultimate goal appears to break down into the following sub-tasks (not in order):

Read sensor value
Connect to a WiFi network
Connect to a MySQL server
Send sensor data to MySQL database

You are unlikely to find a single library to do all of these tasks, but as progress in solving each step, any library that works is the "Right" one, in general. Choose a library that solves an individual task.
You say you tried to upload a simple program to only connect to WiFi, but that it did not compile. The clue to why it did not compile will be found in the actual compile error message. If you can update your question with the error message and the code to the simple program, you can get some guidance from the users of this site to solve that problem.

Okay, I will follow the above methodology. But what I wanted to know is that whether Arduino website provides a systematic approach to select libraries in their website (Although I didn't find anything there). Means that instead of googling the library, a more reliable way to do it.

I find the Arduino website to not be a good source of "what's available" for external libraries. The ones that are documented are often under-documented.

Ok, cool. Btw I just reuploaded the simple ESP8266 program and it worked. Thank you for suggestions.

But how can I know what are all the functions, objects available in a library?

Typically the best way is to find and read the source code of the library.

sources of information are examples in IDE in File menu,  "More info" link in Library Manager in Sketch menu in IDE, repository on GitHub, ...


text:
DC Motor Control L298N
I am trying to control the speed of two motors using L298N. I use "Arduino Nano ATmega 168". I change the analogWrite between 0-255 but I cannot see any difference. When I assign it to something like 120 the motor stops.
The pwm pins of the motor drive is connected to the 7th and 8th pins of the Arduino. My code is like that:
const int in1=9; //motor 1
const int in2=10;//motor 1
const int in3=11;//motor 2
const int in4=12;//motor 2
const int p1=7;//pwm pin for motor 1
const int p2=8; //pwm pin for motor 2

void setup() {
  // put your setup code here, to run once:
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
pinMode(in3,OUTPUT);
pinMode(in4,OUTPUT);
pinMode(p1,OUTPUT);
pinMode(p2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  analogWrite(p1,255);
  analogWrite(p2,130);
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  digitalWrite(in3,HIGH);
  digitalWrite(in4,LOW);

}

PS:

My Arduino and Motor Shield have same the ground
I use a power supply and not a battery.

I would be happy if anyone could help me)

const int p1=7;//pwm pin for motor 1
const int p2=8; //pwm pin for motor 2
PWM pins on a '168 are 3,5,6,9,10,11

I see. On the internet I also saw many writing to connect them to the PWM pins of the board but when I searched "Arduino Nano PWM pins" i could not get a relevant answer. I think that would work. Thanks so much!


text:
L298N Gradual Voltage Drop
I have connected my motors to L298N and it in turn to arduino. My battery is ~18 V and i used a boost converter to get 12.99V. When I run my program on Arduino Mega, I check the output voltage from the motor drive and observe that it begins from somewhere 11.99V and goes gradually down like 11.70,11.63,11.55..... till 4.03 V then it does not go down. I am attaching my circuit as a photo here. I hope sonebody could help me to find my mistake

Are you measuring voltage across motor's two terminal?

@Fahad yes, I measured voltage on the output of the motor driver. So without connecting the motor. But even when I connect the motor to the drive the motor begins to turn and because of the gradual voltage drop it stops then.

How about voltages on battery and buck converter? What happens if you wire logic levels to run the motor directly (without arduino)? Anyway you should count with the voltage drop on transistors used inside of L298 and they are two of them for single motor...

@KIIV the battery voltage is near 17.65V and on the output of the buck converter i get 12.99 V. Motors work directly connected to battery very well. And for the L298N there should be max 2 V drop. But it drops gradually until 4 V

So, voltage drops even without connecting the motors?

@Fahad yes, exatly

The connection diagram is correct. It's either a faulty L298 or buck converter. When the voltage drops to 4v check the voltage across buck converter. If it's still 12v, you know what to change.

@Fahad okay, that is a good way of determining the problematic part in the circuit.Thank you !


text:
DC Motor Car Steering
I am working on a project with a 3-Wheel Car: 1 Custer Wheel, and 2 DC Motors. I need to steer the car playing with the speeds of these two dc motors. If I would supply a constant voltage and current to the DC motors, is there an equation or maybe a source to know the exact degree of turning by assigning PWM to a certain value? Let's say I want to turn the car 30 Degrees to the left from the straight direction. Can I do calculations to find all of the PWM values or it can only be got through experiments?
Thanks in Advance!

you cannot turn a motor a known amount without some kind of feedback

As my experience in RC robots as yours, you Can't, simply because the speed of the car rotating varies from a surface to another, on ceramic flat surface the robot will turn so fast,but on a carpet for example the robot will rotate slowly even the signals and the voltages were Similar.

As @jsotola said, you would need a feedback, that means a sensor which tells you the angle of your car in order to reach the angle you want, for example use a magnetometer like the HMC5883L

Basically you can't. PWM value required to turn to a specific degree will depend on motors, on voltage, on hardware, in the current velocity of the car and probably on the surface under the wheel. Also keep in mind that real cars don't turn like that (at a fixed angle). Instead, driver constantly adjusts the position of the steering wheel, while looking at the road (i.e.a feedback system). Same is for RC cars, operator smoothly deflects the joystick looking at the vehicle.


text:
Is it possible to modify the animal tags (EM4305) with any module that works with Arduino? 134,2Khz
i have a lot of tags (Animal tags rounded yellow) EM4305, this have 15 spaces of memory and i need change ID writed, currently i'm using this module but it did not can possible write on tag, exist a similar function to Write() from EEPROM, i see that already exist external writers to EM4305, but, is only external?

Why are you linking to a google ad? Please provide a direct link to the module. And what are you talking about EEPROM? I really don't understand, what you mean there and with the "external"

What are the tags used for? In some places ID tags are used to track animals through the supply change and there could be legal consequences to changing the IDs.


text:
CC2541 Bluetooth AT Commands not work for any Commands sended from Serial
i bought the HM 10 Bluetooth controller (CC2541), i got connect on this device through Serial Bluetooth Terminal (Android App) with Serial BLE menu this method not requires any pass and "Connected" state is showed and the led on CC2541 is always HIGH now, but... any command sended from terminal or sended from serial arduino is not show and "AT+NAME" or "AT+NAME?" returns null everytimes, this is my code to run Bluetooth on Arduino Mega2560:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(26, 27); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  delay(500);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
}

void loop() // run over and over
{
  if (mySerial.available()) {
    String s = "";
    char c;
    while((c = mySerial.read()) != -1) {
      s += c;
      delay(10);
    }

    Serial.println("Received: " + s);
  }

  if (Serial.available()) {
    String s = "";
    char c;
    while((c = Serial.read()) != -1) {
      s += c;
      delay(10);
    }

    delay(10);

    Serial.println("Sent: " + s);

    mySerial.print(s);
  }
}

Example of output serial monitor:
Sent: AT+DEFAULT

Sent: AT+BAUD9600

Sent: AT+HELP

I never receive "Received" status...

Your serial code is really weird. Maybe you should instead directly use the typical Serial Passthrough Sketch, just with mySerial instead of Serial1 (and of course the initialization stuff of SoftwareSerial). Also: Are you sure, that the HM-10 module listens for AT commands at 9600 baud? Have you tried other baudrates?

I'm not sure about my CC2541's BAUD rate, why doesn't it accept AT + BAUD?
So I can't know what your BAUD RATE would be

For just accepting that command every time, it would have to read at every baudrate simultaneously. That's a bit too much to ask. The seller, where you have bought the module, should know the baudrate, that it is configured to. Look at the documentation of it. Or (in the case, that there is no documentation) you can test yourself and go through the list of common baudrates (the ones listed in the Serial Monitor). Though I think you could start above 9600 and go up, before trying others. Also SoftwareSerial has problems with the high baudrates (for example 115200), so you can stop there

I tried all BaudRates (But Serial Arduino is always 9600) and the response is equal... null

I tried change mySerial.begin to 9600
19200
38400
57600
115200
4800
2400
1200
230400


text:
How do I make my piezo buzzer only hum once without repetition?
I have a problem with getting my buzzer to only do the tones I programmed in once. I know I have to add some sort of code but I'm relatively new to this so I don't really know. I want it to start playing the tones I have in the code once I press the button. After that it should immediately stop, without looping everything until I press the button again. Basically I have these LEDs that light up in a row with every time I press my button and once the last LED lights up, the buzzer should play its melody. After that, I can press my button again and the whole thing starts from the beginning. If anyone could help, I'd be more than grateful!
This is my code:
#define button 3

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3,INPUT);
  pinMode (11,OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

  buttonPoll = digitalRead (3);
  if (buttonPoll ==1) {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0) {
      state = old + 1;
    }
  }
  else {
    delay(100);

  }

  switch (state) {
    case 1:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 2:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 3:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 4:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 5:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 6:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 7:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 8:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 9:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 10:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);
   old = state;

       tone (11,261);
      delay(250);

      tone(11, 330);
      delay(250);

      tone(11,391.99);
      delay(250);

      tone(11,440);
      delay(250);

      tone(11, 391.995);
      delay(250);

      tone(11, 330);
      delay(250);

        }

    break;

   default:
  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

    old = 0;

    break;

  }
}

Enshrine the first section of the loop() code inside a while loop.
while (condition)
{
    // this code executes continually until 'condition' is true
}

In your case, the variable state changes when an active button press is recorded: use that as your condition.
while (state == old)
{
  buttonPoll = digitalRead (3);
  if (buttonPoll ==1)
  {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0)
    {
      state = old + 1;
    }
  }
  else
  {
    delay(100);
  }
}

So long as state stays the same, i.e. it equals old, the code within the while loop will execute indefinitely.
NOTE: Any code outside the while loop will effectively only run once. You may find, if you expand the code, most of it lives within the while loop. If that is the case there may be better approach to consider.

Thanks so much for your help! I really appreciate it!

I'm so glad you took the effort to answer me. Unfortunately, I've tried it out and the outcome was the same as before. Thanks anyways though!

Oh! You forgot to add noTone(11); at the end of the different tones! You will also need to reset state to zero when you reset old to zero, otherwise you will get stuck in an infinite loop.

Oh my gosh thank you so much!!! You have no idea how much you've helped me! I am so grateful for your help.

Welcome to ASE :)

You have mapped the Tone function and the LED to the same Pins. So, you may have to find another pin for the buzzer (pin 0 )
I have taken code from @charlieHanson as well.
The braces for the switch statement were put in the wrong place. I have fixed it.

Have a try: The code is here
#define button 3

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3, INPUT_PULLUP);
  pinMode (11, OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED, LOW);
  digitalWrite(threeLED, LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

  while (state == old)
  {
    buttonPoll = digitalRead (3);
    if (buttonPoll == 1)
    {
      delay (50);
      buttonPoll = digitalRead (3);
      if (buttonPoll == 0)
      {
        state = old + 1;
      }
    }
    else
    {
      delay(100);
    }
  }

  switch (state) {
    case 1:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, LOW);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 2:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 3:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 4:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 5:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 6:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 7:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 8:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 9:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, HIGH);
      digitalWrite(tenLED, LOW);
      old = state;
      break;

    case 10:
      digitalWrite(LED, HIGH);
      digitalWrite(twoLED, HIGH);
      digitalWrite(threeLED, HIGH);
      digitalWrite(fourLED, HIGH);
      digitalWrite(fiveLED, HIGH);
      digitalWrite(sixLED, HIGH);
      digitalWrite(sevenLED, HIGH);
      digitalWrite(eightLED, HIGH);
      digitalWrite(nineLED, HIGH);
      digitalWrite(tenLED, HIGH);
      old = 0;
      state = 0;

      tone (11, 261);
      delay(250);

      tone(11, 330);
      delay(250);

      tone(11, 391.99);
      delay(250);

      tone(11, 440);
      delay(250);

      tone(11, 391.995);
      delay(250);

      tone(11, 330);
      delay(250);
      noTone(11);

      break;

    default:
      digitalWrite(LED, LOW);
      digitalWrite(twoLED, LOW);
      digitalWrite(threeLED, LOW);
      digitalWrite(fourLED, LOW);
      digitalWrite(fiveLED, LOW);
      digitalWrite(sixLED, LOW);
      digitalWrite(sevenLED, LOW);
      digitalWrite(eightLED, LOW);
      digitalWrite(nineLED, LOW);
      digitalWrite(tenLED, LOW);

      old = 0;

      break;

  }
}

Here is the preview :)

Here is the Arduino simulator link: https://wokwi.com/arduino/projects/297098737606459913

Wow, thanks so much!!!

Once the LEDs & Piezo sequence finishes, your code doesn't wait for the button to be pressed again. If the button is not pressed, the code doesn't wait, it merely delays for 100ms, then repeats the sequence.


text:
ESP32-S2 Brownout Detector Randomly Triggered in Deep Sleep
I have thoroughly searched for answers on this over the past couple weeks, and have not been able to find a solution for Arduino.
I'm using an ESP32-S2-Saola-1M Dev board that needs to store a sensor reading in RTC memory, go to sleep for 5 min, and then wake up again and store another reading. Every few hours, it shares its data and starts over.
The issue I'm having is that about 2/3 of the devices I have will randomly wakeup with a POWERON event instead of from the timer, and all of the RTC memory is lost. From searching online, this seems to be a hardware issue that causes the brownout detector to trigger incorrectly.
The accepted solution in the esp-idf is turning off the brownout detector , but this doesn't seem to be implemented in the ESP32 Arduino core, and using code I've found for turning off the brownout detector in Arduino causes constant brownouts rather than turning the detector off.
There seem to be solutions if I switch my development environment, but I'd rather not do that at this point in development. Has anyone had luck fixing this issue in Arduino?


text:
Can I use an accelerometer to measure the velocity of a car in a curve?
I am making an application that is used to measure the velocity, it has an accelerometer that measures the component acceleration in the XYZ-axis. When the car is moving just straight the measurement is ok, as only linear components are involved.
My doubt came when the car is on a curve, I am not sure if the accelerometer can measure correctly in such situation or if it is necessary to apply a gyroscope to measure any missing component.
The code snippet for measure the total acceleration is shown below, I measure the acceleration in each axis and I remove the gravitational to finally calculate the velocity and the speed
    float AccTotal_X = ((AcX - grav_X)*9.81);
    float AccTotal_Y = ((AcY - grav_Y)*9.81);
    float AccTotal_Z = ((AcZ - grav_Z)*9.81);

    float Vx = vx_0 + AccTotal_X*dt;
    vx_0 = Vx;
    float Vy = vy_0 + AccTotal_Y*dt;
    vy_0 = Vy;
    float Vz = vz_0 + AccTotal_Z*dt;
    vz_0 = Vz;

    speed_dt = sqrt(pow(Vx,2)+pow(Vy,2)+pow(Vz,2))*3.6;

What hardware are you using? Most accelerometers also include turn sensors. But there's a great range in quality of these things, from very inaccurate for $5 to highly accurate for $60000.

Note that the gravity only acts in one direction. You don't need to multiply with the gravity in all axes.

@PMF, I am using the MPU5060, it has both accelerometer and gyroscope, however, I am justing using the accelerometer to measure the acceleration linear to get the velocity.

@PMF about the gravity being multiplied in all axis is because depending on the inclination of the sensor on the plane, the gravity will be present in one or more axis

@GustavoDaSilvaGhedim Are you getting accurate results? Accelerometers usually have bias and noise which usually make them unsuitable to compute velocity by integrating their readings.

@Sacha for straight moviments the results have good accuracy, however, the problem comes when the vehicle is turning left or right, during such a situation the difference between reading and the true velocity is considerable

That's sure right. But you have to know which direction is down. Typically, that is obtained when the device is in a standstill.

You're probably better off on the physics (or maybe maths) stack, since you're getting into the realms of integrating angular acceleration and other complex topics that are far outside the realms of this stack.

I think the last line of the Wikipedia page on angular acceleration sums it up nicely: "In conclusion, the general relation between torque and angular acceleration is necessarily more complicated than that for force and linear acceleration"

Yes, you need the gyroscope. You can't determine the radius of the curve with the accelerometer only, but that is critical.

@SimSon, thank you for the answer, but do you know how could I represent it in the equation or which source could I find it, most sources that I read the just represent the linear case, there was none explaining about the the linear and circular in the same case

As long as the car does not slip or drift, the rotation angle of the car (gyroscope) equals the angel it passes around the curve's center. The same applies to angular velocity and acceleration. The equation is centripetal vs momentum: ma=mv^2/r or a=w^2*r

I found out the answer to the question in the following article SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments
According to the article

When a vehicle makes a turn, it experiences a centripetal force, which
is related to its speed, angular speed and turning radius. Thus, by
utilizing the accelerometer and the gyroscope, we can derive the
tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.
The equation to measure the tangential velocity is:
v = Rω (1),
Where v is the tangential speed, R the radius of the curve and ω the angular speed.
As the centripetal acceleration is given by a = ω²R (2), reformulating (2) and substituting in (1), it is obtained:
v = a/ω (3).
Both a and ω are given by the accelerometer and the gyroscope respectively.


text:
Initial setup print getting cut off from printing
I am writing a program in Python (using PySerial) that needs to read data from the Arduino quickly. For this reason I have set the serial timeout to 0.01 seconds. (Baud rate is 115k) If I don't set the timeout this low I run into issues with there being a noticeable delay between sending a command and receiving a reply. As long as I have the timeout set low enough then its all fine, but the downside is that I have a message print out when I first connect to the Arduino to confirm that it has indeed connected. (Message reads "Connected" once the serial connection has been established in void setup)
Okay, the problem: If I don't have the timeout set to 0.9 seconds or higher, the initial 'connected' message gets cut off. Of course if I have it set that high I get the issues I first described.
I'm looking for a way to keep the timeout very low but also get this first connected message when the void setup runs. Is there a way to have my cake and eat it too?
I did try starting with the timeout set to 1 second and once the connected message prints out change it to 0.01 seconds, but it just kept giving me an error.
Any help would be appreciated.

If you can send a character to mean “end of message” (typically CR and/or LF), then you will not need timeouts.

you can always check available() or change the timeout. but I am not sure if I understand what you do


text:
How to use pins for I2C that is used from other hardware?
I am using ESP32 CAM for one project and I have a sensor that is I2C connected to pins 21 and 22 (default I2C). The sensor is working fine until I turn on the camera. The camera uses this pins (21,22) as input output, not for I2C communication. When I try to read the sensor data in the loop I can't reach the sensor. I want to check the sensor data mainly and if there is some indication from the sensor to turn on the camera.
 How I can make this redefinition of the pins in the main loop?
I did try to declare the pins with  Wire.begin(21,22, 100000); in the loop but is not working.

Wire.begin(21,22, 100000); declares the pins 21 and 22 ... you already said that they interfere with the camera

Unfortunately I can't change the pins. The board have modifications and this are the only free pins. I am looking more for a solution where I can switch between the camera and the sensor without restart.

Well, if two different hardware devices are connected and want to input on both, the devices may or may not allow a software solution and you may need to add hardware logic to arbitrate them. Without knowing the details of your current HW design, it's hard to offer much specific advice. if the HE doesn't provide a way to arbitrate, it's poorly resigned.

Posting a schematic,not a frizzy thing would go a long way in solving your problem.

You didn't provide any code or schematic, so it is hard to provide a specific solution to your problem. One thing worth trying is to create a function getSensorReading() and only create the Wire instance Wire.begin() within the function so that it get out of scope at the end of the function. On your comment "I can't change the pins", well, ESP32 does provides two I2C ports, you could try Wire1.begin(14,15, 100000);.

Does this answer your problem? Especially the comments to my answer.


text:
Strange cyclic errors in analogRead on Nano
I am trying to build an emergency shutdown of a gas valve based on the output of a smoke detector.
It basically measures the voltage on the buzzer of the smoke detector, and if high enough, changes the direction of the motordriver, which is  connected to an actuator (with automatic shutdown) that operates the gas valve.
A button is used to reset the alarm.
The actual setup is soldered on a prototype board, but below the layout as a breadboard.

The nano is powered by a step down converter connected to the 5V pin, that in turn is powered by the 12V power supply that also drives the actuator. Its output is 5.13V according to my multimeter, and seems stable when I measure it.
The problem I have is that the system continuusly enters alarm state.
After some experimenting I have found out that when I short the analog pin to ground, I always read 0, but when I use a resistor, as in the breadboard layout, I get a couple of 0 readings, then a sort of peak, that goes back to 0, and that behaviour in a cycle of approximately 10 sec.
The cyclic pattern is consistent, the values differ depending on how I power the system (external of from the USB of my PC), and whether I connect the smoke detector or use the resistor.
Below the code (I left out the utility functions for brevity), and the output when I use the 100k resistor between A2 and ground, with the board powered by the USB connection.
Can anyone explain what is going on here?
void setup() {
  bool storedAlarm;

  initOutput(activeLedPin);
  initOutput(alarmLedPin);
  initOutput(gasValveIn1Pin);
  initOutput(gasValveIn2Pin);

  EEPROM.get(0,storedAlarm);
  alarm = false;

  Serial.begin(9600);
  Serial.print("start with Alarm ");
  Serial.println( storedAlarm ? "ON" : "undetermined" );

  digitalWrite(activeLedPin, HIGH);
  blinkAlarmLed(500,333,3);

  if (storedAlarm) {
    switchAlarmOn();
  }
  // never switch off automatically
  // if the valve is open it will stay open
}
void loop() {
  int sensorValue = analogRead(sensorPin);
  bool reset = digitalRead(alarmResetPin);

  Serial.println(sensorValue);
  if ( sensorValue > 500 ) {
    switchAlarmOn();
    if (reset) {
      blinkAlarmLed(100,100,7); // show refusal
    }
  }
  else if ( reset ) switchAlarmOff();

  delay(800);
}

Output:
14:01:08.587 -> start with Alarm ON
14:01:11.061 -> alarm
14:01:11.367 -> 36
14:01:12.148 -> 35
14:01:12.963 -> 9
14:01:13.778 -> 0
14:01:14.559 -> 0
14:01:15.374 -> 0
14:01:16.155 -> 0
14:01:16.970 -> 0
14:01:17.784 -> 0
14:01:18.564 -> 0
14:01:19.380 -> 0
14:01:20.161 -> 0
14:01:20.974 -> 0
14:01:21.787 -> 17
14:01:22.568 -> 62
14:01:23.383 -> 65
14:01:24.162 -> 67
14:01:24.977 -> 54
14:01:25.791 -> 137
14:01:26.570 -> 104
14:01:27.385 -> 29
14:01:28.165 -> 17
14:01:28.980 -> 0
14:01:29.795 -> 0
14:01:30.575 -> 0
14:01:31.390 -> 0
14:01:32.171 -> 0
14:01:32.986 -> 0
14:01:33.801 -> 0
14:01:34.581 -> 0
14:01:35.397 -> 0
14:01:36.178 -> 0
14:01:36.993 -> 37
14:01:37.809 -> 64
14:01:38.589 -> 69
14:01:39.404 -> 64
14:01:40.184 -> 34
14:01:40.997 -> 136
14:01:41.811 -> 120
14:01:42.592 -> 46
14:01:43.406 -> 16
14:01:44.187 -> 8
14:01:45.003 -> 0
14:01:45.784 -> 0
14:01:46.600 -> 0
14:01:47.415 -> 0
14:01:48.196 -> 0
14:01:49.012 -> 0
14:01:49.793 -> 0
14:01:50.607 -> 0
14:01:51.422 -> 0
14:01:52.201 -> 0
14:01:53.016 -> 0
14:01:53.796 -> 0
14:01:54.611 -> 28
14:01:55.427 -> 53
14:01:56.208 -> 65
14:01:57.022 -> 72
14:01:57.803 -> 68
14:01:58.617 -> 73
14:01:59.432 -> 0
14:02:00.212 -> 140
14:02:01.027 -> 136
14:02:01.808 -> 101
14:02:02.622 -> 46
14:02:03.437 -> 22
14:02:04.218 -> 16
14:02:05.032 -> 8
14:02:05.812 -> 0
14:02:06.627 -> 0
14:02:07.409 -> 0
14:02:08.224 -> 0
14:02:09.038 -> 0
14:02:09.820 -> 0
14:02:10.633 -> 0
14:02:11.415 -> 0
14:02:12.231 -> 0
14:02:13.047 -> 0
14:02:13.828 -> 0
14:02:14.642 -> 0
14:02:15.422 -> 40
14:02:16.237 -> 73
14:02:17.050 -> 72
14:02:17.830 -> 65
14:02:18.644 -> 11
14:02:19.427 -> 131
14:02:20.240 -> 108
14:02:21.054 -> 61
14:02:21.834 -> 18
14:02:22.648 -> 14
14:02:23.428 -> 0
14:02:24.242 -> 0
14:02:25.058 -> 0
14:02:25.839 -> 0
14:02:26.654 -> 0

Please try to connect the resistor between A2 and Arduino ground as close as possible to GND pin.

Try it with a much lower value resistor. 100k is perhaps just too large

With a 20k resistor directly between the Pin and ground the cyclic behaviour is still there, although the max value is then 20.


text:
Weird sound when modulating the pulse width on Arduino
I'm trying to generate a pulse width modulated sound using Arduino Nano.
But it generates the weird sound unlike my expectation.
Here's my code:
class Phasor
{
public:
    Phasor(const float frequency)
    :frequency(frequency)
    ,phase(1.0f)
    ,lastTimeMicros(0){};
    virtual ~Phasor(){};
    void setFrequency(const float frequency)
    {
        this->frequency = frequency;
    }
    float process()
    {
        const unsigned long currentTimeMicros = micros();
        if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
        const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
        const unsigned long cycleDurationMicros = static_cast<unsigned long>(1000.0f / frequency) * 1000;
        if (elapsedTimeMicros < cycleDurationMicros)
            phase = static_cast<float>(elapsedTimeMicros) / static_cast<float>(cycleDurationMicros);
        else
            phase = 1.0f;
        return phase;
    }
private:
    float frequency;
    float phase;
    unsigned long lastTimeMicros;
};

class PulseOsc
{
public:
    PulseOsc(const float frequency, const float pulseWidth)
    :phasor(frequency)
    ,pulseWidth(pulseWidth){};
    virtual ~PulseOsc(){};
    void setFrequency(const float frequency)
    {
        this->phasor.setFrequency(frequency);
    }
    void setPulseWidth(const float pulseWidth)
    {
        this->pulseWidth = pulseWidth;
    }
    float process()
    {
        const float phase = phasor.process();
        if (phase <= pulseWidth)
            return 1.0f;
        else
            return -1.0f;
    }
private:
    Phasor phasor;
    float pulseWidth;
};

Phasor *phasorLFO;
PulseOsc *pulseOsc;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
    phasorLFO = new Phasor(0.1f);
    pulseOsc = new PulseOsc(440.0f, 0.5f);
}

void loop()
{
    pulseOsc->setPulseWidth(phasorLFO->process());
    int outVal = LOW;
    if (pulseOsc->process() > 0.0f) outVal = HIGH;
    digitalWrite(9, outVal);
}

The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)
What is wrong with my code?
How do I fix this? I would appreciate any advice.

Probably the Nano isn't powerful enough to do all those floating point calculations in a timely manner.

I see two issues with this program. The first one has already been
pointed out by Majenko in a comment: you are doing too much floating
point calculations. The second has to do with the way your Phasor
manages the time.
If you take a look at the Blink Without Delay Arduino tutorial, you
will see something along these lines:
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    toggle_the_LED();
}

In this code, interval is the minimum time between toggles. Whenever
the program gets a little bit late and currentMillis - previousMillis
is strictly larger than interval, this extra time is lost and the
program will be late for all the subsequent LED toggles. If instead of
the minimum you are interested in the average time between toggles,
then you should write:
if (currentMillis - previousMillis >= interval) {
    previousMillis += interval;  // <- advance by exactly one period
    toggle_the_LED();
}

Now, previousMillis is no more the time when the last toggle was
performed, it is the time when the last toggle was scheduled. With
this version you can still have some jitter, but at least the average
frequency should be right. If the program is so busy that it can get
late by a full period, then it would be better to replace the if by a
while, in order to catch up all the missed periods.
Your Phasor::process() method is a little bit more involved than the
tutorial above, yet the line
if (phase == 1.0f) lastTimeMicros = currentTimeMicros;

is going to get you out of schedule for exactly the same reason.
That being said, here is my take at your phasor idea, completely
untested:
class Phasor()
{
public:
    Phasor(float frequency_Hz)
    {
        period = round(1e6 / frequency_Hz);
        frequency = 0x10000 / period;
    }
    uint16_t process()
    {
        uint16_t now = micros();
        while (now - last_time >= period)
            last_time += period;
        return (now - last_time) * frequency;
    }
private:
    uint16_t period;     // unit = 1 us
    uint16_t frequency;  // unit = 1/(2^16 us) ~ 15.3 Hz
    uint16_t last_time = 0;
};

I changed a few things from your implementation:

removed the setFrequency() method because YAGNI
no floating point except in the constructor, for performance reasons
only 16-bit arithmetics, for the same reason
no division in process(), because division is expensive
the phase is not stored, because there is no use to storing it
the phase is an integer in units of 2−16 periods

Note that the unit chosen for the phase is the most natural one when
dealing with 16-bit arithmetics. Note also that storing microseconds in
16-bit variables only works for frequencies higher than 15.3 Hz. A
very low frequency phasor (your “LFO” for instance) would need 32-bit
arithmetics.

Seems like you are using the system clock micros() to  calculate elapsedTimeMicros, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.


text:
Is digitalWrite(pinnumber,LOW) different from ground pin
I am using Tinkercad simulator, but an unusual thing happened. When I connect one wire of dc motor to pin 9 with digitalWrite(9,HIGH) and other wire to ground, the motor runs with rpm of 5555.
void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, 1);
}

But instead if I connect the other wire to pin 13(say) and set digitalWrite(13,LOW) the motor runs at an rpm of 3846.
void setup()
{
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(9, 1);
  digitalWrite(13,0);
}

Can anyone explain this?

Tinkercad probably doesn't have an option to show smoke coming from your Arduino, which is what would happen if you tried to ground a motor through a pin set to LOW. DON'T DO THAT. As others have mentioned, It can't handle the current, and a motor is a "dirty" load that can push negative voltages into the pin through a process called "back EMF". (It is caused by the inductive coils in a motor. When you remove power from an inductor, the collapsing magnetic field causes a surge of current flowing backwards.)

Thank you, next time I'll use a motor driver

You can control a regular DC motor with a power MOSFET and a "flyback diode". A motor driver is overkill unless you have a servo or a stepper motor.

Yes, it is different.
First: Never run a motor directly from IO pins - you will damage your Arduino. Not only can a real Arduino not supply enough current, but motors generate a lot of back-EMF that will kill an Arduino.
Secondly a pin doesn't connect direct to GND or VCC - it is connected through a MOSFET that performs the switching.  That MOSFET has an ON resistance, which causes a voltage drop across it determined by the current being sourced or sunk through the pin.
You can read more about GPIO pins here.

Thank you, next time I'll use a motor driver

In the real world, either pin sinks current to Gnd via an onchip N-channel MOSFET. They will safely sink 20, 25mA. If your motor allows more than 40mA to flow, you risk damaging the pin and likely the whole chip.
Similarly, either pin can source the same current to a load, likely via P-channel MOSFET, with the same current limitations.
Using both together, you have one transistor sourcing current, one transistor sinking current, so you have twice the Rds (MOSFET on-resistance) limiting current to the load, hence the simulator might have the motor going slower due to less current being available.


text:
How Can I convert my arduino code to C/C++ embedded code
For example I have an code for arduino but I want to change it to embedded C to create more professional project with different hardware. is there any tutorial? I know the logic and the most of the codes are the same. I just wanna know about libraries or pin definitions for LCD and buttons.

Arduino code is already C, you can even use C++ constructs (some at least). Most libraries use already C++ classes for example. You are quite vague about 'different hardware'.

By different hardware I meant non arduino micro controller and customized LCD

non-arduino is sill very vague. Some MCUs don't offer a C compiler at all. Some offer a somewhat C compiler with weird syntax (PMS150C - I'm looking at you). You will have to be more specific that that. Tell us what hardware platform you are targeting and someone here will be able to give you an answer.

ATMega328P this is my MC target

Arduinos use a standard C++ compiler. The supposed "Arduino Language" doesn't exist; it is C++. Except that the Arduino IDE will permit you some shortcuts that the compiler doesn't. The two biggies are:

The IDE will notice that your are trying to use libraries (ones it recognizes, anyway) and insert the necessary #include <SOMELIBRARY.H>, if you didn't do it.
The IDE will notice when you make forward reference to a function not yet defined nor declared, and provide the necessary forward declaration.

But if you manage these for yourself, as you would have to in any other C++ environment, your code structure will be portable.
The remaining source of incompatibility is hardware dependence. Writing embedded systems software is almost always hardware dependent. It has to be dependent on the external hardware, and quite likely is dependent on specifics of the MCU. The latter dependencies can usually be written around. Function calls or direct references to the processor's I/O registers, for example, which, on another processor, will map differently, maybe even to memory addresses instead of to registers at all.
Another processor will very likely have an entirely different set of pins with different characteristics and capabilities from the original one. Libraries to drive external hardware will likely have been designed for a given processor or processor-family and may not map gracefully to another.
If processor independence is a design-goal of the project, then you'd probably define a hypothetical set of features that you'd expect all processors to share, and hand code for anything outside of that basic set. If you wanted to take advantage of certain features if they were available on a given processors, then, in addition to the hand-coded features you wish to have, you'd also provide conditionally compiled, optimized-for-the-processor code that you could enable when you compile for that processor, and disable for all others.

exactly I want to know what shortcuts Arduino gives me that other compilers don't

It's actually done by the IDE. The underlying compiler is a pretty plain vanilla C++ compiler. FWIW, I do what you're contemplating - write standard and complete C/C++. I don't actually port it much of anywhere; my primary purpose is to be able to use either the Arduino IDE or Eclipse/Sloeber, at will, and portable code is very effective to enable me to do that.

If you would to write more professional code, you could try to use a different editor instead the basic arduino editor.
Possible choices are, for example:

Visual Studio Core with platformio plugin.
Eclipse With Sloeber plugin.

Since arduino already use C/C++ Languange,  the only difference is the way you write and organize the code.

Amen! I am wondering if Arduino IDE 2.x will be based on something like VS Code with features that go beyond plain syntax highlighting.

In my opinion Arduino IDE should be very simple. If you need more that write a simple scatch, you can use other IDE already compatible with arduino.

The only thing that keeps me installing Arduino IDE is the board and library manager. As Arduino CLI doesn't seem to gain tracktion, this is unfortunately the easiest way to get startet with those. I wonder when Arduino-CLI will be stable and promoted on their page.


text:
What is difference between NodeMCU and esp8266?
Since I have no previous experience in electronics I'm getting quite confused while coming across these two terms ..I'd like to know whether they're the same or different.

From https://forum.arduino.cc/index.php?topic=616324.0:

NodeMcu is the name of the firmware originally for the ESP8266
  microcontroller, with support for the ESP32 microcontroller added more
  recently, that allows you to program these microcontrollers using the
  Lua programming language.
NodeMCU firmware was developed so that AT commands can be replaced
  with Lua scripting making the life of developers easier. So it would
  be redundant to use AT commands again in NodeMCU.

And ESP8266 is one of the microcontrollers supported by the NodeMcu firmware.
From NodeMcu vs Esp32 vs esp8266

In the early days of the hobbyist community's adoption of the ESP8266,
  ESP8266 development boards were marketed with the name NodeMcu and the
  term "NodeMcu" started to be associated more with the hardware than
  the firmware. It is common for people with no interest in the Lua
  programming language to buy "NodeMcu" boards and program them with the
  Arduino IDE, which erases the NodeMcu firmware from the board. To make
  things more confusing, multiple companies marketed boards with the
  name "NodeMcu", but with small hardware differences. Over time, the
  NodeMcu boards became less popular in the Arduino world because the
  similarly priced WeMos D1 Mini came out with the same functionality,
  but in a smaller form factor. Now, the "NodeMcu" name is being used to
  market ESP32 boards as well.

ESP8266 is a microcontroller with WiFi capability. it requires external flash memory and some antenna to work. There are different modules and development boards with this system. Some development boards use basic esp8266 modules and some integrate the chip, flash memory and the antenna on the PCB.
NodeMcu is a development board with esp8266 and a firmware with the same name. On the picture is a NodeMcu development board with an esp-12F esp8266 module soldered to the PCB of the NodeMcu. The development board adds required circuits around the module - boot configuration pull-up and pull-down and enable pin pull-up. On the board is an USB chip to connect the esp8266 to USB and an auto reset circuit to enable the upload tool to put the esp8266 into flashing mode. The 3.3 V power for the esp8266 is converted from the 5 V of USB.

The NodeMcu firmware is a Lua language interpreter and has nothing to do with Arduino, but the NodeMcu development board can be used as any other esp8266 development board.


text:
How can I burn the bootloader onto atmega328 (not atmega328p)?
Hi I bought some atmega328 chips (not to be confused with atmega328p). They are very similar but the atmega328p chips are just more power efficient, so I've read. Anyways, my goal is to burn the arduino bootloader onto these chips so that I can make some breadboard arduinos. I used the arduino ISP sketch and hooked up everything like so ->

I was following instructions from the following link ->
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
However, when I press the Burn Bootloader button under Tools, it keeps telling me that it can't verify that my chip is an atmega328p. Well it is not atmega328p but everywhere online says it does not matter since they are the same architecture. The error also tells me that I can override by typing -F, but it doesn't tell me where to input this. I'm pretty sure that may fix the issue, but I am not sure where I'm supposed to put the -F.
Also I saw another post that was similar to this one but the answer said that the problem is the atmega328 chip itself. Is it even possible to add the bootloader to these chips??? Other sources said it is, but I can't seem to do it.

use MiniCore https://github.com/MCUdude/MiniCore

How can I burn the bootloader onto ATmega328 (not ATmega328P)?

As Juarj commented, For a variety of standalone AVR microcontrollers you can add new "cores" to the Arduino IDE using it's board manager.
This provides the Arduino IDE with information about your specific chip and this means the IDE can instruct the avrdude program appropriately and select a bootloader image that was written to support your specific chip
The Minicore documentation says it supports all variants of ATmega328
Other well-known examples of cores for bare AVR microcontroller chips  include ATtinycore which supports a wide range of ATtiny microcontroller chips like the popular ATtiny85.

Oh wow thanks! I will definitely try this!


text:
Problem communicating with GSM module which is a Fona 3G from adafruit
My issue is fairly simple to describe but I have no idea what the problem could be. So I got my FONA 3G and immediately after taking it out of the box, I connected the battery and I wired up my FTDI board (aka USB to serial converter), and then I plugged it into my USB port to try and establish communication. I just tried the most basic at command AT(using PuTTy). You're supposed to get an OK in response but the FONA doesn't appear to even notice that I'm trying to talk to it. I type AT and press enter and nothing happens at all.
The issue is most certainly not my FTDI board, I'm very experienced communicating with wifi modules and other GSM modules using PuTTy. So please don't be concerned with the setup. That's 100 percent definitely not the problem.
I was able to send AT commands after plugging the module into my laptop directly using the module's USB input, but there is still some issue with its UART. I haven't been able to send or receive any communications directly from RX and TX. It wont respond to any programs I load up onto my arduino. Its like the UART is asleep.
If you have experience with FONA 3G, please speak up and tell me what steps you took to get the UART to respond. What should the status indicator look like before its ready to receive commands? Any knowledge you have about the FONA3G module would be helpful.
As a side note, the FONA3G has a chip number. It is SIM5320a. I don't know if that helps. Most people know it as FONA 3G.

If your Fona3G is not even reacting to Putty AT commands, you set everything up  perfectly there is only one possibility left. Power supply not sufficient or DOA -in that case let it replace by the seller or go to a repair store if its a used one

It's been my experience that when a poster is 100% sure that the problem doesn't lie in one particular area, about 50% of the time we end up finding the problem in that area.  Mostly because the OP has probably looked at everything else, but isn't looking where they're sure the problem isn't.  Look even experts make dumb mistakes and miswire something sometimes.  I surely doesn't hurt you at all to show that part.  It's amazing what another set of eyes can catch sometimes.  Smart folks get the details out when they want help.  It's foolish to hide things in a case like this.

Okay I realize thats a common thing. But I have never had issues like this with other devices. I'm experienced in working with the UART. Some devices need to be reset before they'll respond to AT commands. I was wondering if someone who has used this module before knows what the trick is to get it to respond. That's all.

All right. Thanks to those of you who posted comments. It turned out to be an issue with the baud rate! Its always the simple stuff. Adafruit said this thing has auto baud meaning you can use any baud rate but they are wrong. It requires 115200 to work properly. Also I'd like to point out that there was nothing wrong with my setup. Sometimes you should trust the person when they say their setup is 100 percent fine.


text:
Looking for light-weight Arduino OLED library that supports text and bitmaps
I'm trying to incorporate a screen into my Arduino code which is quite large already. The Adafruit SSD1306 library is overly large and has a lot of unnecessary things in it. I've found the SSD1306Ascii library which is great because it takes up barely any space, but I really would like to be able to display a bitmap logo on the screen. Does anyone know of a library that is light weight but still supports bitmaps?
Thanks.

Light-weight with bitmaps and your sketch is already large? Then need a newer Arduino board, for example one of the mkr series. Do you know these: https://github.com/olikraus The u8g2 library is large, and the 8x8 option has no bitmaps. The older U8glib is memory efficient but it is still large and it takes time to learn how to use it (because it is memory efficient it has a specific way to update the screen). What is so large about your sketch? Are you a beginner with programming? In the end you need another arduino board anyway, so it is easier to move to a new arduino board right now.

This is supposed to be a small implementation. https://github.com/nicoud/Oled
I have not used it, but it does look interesting. You can pick the bits that you need.
https://www.didel.com/OledLib.pdf


text:
esp8266 and arduino pro mini
I have few sensors. Temperature sensor (DHT22), flow rate sensor, rpm optical tachometer sensor and a rgb led.
I want to use adafruit IO to get values of these sensors and change the colour of the led.  Most of the tutorials online use a builtin WiFi module  but I want to do it separately. please guide me how to do it?
I am going to use esp8266 and  arduino nano.

Please read [ask] and How to ask a good question for Arduino Stack Exchange and then edit your question to suit.

Use tutorial for the esp8266 module to connect to Adafruit IO (MQTT). Then code the exchange of the data between Nano and esp8266 using Serial communication.
(You can test the Serial communication by sending lines to esp8266 from Serial Monitor and of course by showing the prints from the Nano.)
Consider using only esp8266 dev board like Wemos D1 mini or NodeMCU.

Why would you recommend using Wemos or NodeMCU ?

@Guy.D, instead of Nano+esp8266, only a esp8266 dev board


text:
Unwanted Wi-Fi Jamming by ESP8266
I bought an ESP8266-01 module. I attempted to upload following code onto it.
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println("I'm working");
Serial.println(millis());
}

Then I powered it and there was nothing in Serial monitor. Also my computer lost wifi connection. What's the cause of this error? How to solve it?

what baud rate do you have set in Serial Monitor?

Did the upload complete successfully? To upload, GPIO pin is required to be pulled HIGH; was it? A diagram showing how your ESP was connected for both programming and testing would help. About jamming the WiFi, could your PC see any WiFis? Do you have any other WiFi devices, and how were they affected? The more information you can provide, the better someone can help you find out what happened (or didn't happen).

@Juraj No matter which baud rate, there is nothing on the serial monitor.

@JRobert IDE said that it's uploaded successfully. Instructions stated that GPIO-0 connected to ground. Now I connected it to 3.3V, unable to upload new codes.

Solved:
I catched more details. ESP creates Wi-Fi network. It causes jamming.

I'm not sure what you mean by "jamming"; if you mean your computer auto-connects to the ESP, you can disable auto-connect on your computer. There's no issue w/ having multiple networks in the same room, though :)

The only way I've found to interpret this that could make sense is that you created a network with the same SSID as your existing network, such that some clients connected to ESP8266 when they should have been connecting to the proper network.

@timemage, with that sketch? AP starts by default on esp. esp with wrong content of RF calibration data area on flash can disturb other WiFi networks. it usually adjusts after a few resets. but it is better to clear the RF calibration data.

@Juraj, I have no idea what you're talking about.


text:
RFID and Keypad Based Door Lock Using Arduino
I'm new to the Arduino world and I have a question. I found this project to do but I need your help, I want instead of this servomotor to put an electromagnetic door lock, could you help me with the changes in the scheme and code to understand this process? Thank you very much! I leave the diagram and the code here.

#include <deprecated.h>
#include <MFRC522.h>
#include <MFRC522Extended.h>
#include <require_cpp11.h>

// Include required libraries
#include <MFRC522.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
#include <SPI.h>
// Create instances
LiquidCrystal_I2C lcd(0x27, 16, 2);
MFRC522 mfrc522(10, 9); // MFRC522 mfrc522(SS_PIN, RST_PIN)
Servo sg90;
// Initialize Pins for led's, servo and buzzer
// Blue LED is connected to 5V
constexpr uint8_t greenLed = 7;
constexpr uint8_t redLed = 6;
constexpr uint8_t servoPin = 8;
constexpr uint8_t buzzerPin = 5;
char initial_password[4] = {'1', '2', '3', '4'};  // Variable to store initial password
String tagUID = "19 7F 30 C2";  // String to store UID of tag. Change it with your tag's UID
char password[4];   // Variable to store users password
boolean RFIDMode = true; // boolean to change modes
char key_pressed = 0; // Variable to store incoming keys
uint8_t i = 0;  // Variable used for counter
// defining how many rows and columns our keypad have
const byte rows = 4;
const byte columns = 4;
// Keypad pin map
char hexaKeys[rows][columns] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
// Initializing pins for keypad
byte row_pins[rows] = {A0, A1, A2, A3};
byte column_pins[columns] = {2, 1, 0};
// Create instance for keypad
Keypad keypad_key = Keypad( makeKeymap(hexaKeys), row_pins, column_pins, rows, columns);
void setup() {
  // Arduino Pin configuration
  pinMode(buzzerPin, OUTPUT);
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  sg90.attach(servoPin);  //Declare pin 8 for servo
  sg90.write(0); // Set initial position at 90 degrees
  lcd.begin();   // LCD screen
  lcd.backlight();
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  lcd.clear(); // Clear LCD screen
}
void loop() {
  // System will first look for mode
  if (RFIDMode == true) {
    lcd.setCursor(0, 0);
    lcd.print("   Door Lock");
    lcd.setCursor(0, 1);
    lcd.print(" Scan Your Tag ");
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    //Reading from the card
    String tag = "";
    for (byte j = 0; j < mfrc522.uid.size; j++)
    {
      tag.concat(String(mfrc522.uid.uidByte[j] < 0x10 ? " 0" : " "));
      tag.concat(String(mfrc522.uid.uidByte[j], HEX));
    }
    tag.toUpperCase();
    //Checking the card
    if (tag.substring(1) == tagUID)
    {
      // If UID of tag is matched.
      lcd.clear();
      lcd.print("Tag Matched");
      digitalWrite(greenLed, HIGH);
      delay(3000);
      digitalWrite(greenLed, LOW);
      lcd.clear();
      lcd.print("Enter Password:");
      lcd.setCursor(0, 1);
      RFIDMode = false; // Make RFID mode false
    }
    else
    {
      // If UID of tag is not matched.
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Wrong Tag Shown");
      lcd.setCursor(0, 1);
      lcd.print("Access Denied");
      digitalWrite(buzzerPin, HIGH);
      digitalWrite(redLed, HIGH);
      delay(3000);
      digitalWrite(buzzerPin, LOW);
      digitalWrite(redLed, LOW);
      lcd.clear();
    }
  }
  // If RFID mode is false, it will look for keys from keypad
  if (RFIDMode == false) {
    key_pressed = keypad_key.getKey(); // Storing keys
    if (key_pressed)
    {
      password[i++] = key_pressed; // Storing in password variable
      lcd.print("*");
    }
    if (i == 4) // If 4 keys are completed
    {
      delay(200);
      if (!(strncmp(password, initial_password, 4))) // If password is matched
      {
        lcd.clear();
        lcd.print("Pass Accepted");
        sg90.write(90); // Door Opened
        digitalWrite(greenLed, HIGH);
        delay(3000);
        digitalWrite(greenLed, LOW);
        sg90.write(0); // Door Closed
        lcd.clear();
        i = 0;
        RFIDMode = true; // Make RFID mode true
      }
      else    // If password is not matched
      {
        lcd.clear();
        lcd.print("Wrong Password");
        digitalWrite(buzzerPin, HIGH);
        digitalWrite(redLed, HIGH);
        delay(3000);
        digitalWrite(buzzerPin, LOW);
        digitalWrite(redLed, LOW);
        lcd.clear();
        i = 0;
        RFIDMode = true;  // Make RFID mode true
      }
    }
  }
}

First: Please tell us, what electromagnetic doorlock you exactly have. A link to the product would be fine. Second: What exactly don't you understand in that code? Even without understanding the whole code you might get good results when playing with it a bit. The servo part is everything with sg90. You can then replace these parts with your door lock code.


text:
First Arduino Project - Need Advice (powering WS2812B LEDs)
I'm making a long LED display made up of 3 (8x32) LED matrices to go inside of a car. I can't seem to find any in-depth guides on this sort of thing. If anybody has examples that they would like to share please do!
The major issue I'm having is power. I'm extremely new to electronics, and I don't understand how these lights can be powered separately, and still be addressably lit by the Arduino?
Parts:
3* LED matrices (8x32)
https://www.amazon.com/gp/product/B088BTXHRG/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
1* Mega 2560
Here's the mock-up schema:

I forgot to draw in a switch, and a power line leading to the Arduino. But let's assume there will be a switch before the resistor and a line that feeds power to the MEGA 2560.
What in this schematic doesn't look or sound right?
Thank you all in advance for your help. This is probably not at all how to go about building circuits, and I'm trying my best to learn. All advice is wanted!

In addition to the answer, you might want to read https://learn.adafruit.com/adafruit-neopixel-uberguide?view=all#powering-neopixels and https://learn.adafruit.com/sipping-power-with-neopixels. It's not shown in your diagram but keep in mind that the Arduino and power supply/ies need to share a ground as well.

you should get 12v LEDs instead of 5.

Powering the LED panels
Powering your panels will be your greatest challenge!
These LED panels are powered by a single +5V power input per panel and do not need a resistor in the power supply path (they actually need a very low resitance path). You do need a good quality +12V DC -> +5V DC power supply (or multiple, as explained below).
Since 3 x 256 RGB LEDs require a large amount of power when they're all lighted at the same time (something like 60mA * 768 =~ 46A), the power supply should be able to accomodate that. It might be better to use three individual, smaller (~15A) power supplies. You could opt for power supplies smaller than 15A, but you should ensure that all LEDs will never light up at full intensity at the same time.
For supplying power from a 12V car battery, you could use high quality 12V DC to 5V DC buck converters (they're efficient). Use good quality cable with a diameter large enough for transporting the large currents necessary. If you need connections in the path of the power supply, make sure they are good quality as well. To reduce losses in long stretches of wire, you should place the buck converter(s) near the LED panels.
Connecting the data lines
The color and intensity of Individual LEDs is controlled via the data input coming from your Arduino and it only needs one input to control all 768 LEDs. The first panel's "data out" should be connected to the next panel's "data in" and so on, like your drawing.
Software
I recommend you look up the FastLED library and some of its examples to get familiar with controlling large amounts of addressable RGB LEDs. There are many good examples and interesting projects out there.

I think it should be mentioned that this whole idea is very impractical for a car, all but impossible w/o great expense and expertise, and would be non-trivial even with mains power available. A cigarette lighter socket for example can only do 15A, and it will quickly overheat at that load. You alternator probably only kicks out about 50A, and your car needs some to run, so you'll likely kill the engine and drain the battery in no time even if you managed to get everything safely wired up. Use LCD displays if you need that many pixels..

@dandavis, I agree, but it is feasible, especially if not using lighter sockets (which are about the worst sockets in the world i.m.o.) but direct, fused connections and not keeping the intensity at maximum. It’s up to the asker.


text:
Have terminal bash script act as virtual "button" for Leonardo?
I've searched quite a lot for this and tried to piece bits of code together but with no luck so far.
All i'm looking to do is have a command I can run in terminal/bash script on the Mac trigger some code to run on the Arduino (Leonardo)
It doesn't matter what data the Mac sends, I only have one command to run so it doesn't need to look like separate buttons or anything.
So far i've tried
int incomingByte = 0;   // for incoming serial data
void setup() {
Serial.begin(9600);
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
//run commands
  }
    }

and then from terminal/script both
echo "1" > /dev/tty.usbmodemHIDPC1 9600

and
screen > /dev/tty.usbmodemHIDPC1 9600

I see the Arduino light flash when I run those two commands in terminal which would seem to suggest that its receiving the data, but nothing runs.
I have stripped out my code that is due to be run by the way for simplicity. I've got working keyboard presses ready to go to enter in the "run commands".

how do you know that the code does not run?

stty -F /dev/tty.usbmodemHIDPC1 speed 9600 && echo "1" > /dev/tty.usbmodemHIDPC1

@jsotola it's set to write some letters with the keyboard, but nothing is written. Will try Majenkos edit below.

@Majenko neither of those commands did anything unfortunately, just locked terminal up - the Arduino hasn't even flashed either

Also asked at: http://forum.arduino.cc/index.php?topic=588990 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.


text:
Arduino Leonardo board - not running or appearing a USB on external power
I've got an Leonardo board, it seems to be official, in that it has the Arduino branding and Made In Italy on the bottom.
However I cannot get anything to run with external power supply. Everything when powered via the USB from the computer runs fine. As soon as I use any sort of external power, and I've tried both the barrel jack with 4x AA batteries, 6x AA batteries, 9v square battery and a Shield with 2x 3.7v lithium batteries - it turns on but doesn't do anything - the USB device doesn't even appear to the computer at all unless I pull the external power out again.
Is this a faulty board? Do I need to change the jumper arrangement on the board so it'll run with external power?

I have just tested all combinations of power plugging and unplugging on my Leonardo. No problem with anything.

And what "jumper arrangement" are you on about? There's no jumpers on a Leonardo.

The ICSP section - I thought it might have something to do with it. I guess i've just got a dud board then. It's a Leonardo R3 by the way.

The ICSP is a header for a connector, not for jumpers! This question is related to your previous question: https://arduino.stackexchange.com/questions/60405/leonardo-always-on-power-status-remains-between-computer-reboots With a new question please show us also the sketch. I think a arduino board with seperated usb-serial chip and removed the reset via the dtr signal is better for your project. But I don't know the ideal combination that can do it all. You are in uncharted waters.

@Jot I think this board would be idea if it would work as obviously Majenkos does when you plug in power. As there are no settings or code related to this, I can only come to the conclusion there is a fault on this board.

I just grabbed an unregulated power supply of 12v and measured 18v. Please show a sketch that we can try, tell us what kind of power supply you use.

I was just testing with Blink. You get the CDC/ACM endpoint regardless, so enumeration can be tested and the blinking confirms constant sketch execution.

I think key to my sketch is that it's working over USB-HID - it's that connection which is never made when powering externally - it doesn't appear to the computer at all. As soon as I pull the external power it connects to the computer as a HID device.

Still fine if I add Keyboard.h and Keyboard.begin() to Blink. Enumerates fine and creates a HID input device every time - with or without external power, with external power added first, or USB power added first. All combinations are fine.

I am testing it and everything is working as it should be. Can you give more information? Do you know how old the leonardo board is and which bootloader is on it? What kind of power supply? What is your sketch?

Also what version of the IDE and boards package?

by USB device not appearing you mean  the virtual com port or a HID device?

4xAA won't work as the VIN voltage must be greater than 6.6V to get precedence over the USB voltage. Did you check the polarity? The middle contact is positive, the surrounding contact is GND (negative).

@Pylon While a voltage lower than 6.6V will cause the USB's P-fet to get turned on when it's not desirable. It won't affect the operation of the sketch at all. Worst case scenario the computer will disable the USB port completely to isolate the external power. And it would alert you to that fact (Windows would pop up a bubble, linux / OS X would put it in dmesg, etc).

I tried with my Leonardo Microboard and the sketch runs just fine - so for whatever reason there's a fault on the Leonardo R3 board. Makes things a bit more annoying as i'll have to solder onto the micro board to complete the project instead of just using the shield, but supplying 5v from the shield to the micro works fine.


text:
Displaying characters as bitmaps
I have resorted to creating bitmaps for each number and a few letters for a 128x64 Oled module. This was to save memory and get around limitations of libraries such as the u8glib. If I had linux I could use the tools they provided to fix some of these but that's out of the question for now. I wanted to know if there's a simple way of mapping each character to it's bitmap so a function similar to XXX.print(); be used, in order to parse the characters and display the corresponding bitmaps automatically. That would make my life so much easier! thanks!

Example: Font and Character handling for PCD8544. https://github.com/mikaelpatel/Arduino-LCD/blob/master/src/Driver/PCD8544.h#L304. The class implements the Print::write() virtual member function and reuses all the print() member functions.

I would split it down into functions.
First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.
Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.
Finally you want an outer layer (or a few outer layer) functions that take different data types (const char * for example) and send each character in turn to the second function above.
If you were to make a class to wrap it all in you could inherit the Print class. That means you just need to provide the size_t write(char) function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.

my biggest problem now is that I can't use any other structure except const uint8_t var[] PROGMEM = {}; for my bitmaps. They will be changed by the compiler as soon as I delete the PROGMEM line. Also when I do this, there is no way I can pass the bitmap into anything (other than manually typing it which defeats the purpose!).As soon as I copy it, even using memcopy_P it is altered when it's displayed! I'm losing my mind over this!

Maybe I can write a huge case statement rather than a lookup table, but that seems awfully wasteful and bad practice. I played around with using structures, pointers, etc with no real luck in solving anything! it seems to be cursed!


text:
Specific formatting of floats and converting them to an array of chars
I have an oled display which can only display 4 digits + decimal point.
I need a way to format the number into 4 significant figures;
Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.
Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

printf on AVR doesn't support float formatting without some tweaking in configuration files of the builder.

Normally sprintf() would be the solution - however the sprintf() in the AVR LIBC is a cutdown version with no floating point support.
Instead you have to use dtostrf() to get the job done:
dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.
Another (nasty) way would be to go via String (although I would never recommend using String for anything, ever):
String s(val, 4);
const char *buf = s.c_str(); // this points to the internal char buffer.

Is the String class in the Arduino library reallly that bad?

Indeed it is. It uses dynamic allocation for the internal data storage, and that is a terrible idea when you only have 2k.

How about for stack-allocated String objects? Won't they get freed on return, so avoid fragmentation (Obviously unless you allocate other longer-lived objects while in the same call chain.)

@DuncanC what is a stack-allocated arduino String? It still uses realloc and free from the heap. Allocating and releasing memory is not problem, but the fragmentation is. That is also caused by changes made to a String (the reallocate can cause fragmentation).

If you define a String as a local variable in a function, or in an expression to compose Strings from other strings, those String objects should be transient (In C++ objects assigned to local variables in functions get created on the stack, and released as soon as the function returns)

@DuncanC The string object is local, but the data it allocates to do its job is on the heap.

Ok, but when the string gets destroyed, it's heap data will get freed.

@DuncanC it's not about quantity. It's about heap fragmentation. Local strings are actually worse because they get freed.

Well, if you are in a local function, create some objects, and then return and some of the objects persist but some don't, you have fragmentation. If you only create temporary objects and they all get freed, you don't cause fragmentation.

@DuncanC I thing you are lacking in your understanding about how the String object works. Yes, it's an object. But it's not a simple object. The object itself allocates memory on the heap with malloc() and frees it with free(). It also resizes it with realloc(). What happens to the String object during its lifetime is what causes the fragmentation - not the simple fact that the object exists. If you create a String object then delete it again then obviously you won't get fragmentation. ... cont ...

... If you create a String object, then assign a value to it, then concatenate more data to the end of it, then get a substring, the reassign something else to it, by the end of that, who knows what your heap looks like? Strings, when used sparingly, for simple operations, can be a benefit - however the risks of using them (when you don't know how to use the properly, and what the dangers with them are) far out weigh the small benefit you get from them.  Every time I have seen someone with the problem "My Arduino freezes randomly" the issue has been ... cont ...

cured by removing the String objects and reimplementing it with character arrays. Every single time. Strings used by a novice are deadly. Strings used by an intermediate user are still a minefield. Strings used by a professional is something you never see.

I'm an IT professional with over 30 years of experience. It's been a long time since I worked in C++, and I have little experience with Arduino String objects, which is why I'm asking. What are the alternatives using C strings? I'm perfectly comfortable with C, but used to having printf() and sprintf(), so feel a bit lost.

Let us continue this discussion in chat.