text:
Arduino Project Interrupt Error?
I have a project to be made i.e. water Billing System using RFID(Mfrc522) on Arduino NANO.
There is one difficulty that I haven't been able to overcome. I hope someone could help me out.
Project flow:

water or any liquid flows through the sensor and quantity of water gets recorded
now according to quantity of water flown there is price decided
this price needs to be deducted by swiping rfid card
issue:
i haven't been able to control interrupts
my program calculates the water flown
required:
edit code such that it as soon as water flows through it, it calculates and ask user to swipe card and as user swipes a amount deductes and process continues.

if not clear please ask and help me out
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN);
String tagUID = "10 90 70 38";  // String to store UID of tag. Change it with your tag's UID
int bal =1000;

byte statusLed    = 13;
byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;

volatile byte pulseCount;

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

unsigned long oldTime;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;
  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  Serial.begin(9600);    // Initialize serial communications with the PC
  while (!Serial);
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
}

/**
 * Main program loop
 */
void loop()
{

   if((millis() - oldTime) > 2000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");       // Print tab space

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("\t");       // Print tab space
    Serial.print(totalMilliLitres/1000);
    Serial.print("L");
    rfid();

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void rfid()
{
   // put your main code here, to run repeatedly:

  Serial.println("In Rfid Loop");
  delay(3000);
  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();
       if (tag.substring(1) == tagUID)
      {
        bal=bal-20;
        delay(100);
        if(bal>=30)
        {
          Serial.println(bal);
          Serial.println("YOUR BALANCE");
          delay(400);

          // Reset the pulse counter so we can start incrementing again
          //pulseCount = 0;

          // Enable the interrupt again now that we've finished sending output
          //attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
        }
       else
        {
          Serial.println("INSUFFICIENT BALANCE PLEASE RECHARGE");
         }
        delay(100);

      }
      else
      {
        Serial.println("WRONG CARD ENTERED");

       }
}

And what is your actual problem with the interrupts? "haven't been able to control interrupts" is not a good problem description. Was did you expect your code to do and what did it actually do instead?

You have the interrupts detached for most of the time.  If you want to use the interrupt you need to have it attached.  Instead of detaching for all of loop, only detach for a very short time, make a copy of the pulseCount variable, and then turn interrupts back on.  Then use the copy you made in the calculations.

You are disabling interrupts for way too long. Interrupts are meant for
handling time-critical tasks that cannot wait for a full loop iteration.
If you ever disable them, it should be for a time as short as possible.
In your case, you only need to disable interrupts while accessing the
pulseCount variable, as this variable is shared between the ISR and
the regular code. This can be done in a very short "critical section" as
follows:
noInterrupts();
uint8_t pulseCountCopy = pulseCount;
pulseCount = 0;
interrupts();

In the rest of the loop you then only access pulseCountCopy. Note that
you don't really need to reset pulseCount to zero. Since it is
incremented using the rules of modular arithmetic, you can just compute
the differences between consecutive readings. You will get the correct
result even when it rolls over. This makes the critical section even
shorter:
static byte oldPulseCount;
noInterrupts();
uint8_t pulseCountCopy = pulseCount;
interrupts();
uint8_t pulseIncrement = pulseCountCopy - oldPulseCount;
oldPulseCount = pulseCountCopy;

And then note that, since reading a single byte is an atomic operation
(a single machine instruction), you do not even need to disable
interrupts al all! However, if the flow can ever be larger than
0.47 L/s, then 8 bits will not be enough for pulseCount. You
will have to use a 16-bit variable (uint16_t) and keep the critical
section.
As a side note, you are calling millis() several times per loop
iteration. This is bad practice, as there is no guarantee that you will
always get the same value, so you end up with your timing calculations
being somewhat sloppy. You should rather do something like
uint32_t now = millis();

at the start of loop(), and use the same value for the whole
iteration.
Another side note: you are differentiating the pulse count in order to
get a flow rate, then integrating the flow rate to get a total volume.
This is completely useless. The pulse count is already a measure of the
total volume. Basic arithmetics shows you that the calibration factor is
4.5 (pulses/s) / (L/min) = 270 pulses/L
Your calculations will be less sloppy (having less accumulated error) if
you just divide the total pulse count by 270 to get the total volume in
liters.


text:
Arduino split comma separated serial stream
I'm trying to read serial data into Arduino.
I usually use a Serial to USB cable to connect to the hardware and is sending data like
33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68

At 38400 bound rate.
I have been reading this post Splitting a comma separated string through serial (Arduino) https://www.arduino.cc/reference/en/language/functions/communication/serial/print/
I have tried to write something my own but none return readable data.
Any tips please?

Your device seems to use a line-oriented protocol, where each message ends with a CR and/or LF character. The first thing you should do is make sure you buffer the input in order to process one line at a time. See Reading Serial on the Arduino, by Majenko. Once you have this sorted out, follow chrisl's advice.

see https://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string

The reference article, that you linked to, is about sending data over Serial, not about reading.
You can use the strtok() function, which can split a character buffer into tokens based on a delimiting character (the comma in your case).
First you have a buffer, where your Serial message in saved (I'm not covering the actual receiving/reading of the Serial data here, because there are tons of tutorials on the web):
char buffer[] = "1,2.3,4,0x56";

Then you can get the first token:
char *token1 = strtok(buffer, ",");

token1 is a pointer to the start of the token. strtok() replaces the found delimiter (which you specify with the second parameter) with a null character. That means, that token1 points to a null terminated C string with only the first token in it (Keep in mind that the buffer is changed with that, so it does not make any sense to try printing buffer after you used strtok()). Note, that this does not create a new buffer. It simply points to a specific place inside buffer.
You could also directly process it, for example convert it to an integer:
int token1_value = atoi(strtok(buffer, ",");

To get the next token, you simply again call strtok(), but now you provide NULL instead of buffer in the first parameter. That tells strtok(), that you still want to process the same buffer from the last execution.
float token2_value = atof(strtok(NULL, ",");

You can now do this, until no token is left unprocessed in the buffer. In that case strtok() returns NULL.
char *token = strtok(NULL, ",");
while(token != NULL){
    Serial.println(token);
    token = strtok(NULL, ",");
}

Have a look at the C++ reference for strtok(). It also includes an online editor, where you can run the provided example and play with it.

source: Stack Exchange

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

sort: votes


text:
Arduino Serial Queue
So I am programming an LED Music Visualizer that uses a combination of Processing and Arduino. I have it all working as I want to but there is a small problem. If I were to stop the music, then the Arduino will keep displaying the visualization for a few seconds. I believe that this issue would be caused by it "catching up" on new serial data from Processing like a queue. So my question is: When arduino uses the Serial.read() function, is it using the most recent value or is it using the next value received after the last one that it used, like a queue of values.
Example: Processing sends the values 1,2,3,4,5,6,7,8,9 over serial in 10 millisecond intervals. Arduino only performs Serial.read at 20 millisecond intervals. Would the arduino read the values 1,3,5,7,9 in or would it read the values 1-9 but in twice the time?
Sorry for the confusing question, hopefully somebody could shed some light. At the core, it is a question on how serial works, you can ignore the part about the music visualizer.

Arduino only performs Serial.read at 20 millisecond intervals.

It sounds like you're using delay to pace the reads.  But why?  You'll start to lose data after reading just 3 or 4 characters (60ms to 80ms).  Serial at 9600 can send 1 character per millisecond, 20 times faster than you are reading them.
If you edit your post to include your code, we might be able to make a suggestion to eliminate that delay.

It sounds like you figured most of your question out already.
(Someone correct me here if I'm wrong). The Atmega 328p uC, I believe, has an 8 byte hardware buffer for RX serial data. In software, the Arduino core code defines a maximum ring buffer of 64 bytes that acts as a FIFO queue.
So, what does his mean? Let's just focus on the hardware buffer since it's fairly easy. Say you send your data 1,2,...,10 at 10ms intervals, and you read your data at 100ms intervals (for illustration purposes). The problem is that you send 10 bytes of data but only have room for 8 bytes. So, your first two values (1,2) are pushed out of the buffer and lost. This idea also illustrates a FIFO queue, first in first out.
The same idea can be extended to a ring buffer.
Anyway, like you said, this could explain your problem. If you have 64 bytes, which will obviously be full since your inevitably losing data (20ms read with a 10ms write), you'll be seeing the effects for 64 * 20ms = 1.28s. There's probably some processing delay too which will extend this delay, but it's more than likely minimal if it's efficient code.

The hardware buffer is only 2 bytes according to the datasheet: “The receive buffer consists of a two level FIFO.”

Actually, the last bytes received are dropped when the input ring buffer is full.

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


text:
Arduino serial communication synchronisation
i am trying to send data via Labview to my arduino board using serial communication.My problem is that the arduino reads only the first byte of sent data then when i change it ,it doesn't react.
For example when i start the communication i send '0' to arduino.I sees it.but while it is running i send '1' but it doesn't behave accordingly to it.
I noticed also that the board 'sees' sometime the new value after a random period of time.
void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

char data = 'F';

void loop()
{
    data = Serial.read();
    delay(50);

    if (data == '0')
    {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
    if (data == '1')
    {
        digitalWrite(13, HIGH);
        delay(4000);
        digitalWrite(13, LOW);
        delay(4000);
    }

    data = '4';
}

I suspect you problem stems from the use of delay's in your code. for example,
if (data=='1')
 {
  digitalWrite(13,HIGH);
  delay(4000);
  digitalWrite(13,LOW);
  delay(4000);
 }

Those delays prevent any computations from happening for 4 seconds each. Your arduino will not read another character after it sees a '1' for 8 seconds. If you send too much data in that 8 seconds to fit in the serial buffer, the extra characters are lost.
The behavior you seem to want will require separating the code that reads serial from the code that runs the output, and making sure neither section ever stops execution with delays. Your blinks will need to be timed with something else, like frequent comparisons against the current time with millis()

JUST add the part ~
This flushes the serial buffer, which aids in error free data receiving. No need to implement the millis() protocol as you want the led to be active for that time so you do not want any data to enter the system, neither you are using interrupts service.
Serial.readString();

No.  This will cause data loss.  In the overwhelming majority of cases, if you feel you need to flush and discard the input buffer, you have a design error in your scheme.

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


text:
Using external battery for motor
i have a little project going on, where i want to connect vibration motors to an arduino. I found this, with example code but also found other tutorials wish use a capacitor for the motor. What is the advantage of using one ?
I am currently planning to power the arduino by a 9V battery, with 3 ultrasound sensors being connected to the 5v output of the arduino. Hence, i believe that i need an external battery for the 2 vibration motors. I think 2x AA's should do the job for some hours, right ?
I also have a question about the rating of the resistor to use at the base of the transistor. How do i calculate the rating that i need ?

a transistor is a current controlled current source. it means that you can control how much current is "Allowed" to flow from emitter to collector, by controlling the minor current flowing through the base of transistor. there is a specific ratio for this two currents for various transistors. (I recommend reading some transistor tutorials). let's say, your motor is drawing 250mA in full speed. you want to "allow" up to 300mA to be available to it.

base is connected to 5V through a 2.2 kOhm resistor. The base current is : (5/220) ~=  2.2mA
the hfe of your transistor is 150 (it depends on transistor model. It’s written in the datasheet available for every transistor on the market. it's the ratio of base current and emitter collector current mentioned above. You “must” read it first as it’s highly various between transistor models).
The current allowed to flow from emitter to collector is 2.2mA * 150 = 330mA which is sufficient for you motor.

note : many simplifications are made to make it easier to understand.

Resistor is there to limit Arduino current out. 220, 270, 330, any should be okay.
Be sure to connect battery - to Arduino Gnd.
Transistor will be used to connect motor '-' to Gnd? Be sure to put a diode across it - anode to motor '+', cathode to motor '-' to dissipate current surge generated by the motor when the transistor turns off.
2AAs will last a little while. Better than using 9V for them, that will drain a battery quick.

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


text:
Servomotor losing its connection right after being connected to Arduino
I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.
#include <Servo.h>

#define SERVO 6 // Porta Digital 6 PWM

Servo s; // Variável Servo
int pos; // Posição Servo

void setup ()
{
  s.attach(SERVO);
  Serial.begin(9600);
  s.write(0); // Inicia motor posição zero
}

void loop()
{
  for(pos = 0; pos < 90; pos++)
  {
    s.write(pos);
  delay(15);
  }
delay(1000);
  for(pos = 90; pos >= 0; pos--)
  {
    s.write(pos);
    delay(15);
  }
}

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

In case it's a hardware problem, add a photo of setup + circuit schematic or reference to how you wired stuff up.  Add model numbers of the servos and specs of the power supply that's powering the servos.  Indicate what actually happens, rather than saying "they do as the code says", because nobody but you knows what you think the code does.  Also report results that occur with only one or the other servo attached, and results when you change delay(15) to eg  delay(150)

Your code is correct. Check the following:

Arduino works from 5V, but most servos need 6V.
Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
Check that grounds of both power supply for Arduino and power supply for servo are connected together.

would it work if I attach it to a shield, instead of directly in the arduino pin?

it will work only if shield has its own power supply AND is dedicated for providing power its to servo


text:
Phase and frequency correct PWM mode Arduino Mega 2560
I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?

unsigned int b=7999;
void setup() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TCCR4B=(1<<WGM43)|(0<<WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1<<CS10);
TIMSK4 |=(1<<OCIE4A);
}

void loop() {
  }

ISR(TIMER_COMPA_vect){

  }

The output of the code for different duty cycles are as below
Duty cycle:0.2 (OCR4A=b/5)

Duty cycle:0.2 (OCR4A=b/2)

see the diagrams for pwm timing  in the datasheet

Can you please explain what is wrong

in phase correct pwm the counter counts up and then down and so it matches the compare register twice in one period. first while counting up a second match while counting down. the pin changes state on both matches

That's what I need. But it's clear from the wave form that the pin trigger while down counting and resets immediately as a glitch

You wrote:

TIMSK4 |= (1<<OCIE4A);

and then never defined ISR(TIMER4_COMPA_vect). As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.

When I added interrupt service routine (ISR(TIMER4_COMPA_vect)) the output waveform acts exactly like fast PWM. It does not provide phase correct wave

@VivekVijayan: Do you get the expected frequency? If so, how do you tell it is not phase correct?

@Edger Bonet: I am getting the expected frequency. But when I observe the waveform all the waves with different duty cycle starts from the same point. I believe in phase correct pwm mode the OCnA or OCnB pins are set during upcounting. So I could expect different starting points(in time) for waves with different duty cycles

@VivekVijayan: You would not get 1 kHz in fast PWM mode. Re “different starting points (in time)”: What is your time reference for defining the starting points? Are you using an oscilloscope? If so, how did you configure its trigger?

I don't know much about CRO. I am using an electronic module called Expeyes which basically acts as a DSO. I used the time reference axis to determine the triggering points. Expeyes doesnt have any option to control triggering. I generated Fast PWM using different code and compared it with the output from the above mentioned code.

@VivekVijayan: Your phase correct waveform is fine. It looks wrong to you only because you don't understand how your DSO sets its time axis.

Thanks for your time. I am proceeding with it. Will try some RC filters to identify the output waveform.


text:
Making '*' key on keypad a backspace key
Using a 4x3 membrane keypad and I want to make the '*' key a backspace if the wrong number is entered.
I am a newbie and having a hard time trying to figure out how to code that, any help would be great.

int getNumber()
{
  int num = 0;
  char key = myKeypad.getKey();
  while (digitCount <=  1)
  {
    switch (key)

    {
    case NO_KEY:
      break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      num = num * 10 + (key -  48);
      digitCount++;
      break;
    case '*':
      break;
    case '#':
      break;
    }
  key = myKeypad.getKey();
  }

  digitCount = 0;
  return num;
}

Divide your number by 10?

Sorry, don't understand what you mean.

To make room to add a number you multiply by Ten. So to remove that space you divide by 10.

case '*': num /= 10; break; and then you need to echo that to the display (if any).


text:
Multiple WiFi client/server connections
I'm implementing a WiFi HTML web server using the WiFiNINA library, an Adafruit Airlift ESP32 coprocessor, and a Teensy 3.5. It's starting to work, but I have a couple of questions. This simplified code will illustrate the first.
#include <WiFiNINA.h>
#include "Wifi_names.h"

WiFiServer server(80);

void error (const char *msg) {
   Serial.println(msg);
   while (1) ; }

void setup(void) {
   Serial.begin(115200);
   while (!Serial) ;
   WiFi.setPins(19, 20, 21, -1, &SPI);
   if (WiFi.status() == WL_NO_SHIELD) error("no Wifi shield");
   Serial.print("ESP32 firmware version: "); Serial.println(WiFi.firmwareVersion());
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
   while (WiFi.status() != WL_CONNECTED) ;
   Serial.print("connected, IP address is ");
   server.begin();
   Serial.println(WiFi.localIP()); }

void show_client(const char *msg, WiFiClient *pclient) {
   Serial.print(msg); Serial.print(":");
   if (*pclient) {
      Serial.print(" IP "); Serial.print(pclient->remoteIP());
      Serial.print(" port "); Serial.print(pclient->remotePort()); }
   else Serial.print("none");
   Serial.println(); }

void check_for_another_client(const char *msg) {
   WiFiClient newClient;
   newClient = server.available();
   show_client(msg, &newClient); }

void loop(void) {
   WiFiClient client;
   while (!(client = server.available())) ;
   Serial.print("\n time: "); Serial.println((float)millis()/1000);
   show_client("client 1", &client);
   check_for_another_client("client 2");
   while (client.available() == 0) ;  // wait for data
   check_for_another_client("client 3");
   Serial.print("client 1 data read: "); Serial.println(client.read(), HEX); // read the data
   check_for_another_client("client 4");
   while (client.available()) client.read(); // flush the rest of the input
   delay(1000);
   client.stop(); // abort the connection
}

The output is:
ESP32 firmware version: 1.2.2
connected, IP address is 192.168.86.35

 time: 43.22
client 1: IP 192.168.86.32 port 62346
client 2: IP 192.168.86.32 port 62346
client 3:none
client 1 data read: 47
client 4:none

The question is: why does server.available() continue to say that I have new connections until there is some data available on the connection it already gave me? What if a second connection arrives after the 3-way TCP connection establishment handshake (SYN, ACK/SYN, ACK) but before any data arrives? How do I get that second connection?
The second question, which is related, is illustrated by the Sniffer trace of that transaction:
179 *REF*     192.168.86.32  192.168.86.35  TCP  66  62346 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
180 0.000239  192.168.86.32  192.168.86.35  TCP  66  62347 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
183 0.039352  192.168.86.35  192.168.86.32  TCP  58  80 → 62346 [SYN, ACK] Seq=0 Ack=1 Win=5744 Len=0 MSS=1436
184 0.039431  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [ACK] Seq=1 Ack=1 Win=64240 Len=0
185 0.039602  192.168.86.32  192.168.86.35  HTTP 488 GET / HTTP/1.1
195 0.278592  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [ACK] Seq=1 Ack=435 Win=5310 Len=0
197 1.053036  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [FIN, ACK] Seq=1 Ack=435 Win=5310 Len=0
198 1.053146  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [ACK] Seq=435 Ack=2 Win=64240 Len=0
199 1.053600  192.168.86.32  192.168.86.35  TCP  54  62346 → 80 [FIN, ACK] Seq=435 Ack=2 Win=64240 Len=0
200 1.060248  192.168.86.35  192.168.86.32  TCP  54  80 → 62346 [ACK] Seq=2 Ack=436 Win=5309 Len=0

The request is from the Chrome browser. As you can see, it tries to establish two simultaneous TCP connections from two different source ports, 62346 and 62347, because it will use the second one for embedded images. But WiFiMINA never accepts that connection with the 3-way handshake, and never gives it to me. Chrome will resend the second SYN packet three seconds later, but as long as the first connection is still active, WiFiMINA continues to ignore it.
How can you accept two simultaneous TCP connections on different source ports from the same client? That's required for Chrome.

The server.available() in Arduino networking libraries returns always the first connected client. This is in contrary with ESP8266 and ESP32 WiFi libraries for Arduino. They flag the returned connection as claimed and don't return it again. If the WiFiClient on ESP goes out of scope it is closed. In Arduino libraries you must stop() the Client to close the connection and free the 'socket'.
The Arduino Ethernet library has a new function not adopted yet by the WiFi libraries. It is server.accept(). It marks the connection as accepted and the next call doesn't return the same client. The sketch is still responsible to call stop(). The use of accept() is demonstrated in AdvancedChatServer example of the Ethernet library 2.00.
What you can do? Get the connection (WiFiClient), handle the request, send the response and stop() the connection. Then handle the next Client. Set Expires header to let browser cache the static files.

"The server.available() in Arduino networking libraries returns always the first connected client."  That doesn't seem to be the case for WiFiMINA. It's true the first time I call it in my example after connection ("Client 2"), but then as soon as data is available on the connection, server.available() returns zero.

Your suggestion to "...handle the request, send the response and stop()" won't work for Chrome, because by that time the library has already ignored the SYN packet establishing the second connection. Besides, Chrome expects both connections to be open at the same time. That's a totally legitimate use of the TCP/IP protocol.

but the TCP listening socket is on the ESP32. it should handle the TCP part of establishing the TCP connection. and then the connection should wait until the sketch gets to it

I agree, it should. But it doesn't seem to. Notice that it never responds to packet 180, which is trying to establish a connection from port 62347. Is there anything I could be doing wrong that causes it not to?


text:
Arduino I2C Wire.onReceive hangs after a few loops
I have an Arduino Leonardo (master) and a Polulu A-star 328 PB(slave). I intend to use the slave to actuate some servos. I've modified the code from https://www.arduino.cc/en/Tutorial/MasterWriter to also blink the builtin led of the slave and it hangs after a few loops. Without the blink, it works fine. With blink, it hangs after a few loops.
Master:

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting
  x++;
  delay(2000);
}

Slave:
#include <Wire.h>

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Wire.begin(8);                // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600);           // start serial for output
}

void loop() {
delay(100);
}

void receiveEvent(int howMany) {
while (1 < Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
}
int x = Wire.read();
Serial.println(x);
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}

Serial monitor:
x is 16
x is 17
x is 18
x

Any idea what's causing it and what can I do to further debug it or fix it?
Thank you!

onRecieve is an interrupt routine. You can't use things like delay(), millis() or Serial.print inside interrupt routines.

The onReceive callback get's called from an ISR (interrupt service routine). During the execution of this ISR, the MCU cannot react to other interrupts, since interrupts get automatically turned off at the start of an ISR.
Some functions like delay() and millis() rely on interrupts to work correctly, since the timekeeping in the Arduino framework is done via a timer interrupt. This means, that you cannot use delay() inside of an ISR. It will block forever, waiting for the internal time increment from the pointer, which will never come.
You can also get a problem with big Serial.print()s. These Serial functions fill the libraries internal buffer, and  the library will use interrupts to actually transmitt the data. If interrupts are turned off (like in an ISR), the buffer get's filled, until it is full. If you then again call Serial.print() or one of it's siblings, the library will block the execution, until there is enough space in the buffer, which will never happen. (You don't have this problem here, since you are only printing a few characters, but you should know this)
Generally ISR's should be as short as possible to prevent, that the Arduino misses an interrupt (which may mean data loss). Instead doing the blink in the ISR, you should simply set a flag variable, which you check in your loop() function and execute the blink correspondingly. That looks about like this:
volatile byte flag=0;

void loop(){
    if(flag){
        // Execute blink here
    }
}

void receiveEvent(int howMany) {
    // Do receiving here
    flag=1; //Set flag to a non-zero value to activate the corresponding code in loop()
}

After a bit of tinkering, I noticed that removing the delay() call in the slave fixed it and there were no more hangs. Also, when using the Servo library to move a servo instead of blinking the led, Servo.write() hangs while Servo.writeMicroseconds() doesn't. I'd mark the answer that has an explanation for this strange behavior.

upvote for continuing your investigation ... one thing that you could try to find out is will the code work with minimal delay(1) call?


text:
Arduino SocketIO library not working over HTTPS
I am currently using this Socket.io library to be able to send data from the Adafruit Feather HUZZAH (based on ESP8266) to my NodeJS server. It works like a charm on my local webserver, never failing me. However, when I try the setup with the proper webapp hosted on Heroku, the command SocketIOClient::connect(host, port) fails and no connection is established with the webserver's SocketIO.
Since there is no mention of limitations with HTTPS connections, I assume that I might be doing something wrong. If the impossibility of having HTTPS connection is the case, however, is there any other way to send this kind of data through web sockets to a NodeJS server hosted on Heroku?

probably not an arduino question. But it is also hard to know what your doing when you don't post any code or error messages.   "Fails" can mean a lot of different things.

a lot of tls stuff doesn't work on the 8266 because of lack of power and the shared CPU

For anyone having the same issues with SocketIO and the ESP8266, this issue on Github explains how I solved it:

When specifying the host, avoid including the http:// or any other trailing slashes.
  So it became String host = "something.herokuapp.com";


text:
Code that worked in Uno is not working in Mega 2560
I send data with Android and read it from the Arduino serial screen. When I use UNO, I can read the data smoothly. When I use MEGA, it uploads the code without error, but does not transfer data on the serial screen. Can you tell me why?
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(2,3);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  Serial.println("Program is starting...");
  Serial.println("by Berke Ogulcan Parlak");
}

void loop() {
  if (bluetooth.available()) {
    while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {
        azdırma işlemleri bu satırda yapılacak..

      }
    }
  }

}

SoftwareSerial relies on the Pin Change interrupt. Not all pins on the Mega have pin change interrupts.
But that is all a moot point really, because when you're using a microcontroller that has lots of real hardware UARTs there is no call to be using SoftwareSerial in any case.


text:
How to add another condition in the loop?
I am using mpu6050 for counting the twitch movement. The algorithm is counting the peak/twitch whenever it goes above the threshold value. Now, I want to add that the algorithm count twitch only when it goes above threshold value and all the twitch within 90s are counted as one twitch movement. Kindly help me with this. Also try to integrate this in my code.
Here is the code:
#include "I2Cdev.h"
#include "MPU6050.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 accelgyro;

int16_t ax, ay, az;
float threshhold=5000.0;
float conmove=4;
const int sampletime=90000;

float xval[100]={0};
float yval[100]={0};
float zval[100]={0};
float xavg;
float yavg;
float zavg;

int twitch,flag=0;
MPU6050 mpu6050;

int16_t tr;          // raw temperature data register value
char buffer[7];      // temporary string buffer; used with dtostrf() function
#define OUTPUT_READABLE_ACCELGYRO

#define LED_PIN 13
bool blinkState = false;

void setup() {

    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(115200);

    // initialize device
    Serial.println("Initializing I2C devices...");
    accelgyro.initialize();
    mpu6050.initialize();  // initialize MPU6050 sensor module

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    pinMode(LED_PIN, OUTPUT);
    calibrate();
    delay(5000);
}

void loop() {

    accelgyro.getAcceleration(&ax, &ay, &az);
    tr = mpu6050.getTemperature();

    #ifdef OUTPUT_READABLE_ACCELGYRO
    +
        // display tab-separated accel/gyro x/y/z values
        Serial.print("a/g:\t");
        Serial.print(ax); Serial.print("\t");
        Serial.print(ay); Serial.print("\t");
        Serial.print(az);
    #endif

    #ifdef OUTPUT_BINARY_ACCELGYRO
        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
    #endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
    int acc=0;
    float totvect[100]={0};
    float totave[100]={0};
    float xaccl[100]={0};
    float yaccl[100]={0};
    float zaccl[100]={0};

    for (int i=0;i<100;i++)
    {
        xaccl[i]=float(ax);
        delay(1);
        yaccl[i]=float(ay);
        delay(1);

        zaccl[i]=float(az);
        delay(1);

        totvect[i] = sqrt(((xaccl[i]-xavg)* (xaccl[i]-xavg))+ ((yaccl[i] - yavg)*(yaccl[i] - yavg)) + ((zval[i] - zavg)*(zval[i] - zavg)));
        totave[i] = (totvect[i] + totvect[i-1]) / 2 ;
        //acc=acc+totave[i];
        Serial.println(totave[i]);
        Serial.print("T = ");  Serial.print(dtostrf(tr/340.0+36.53, 5, 1, buffer));  Serial.println(" °C");

        // delay(200);

        //cal twitch
        if (totave[i]>threshhold && flag==0)
        {
            twitch=twitch+1;
            flag=1;
        }
        else if (totave[i] > threshhold && flag==1 )
        {
            //do nothing
        }
        if (totave[i] <threshhold  && flag==1 )
        {flag=0;}

        Serial.println('\n');
        Serial.print("twitch=");
        Serial.println(twitch);
    }

    //float tim=acc/100;
    //Serial.println(tim);
    delay(1000);
    // stepcal(totave);
}

void calibrate()
{
    digitalWrite(13,HIGH);
    accelgyro.getAcceleration(&ax, &ay, &az);

    float sum=0;
    float sum1=0;
    float sum2=0;

    for (int i=0;i<100;i++)
    {
        xval[i]=float(ax);

        sum=xval[i]+sum;
    }
    delay(100);
    xavg=sum/100.0;

    Serial.println(xavg);

    for (int j=0;j<100;j++)
    {
        yval[j]=float(ay);

        sum1=yval[j]+sum1;
    }
    yavg=sum1/100.0;

    Serial.println(yavg);
    delay(100);
    for (int i=0;i<100;i++)
    {
        zval[i]=float(az);

        sum2=zval[i]+sum2;
    }
    zavg=sum2/100.0;
    delay(100);
    Serial.println(zavg);

    digitalWrite(13,LOW);
}

You can do this with the millis() function. It returns the number of milliseconds since startup and can be used as a simple clock. Take the if statement, where you increment twitch:
if (totave[i]>threshhold && flag==0)
{
  if(millis()-last_twitch_timestamp > 90000){
    twitch=twitch+1;
    flag=1;
    last_twitch_timestamp = millis();
  }
}

This will check, if at least 90 seconds (90000ms) have passed since the last registered twitch (time difference between the current time and the timestamp of the last twitch). If yes, it will register another twitch and reset the timestamp to the current time (return value of millis()). This deactivates twitch registering for 90s after each twitch.
For this to work, you need to define the last_twitch_timestamp variable at global scope:
unsigned long last_twitch_timestamp = 90000;

I initialize the timestamp to 90000, so that the very first twitch can be registered. If you initialize it to zero, you would need to wait 90s, until the first twitch can be registered.

Btw: The following delays don't make any sense. You can remove them:
xaccl[i]=float(ax);
delay(1);
yaccl[i]=float(ay);
delay(1);

zaccl[i]=float(az);
delay(1);

And you should really really keep all lines indented correctly. The Arduino IDE has an autoformat feature to make it simpler for you.

thank you for your response. Yes,it is counting all those twitch that occurs within 90s as one but after 90s it recognize next twitch for approx after 5s delay. so, this 5 second delay in the count would effect the our data. kindly help me with that.

Moreover, how can we add that the twitch is counted as one within 90s but there should be minimum 4 movements within that 90s.

@zuni What do you mean by 5s delay?. Do you mean, that the next twitch is only recognized after 95s, but not after 90s?

yes you can say not immediately after 90s.

You have a total of about 1.5s delay in your code. That reduces your reaction time. If you need faster reaction time, you should ditch the delay calls totally, going to non-blocking code like in the BlinkWithoutDelay example

okay that helped. kindly help me with this Moreover, how can we add that the twitch is counted as one within 90s but there should be minimum 4 movements within that 90s.

count up another variable right before the millis if statement. Then you can check it inside the if statement and reset it there to zero

would you write the syntax for this??


text:
Beginner problem with DC motor
I am new to electronics and I'm having a problem when creating my project. I have created a Bluetooth controlled rover using HC-06, Dual H-bridge motor driver and 4 DC motors.
However, only two of the DC Motors are moving and the other two remain still.
Could you please suggest what happened?
Attached is the wiring of the motors and code.
char t;

void setup() {
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) {
    t = Serial.read();
    Serial.println(t);
  }

  if(t == '1') {
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '2') {
    digitalWrite(9,LOW);
    digitalWrite(10,HIGH);
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
  }

  else if(t == '3') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '4'){
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  else if(t == '5') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  delay(100);
}

I have seen this question a number of times. What have you done to investigate the problem? Did you test each thing on its own: the arduino board, the driver module and the motors.

Why are you posting a new question, instead of editing your own? Duplicate of https://arduino.stackexchange.com/questions/56995/basic-question-on-dc-motors

To analyze your problem:

Switch two wires between two motors (and repeat this to get all combinations), to find out if the code/wiring until the motors is wrong, or there is a problem with the motors.
Print out the values of pins 9, 10, 11 and 12 and the value of t/input to see if the pins are controlled as you expect.
Remove all but one motors, for all motors one at a time, to see if there is no influence between them.

Below is not an answer to your question, but I can only align the code as answer.
It is better coding style to use the following form:
void loop() {
  if(Serial.available()){
    t = Serial.read();
    Serial.println(t);
  }

  if ((t >= '1') && (t <= '5'))
  {
    int input = (int) t - (int)'0';

    digitalWrite( 9, (input == 1) || (input == 4) ? HIGH : LOW);
    digitalWrite(10, (input == 2)                 ? HIGH : LOW);
    digitalWrite(11, (input == 1) || (input == 3) ? HIGH : LOW);
    digitalWrite(12, (input == 2)                 ? HIGH : LOW);
  }

  delay(100);
}

Note: ? : is a ternary operator which means : a ? b : c => if a then b else c.
Instead of using 9, 10, 11, 12 define pin numbers (e.g. PIN_MOTOR_X), and for 1, 2, 3, 4, 5 input numbers define LEFT, RIGHT, UP/FORWARD, DOWN/BACKWARD, STOP.

I don't know if I agree that code is better coding style, but it is definitely much more compact.  I slightly disagree with it being "better", because it's less obvious as to what the code does.  Part of good code style is making things readable.  This isn't bad code, just not obvious.  I definitely agree that naming the motors will make things a lot better.

@computercarguy Actually it would maybe be better to write a separate digitalWrite that has a parameter in for the 'boolean' so the ternary operator would not be needed (four times). (assuming the ternary operator is what bothers you, which I can understand).

Yes, there's a lot of different ways to write this.  The way you did it just isn't one I'd be comfortable supporting, and that's only because of the mental load to figure out what's going on.  I tend to write things more plainly/simply, so I don't have to really think about it when I have to read it later.  Abstracting the digitalWrite would probably be one of the better ways to simplify this.  And yes, when there's more than one ternary in a block of code, I kind of get the cold sweats.  :-)  I know how easy it is to abuse them.


text:
Having preblem in developing smart curtain
I am developing smart curtain system with voice control using Arduino Uno and bluetooth sensor
Almost of codes is already written. but I have to fix error with delay function.
I am using timer0_millis for time control.
But the one thing I want to fix is that because of delay in timer1 function,
I cannot change the value of a. but it need to be changed when voice is coming.
can anybody help me to fix this?
extern volatile unsigned long timer0_millis;

#include <SoftwareSerial.h>
#include <Stepper.h>
#include <dht.h>
#include <SimpleTimer.h>

SoftwareSerial BT(2, 3);
const int stepsPerRevolution = 64;
Stepper myStepper(stepsPerRevolution, 11, 9, 10, 8);
dht DHT;

#define DHT11_PIN A1

SimpleTimer timer;
char a = BT.read();

void setup() {
    Serial.begin(9600); // Sets the data rate in bits per second (baud) for serial data transmission
    pinMode(7, OUTPUT);
    myStepper.setSpeed(300);
    BT.begin(9600); // Sets digital pin 13 as output pin
}

void loop() {
    if (BT.available()) {
        char a = BT.read();
        if (a == '1') {
            digitalWrite(7, HIGH);
            myStepper.step(2048);
            delay(500);
            Serial.print('1');
        }
        if (a == '2') {
            automode();
        }
        if (a == '3') {
            digitalWrite(7, LOW);
            myStepper.step(-2048);
            Serial.print('2');
            delay(500);
        } if (a == '4') {
            digitalWrite(7, LOW);
            myStepper.step(-2048);
            Serial.print('2');
            delay(500);
        }
    }
}

void automode() {
    int chk = DHT.read11(DHT11_PIN);
    int AnalogValue;
    AnalogValue = analogRead(A0);
    if (DHT.temperature > 30 && AnalogValue > 600) {
        myStepper.step(-2048);
        timer1();
    } else if (DHT.temperature > 30 && AnalogValue < 600) {
        myStepper.step(2048);
        timer1();
    } else if (DHT.temperature < 30 && AnalogValue > 600) {
        myStepper.step(2048);
        timer1();
    } else if (DHT.temperature < 30 && AnalogValue < 600) {
        myStepper.step(-2048);
        timer1();
    }
    return;
}

void timer1() {
    timer0_millis;
    if (timer0_millis >= 100000) {
        timer0_millis = 0;
    }
    do {
        delay(5);
    } while (timer0_millis < 100000);
    return;
}

Sorry, your code doesn't make much sense to me. You include SimpleTimer, but you are not using it. You declare timer0_millis from extern as volatile, but you are using it just as a simple variable and not inside an ISR. And you use delay() and timer0_millis together.

Do not use timer0_millis directly: it's an undocumented implementation detail, and you have a data race every time you access it. Use millis() instead. See Blink without delay.


text:
How can I stop digital pins from floating at reboot?
I've got a LattePanda 3 Delta, which runs windows on its main processor and an Arduino sketch called StandardFirmata on its coprocessor. It's connected to a lock, which locks at HIGH and unlocks at LOW.
When I boot/reboot the LattePanda, there is a short time window where the lock goes haywire. I've managed to fix the worst of it by explicitly setting default pin values inside setup(), but I guess the pins float before setup() has a chance to run.
The setup() method now looks like this:
void setup() {

  // OUTPUT pins
  for (int i = 0; i <= 6; i++) {
    pinMode(i, OUTPUT);
  }

  for (int i = 18; i <= 20; i++) {
    pinMode(i, OUTPUT);
  }

  // INPUT pins
  for (int i = 7; i <= 13; i++) {
    pinMode(i, INPUT_PULLUP);
  }

  for (int i = 21; i <= 23; i++) {
    pinMode(i, INPUT_PULLUP);
  }

  Firmata.begin(57600);
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.attach(SYSTEM_RESET, systemResetCallback);

  while (!Serial) {;}
  systemResetCallback();
}

Is there a way to set pin values even earlier than setup()? I absolutely need them to NOT float. At all.

You can use external pull-up or pull-down resistors.

You could in principle set the pin state a little bit earlier, by
plugging your code into the C runtime's initialization sequence. This,
however, will only buy you a few microseconds: the pins will still float
at boot. At the software level, there is nothing you can do about it.
This is just how the microcontroller works.
If you need to pins to absolutely never float, you need a hardware
solution: pull them LOW or HIGH with external resistors.

Some micro-controllers have registers which allow controlling the behaviour of some pins during reboots. No idea if that's the case on this one. But indeed, appropriate external resistors would solve the issue.

If one needs to have an external I/O device hold either of two states during a reboot without increasing quiescent current draw, a circuit similar to a "bus keeper" may be useful.

simulate this circuit – Schematic created using CircuitLab
The output will default high on power-up (if the board has a brown-out sensor, substitute that for the RC network).  If the CPU pin outputs high or low, the output will switch accordingly, but if the CPU pin is floating the output will maintain its state.  The specified supply current for a TI quad-NAND 74HC00 is 2 microamps max at 25C, or 20uA max throughout its temperature range.  When the CPU pin is floating, driven high, or driven low, no current will be pulled continuously through the 10K resistor, but a weak pull-up or pull-down could pull could pull continuous current through the resistor; such modes should be avoided when using this circuit.


text:
Arduino Nano 33 BLE power consumption optimization
I am working on building a sensor using Arduino Nano 33 BLE that will measure temperature using two thermistors and angle changes. The measured values will be transmitted over Bluetooth to a smartphone every minute. I have written the code for temperature and angle measurements, as well as remote data transfer. However, I need this sensor to operate for 10 to 21 days on a 3.7v 250mAH battery. To achieve this, I planned to use the Arduino low-power library.
Unfortunately, I have not been able to find a library that is compatible with this Arduino board, nor have I found an example of how to put the board into sleep mode and then measure values every minute. I am aware of the option to power the board directly from a 3.3v source by cutting the 3.3V pads on the back of the board, disabling the power indication diode and turning off the sensors/the I2C pull-up resistors.
I would appreciate any suggestions or solutions to this problem. The full code of the sketch  is below:
#include <ArduinoBLE.h>
#include <Arduino_LSM9DS1.h>
//These  values are in the datasheet
#define RT0 100000   // Ω
#define B 4600      //  K
//--------------------------------------
#define VCC 3.3    //Supply  voltage
#define R 100000  //R=100KΩ

//Variables
float RT, VR, ln, TX0, TX1,  T0, VRT1, VRT0;
unsigned long last_time;
float x, y, z,angleX,angleY;

// Define the BLE service and characteristic
BLEService greetingService("180C");
BLEStringCharacteristic greetingCharacteristic("2A56", BLERead | BLENotify, 30);

void setup() {
  // Initialize BLE
  BLE.begin();

  // Set up the service and characteristic
  greetingCharacteristic.setValue("Hi");
  greetingService.addCharacteristic(greetingCharacteristic);
  BLE.addService(greetingService);

  // Start advertising the service
  BLE.advertise();
  Serial.begin(9600);
  T0 = 25 + 273.15;

  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }

  Serial.print("Accelerometer sample rate = ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println("Hz");
   // Set the initial rotation angles to 0
  angleX = 0;
  angleY = 0;
}

void loop() {

  if (millis()-60000>last_time){
  last_time=millis();
  VRT0 = analogRead(A0);              //Acquisition analog value of VRT
  Serial.println(analogRead(A0));
  VRT0  = (3.30 / 1023.00) * VRT0;      //Conversion to voltage
  VR = VCC - VRT0;
  RT = VRT0 / (VR / R);               //Resistance of RT
  ln = log(RT / RT0);
  TX0 = (1 / ((ln / B) + (1 / T0))); //Temperature from thermistor
  TX0 =  TX0 - 273.15;                 //Conversion to Celsius
  Serial.print("Temperature1:");
  Serial.print("\   ");
  Serial.print(TX0);
  Serial.println("\ C");
  VRT1 = analogRead(A1);              //Acquisition analog value of VRT
  Serial.println(analogRead(A1));
  VRT1  = (3.30 / 1023.00) * VRT1;      //Conversion to voltage
  VR = VCC - VRT1;
  RT = VRT1 / (VR / R);               //Resistance of RT
  ln = log(RT / RT0);
  TX1 = (1 / ((ln / B) + (1 / T0))); //Temperature from thermistor
  TX1 =  TX1 - 273.15;                 //Conversion to Celsius
  Serial.print("Temperature2:");
  Serial.print("\   ");
  Serial.print(TX1);
  Serial.println("\ C");

  IMU.readAcceleration(x, y, z);
    Serial.print("x=");
    Serial.print(x);
    Serial.print("y=");
    Serial.print(y);
    Serial.print("z=");
    Serial.print(z);

    // Calculate the rotation angles using the atan2 function
    angleX = atan2(y, z) * 180 / PI;
    angleY = atan2(x, sqrt(y * y + z * z)) * 180 / PI;

    // Map the rotation angles to the range [0, 360]
    angleX = fmod(angleX + 360, 360);
    angleY = fmod(angleY + 360, 360);

  // Print the rotation angles
  Serial.print("Rotation X: ");
  Serial.print(angleX);
  Serial.print(" degrees, Rotation Y: ");
  Serial.print(angleY);
  Serial.println(" degrees");

  BLEDevice central = BLE.central();
  if (central) {
    // Send the value of x to the connected device
    String message = String(TX0)+"/"+String(TX1)+"/"+String(angleX)+"/"+String(angleY);
    greetingCharacteristic.writeValue(message);
   }
  }
}


text:
I2C Scanner does not recognize LCD screen with 1602 I2C module
I'm sorry to ask this, as it has been asked many times, but I can't get the Arduino micro board to recognize my LCD screens. I've tried using two different LCD screens and two different Arduino micros. I've changed the cables. I even swapped the SCL-SDA around if I'm confusing them somehow. Still getting the mocking:
"Scanning...
No I2C devices found"
I've also tried connecting the cables directly to the Arduino pins, suspecting the breadboard to be faulty.
I measured with the multimeter, and there is a 4.7 ohms resistor between the VCC and the SCL-SDA pins.
And I'm out of ideas.

For Arduino Micro, I2C interface is not on A4 and A5 as per your connection, it is on D3 (SCL) and D2 (SDA). See the official pinmap.
Arduino Micro shares the same pin configuration as Leonardo which you can find here Leonando.

Oh. I feel terribly stupid. Thank you.


text:
Sampling rate for Adafruit LSM6DSOX and Arduino MKR WIFI 1010
Please let me know if this post has the wrong tags, I will make sure to change it.
My goal is to get the highest sampling rate possible from the Adafruit LSM6DSOX (6667Hz) using the Arduino MKR WIFI 1010 and I2C communication.
This is the library I am using: stm32duino/LSM6DSOX, specifically the LSM6DSOX_FIFO_Polling example.
I am trying to measure the actual sampling rate achieved with my code and hardware to find out if my implementation is correct and whether I am facing hardware limitations.
The only modifications to the example from the library were uncommenting Serial.print() statements, moving variable declaration and initialization outside of the loop() and adding my sampling rate calculation. Also removing the comment header in the example code to keep this post shorter.
Code
#include "LSM6DSOXSensor.h"

// #define SR 104 // Sample rate. Options are: 12.5, 26, 52, 104, 208, 417, 833, 1667, 3333 and 6667 Hz.
// #define WTM_LV 199 // Watermark threshold level. Max samples in this FIFO configuration is 512 (accel and gyro only).

// INCREASED SAMPLING RATE AND WATERMARK THRESHOLD LEVEL
#define SR 6667
#define WTM_LV 500

LSM6DSOXSensor lsm6dsoxSensor = LSM6DSOXSensor(&Wire, LSM6DSOX_I2C_ADD_L);

// MOVED VARIABLE DECLARATION AND INITIALIZATION OUTSIDE OF LOOP
static uint8_t wtmStatus = 0; // FIFO watermark status
uint8_t fullStatus = 0; // FIFO full status
uint16_t numSamples = 0; // number of samples in FIFO
uint8_t Tag; // FIFO data sensor identifier
int32_t acceleration[3]; // X, Y, Z accelerometer values in mg
int32_t rotation[3]; // X, Y, Z giroscope values in mdps

// VARIABLES DECLARATION AND INITIALIZATION FOR SAMPLING RATE CALCULATION
unsigned long lastUpdate = 0;
unsigned long totalInterval = 0;
unsigned long currentTime = 0;
int updateCount = 0;
float averageInterval = 0;
float samplingRate = 0;

void setup() {

  Serial.begin(921600);
  // Comment this line to skip waiting for serial:
  while(!Serial) delay(10);

  // i2c, fast mode
  Wire.begin();
  Wire.setClock(400000);

  // Initialize sensors
  lsm6dsoxSensor.begin();
  if (lsm6dsoxSensor.Enable_G() == LSM6DSOX_OK && lsm6dsoxSensor.Enable_X() == LSM6DSOX_OK) {
    Serial.println("Success enabling accelero and gyro");
  } else {
    Serial.println("Error enabling accelero and gyro");
    abort();
  }

  // Check device id
  uint8_t id;
  lsm6dsoxSensor.ReadID(&id);
  if (id != LSM6DSOX_ID) {
    Serial.println("Wrong id for LSM6DSOX sensor. Check that device is plugged");
    abort();
  } else {
    Serial.println("Success checking id for LSM6DSOX sensor");
  }

  // Set accelerometer scale. Available values are: 2, 4, 8, 16 G
  lsm6dsoxSensor.Set_X_FS(2);
  // Set gyroscope scale. Available values are: 125, 250, 500, 1000, 2000 dps
  lsm6dsoxSensor.Set_G_FS(250);

  // Set accelerometer Output Data Rate. Available values are: 1.6, 12.5, 26, 52, 104, 208, 417, 833, 1667, 3333, 6667 Hz
  lsm6dsoxSensor.Set_X_ODR(SR);
  // Set gyroscope Output Data Rate. Available values are 12.5, 26, 52, 104, 208, 417, 833, 1667, 3333, 6667 Hz
  lsm6dsoxSensor.Set_G_ODR(SR);

  // Set FIFO Batch Data Rate for accelerometer and gyroscope. Available values are: 0, 12.5, 26, 52, 104, 208, 417, 833, 1667, 3333, 6667 Hz
  lsm6dsoxSensor.Set_FIFO_X_BDR(SR);
  lsm6dsoxSensor.Set_FIFO_G_BDR(SR);

  /** Set FIFO operation mode. Available values are:
   * LSM6DSOX_BYPASS_MODE: FIFO is not used, the buffer content is cleared
   * LSM6DSOX_FIFO_MODE: bufer continues filling until it becomes full. Then it stops collecting data.
   * LSM6DSOX_STREAM_MODE: continuous mode. Older data are replaced by the new data.
   * LSM6DSOX_STREAM_TO_FIFO_MODE: FIFO buffer starts operating in Continuous mode and switches to FIFO mode when an event condition occurs.
   * LSM6DSOX_BYPASS_TO_STREAM_MODE: FIFO buffer starts operating in Bypass mode and switches to Continuous mode when an event condition occurs.
   * */
  lsm6dsoxSensor.Set_FIFO_Mode(LSM6DSOX_BYPASS_MODE); // flush any previous value in FIFO before start
  lsm6dsoxSensor.Set_FIFO_Mode(LSM6DSOX_STREAM_MODE); // start batching in continous mode

  // Set FIFO watermark level. Can be used to check when the number of samples in buffer reaches this defined threshold level.
  lsm6dsoxSensor.Set_FIFO_Watermark_Level(WTM_LV);

  // FIFO size can be limited to the watermark level by setting the STOP_ON_WTM flag to 1
  //lsm6dsoxSensor.Set_FIFO_Stop_On_Fth(1);

  Serial.println("Starting...");
}

void loop() {

  // MOVED VARIABLE DECLARATION AND INITIALIZATION OUTSIDE OF LOOP
  // static uint8_t wtmStatus = 0; // FIFO watermark status
  // uint8_t fullStatus = 0; // FIFO full status
  // uint16_t numSamples = 0; // number of samples in FIFO
  // uint8_t Tag; // FIFO data sensor identifier
  // int32_t acceleration[3]; // X, Y, Z accelerometer values in mg
  // int32_t rotation[3]; // X, Y, Z giroscope values in mdps

  // Get number of samples in buffer
  lsm6dsoxSensor.Get_FIFO_Num_Samples(&numSamples);
  // Serial.print("Samples in FIFO: "); Serial.println(numSamples);
  // Serial.flush();

  // Check if FIFO threshold level was reached.
  lsm6dsoxSensor.Get_FIFO_Watermark_Status(&wtmStatus);

  if (wtmStatus != 0) {
    // Serial.println("-- FIFO Watermark level reached!, fetching data.");
    // Serial.flush();

    // fetch data from FIFO
    for (uint16_t i = 0; i < WTM_LV; i++) {

      lsm6dsoxSensor.Get_FIFO_Tag(&Tag); // get data identifier

      // Get gyroscope data
      if (Tag == 1) {
        lsm6dsoxSensor.Get_FIFO_G_Axes(rotation);
        // #if 1 // set to 1 for printing values
        // Serial.print("mdps: "); Serial.print(rotation[0]);
        // Serial.print(", "); Serial.print(rotation[1]);
        // Serial.print(", "); Serial.print(rotation[2]);
        // Serial.println();
        // Serial.flush();
        // #endif
      }

      // Get accelerometer data
      else if (Tag == 2) {
        lsm6dsoxSensor.Get_FIFO_X_Axes(acceleration);
        // #if 1 // set to 1 for printing values
        // Serial.print("mG: "); Serial.print(acceleration[0]);
        // Serial.print(", "); Serial.print(acceleration[1]);
        // Serial.print(", "); Serial.print(acceleration[2]);
        // Serial.println();
        // Serial.flush();
        // #endif
      }
    }

    currentTime = micros();

    if (lastUpdate != 0) {
      totalInterval += (currentTime - lastUpdate)/(float)numSamples;
      updateCount++;
    }

    lastUpdate = currentTime;
  }

  // Check if FIFO is full.
  lsm6dsoxSensor.Get_FIFO_Full_Status(&fullStatus);

  if (fullStatus != 0) {
    // Serial.println("-- FIFO is full!, consider reducing Watermark Level or Buffer Data Rate.\nFlushing data from FIFO.");
    // Serial.flush();
    lsm6dsoxSensor.Set_FIFO_Mode(LSM6DSOX_BYPASS_MODE); // flush FIFO data
    lsm6dsoxSensor.Set_FIFO_Mode(LSM6DSOX_STREAM_MODE); // continue batching
  }

  if (updateCount >= 10) {  // Average over 10 cycles to reduce the frequency of serial output.
    averageInterval = totalInterval / (float)updateCount;
    samplingRate = 1000000.0 / averageInterval; // Convert from microseconds to Hz
    Serial.print("Average Sampling Rate: ");
    Serial.print(samplingRate);
    Serial.println(" Hz");

    // Reset for next average calculation
    totalInterval = 0;
    updateCount = 0;
  }

  delay(10); // Small delay to prevent continuous polling
}

Serial Monitor
Success enabling accelero and gyro
Success checking id for LSM6DSOX sensor
Starting...
Average Sampling Rate: 1652.89 Hz
Average Sampling Rate: 1652.62 Hz
Average Sampling Rate: 1652.62 Hz

Questions
Is the sampling rate I am achieving limited due to software (LSM6DSOX implementation, sampling rate calculation) or hardware (I2C communication, MKR WIFI 1010 board)?
How can I find out the optimal FIFO buffer parameters (FIFO mode, watermark threshold level) for this application?
Thanks a lot in advance, any help is appreciated!

If you want to measure the performance, 1) don't do the unrelated calculation, especially with floating point and division as they take several clock cycles, 2) don't do Serial.print() as it is slow even at 961200bps baud rate, your printing of 30+ characters costs 300us+ of time. 3) don't do delay. DO toggle a pin and use oscilloscope or logic analyser to observe the pin and the frequency of the toggle.

thank you for the suggestion, I will try that.


text:
Send data with Serial.write() hex values
I'm using ESP32-C3 as hardware and Arduino IDE as my software core.
I receive a data from MQTT server and want to send it to another board using serial port as a hex number. However, it gets sent over serial port as ASCII characters.
Here is the code
unsigned char messageTemp; //data received from MQTT server
unsigned char cups_qty;    //data to be transferred to serial port

cups_qty = messageTemp;
Serial.write(cups_qty);

For example if I receive messageTemp = 2 and send it to variable cups_qty and then send cups_qty to serial via Serial.write(cups_qty);, I receive the equivalent character not number.
For example :
msg from MQTT          >>>   messageTemp = 2
                             cups_qty = messageTemp;
send over serial port  >>>   Serial.write(cups_qty);

What I see on serial RealTerm terminal
(Display As Ascii)  >>>   2

(Display As Hex)    >>>   32

(Display As int8)   >>>   50

What I want to see on the terminal:
(Display As Ascii)  >>>   something unknown

(Display As Hex)    >>>   02

(Display As int8)   >>>   2

The confusing part is when I write something like Serial.write(2), it works just as expected.

An hex number is, almost by definition, a series of ASCII characters.

The confusing part is when I write something like Serial.write(2), it works just as expected. ... you are doing Serial.write('2') .... the two are not the same ... your question. is not about Arduino ... it is about C++ language

You might want to check by Serial.print(cups_qty, HEX); what data you actually received.

You wrote:

if I receive messageTemp = 2 and send it to variable cups_qty and
then send cups_qty to serial via Serial.write(cups_qty);, I
receive the equivalent character not number.

This is incorrect. If you Serial.write(2) you will receive, at the
other end, a byte with the numeric value 2. Try it!
The function Serial.write() transmits binary numbers as-is, without
attempting any conversion. The following lines:
Serial.write('2');
Serial.write(0x32);
Serial.write(50);
Serial.print(2);

all do the same thing: transmit a byte with the numeric value 50. The
three expressions '2', 0x32 and 50 are just three ways of writing
the same number. Note that, unlike Serial.write(), Serial.print()
formats the numbers in ASCII before transmitting.
It looks like your MQTT server sent you a number in ASCII, which you
probably did not expect. If you know for sure that this is a single
ASCII digit, you can convert it to binary by subtracting the ASCII code
for '0', namely 48:
Serial.write(messageTemp - '0');  // send messageTemp in binary

thank you Edgar for your answer. I did what you have suggested >>> Serial.write(messageTemp - '0');
and it works but only when the received data is just one digit. for example the MQTT server sends 4 payloads>> 2, 80, 4, 5  and after conversion I receive the following over serial port in HEX format >> 0x02 , 0X38, 0x04, 0X05   the data 80 converted to 0x38 which is ASCII format of digit 8!
what do you suggest?
the incoming data could be 1 , 2 or 3 digits

for example I want to receive the data 80 as >> 0X50    or the data 90 as >> 0X5A

@EricMatevosian: You want to read a number that is formatted as a text string. This is called parsing. Search the Web for “Arduino parse number”.


text:
How can you turn a specific LED on a strip on depending on a characters from a string?
I am using a Wrover ESP32 Module and WS2811 lights. I am writing code to turn on LED's depending on letters in a string. Eventually I want to get user input to be the string, but that's irrelevant to my issue at the moment. I have written serialprints in order to troubleshoot and each value in the string prints out when called in the switch statement, but the lights won't turn on when I call for it in the switch statement. I have used other code I have found on github and the lights do work properly when the code is written properly.
#include <FastLED.h>
#define DATA_PIN 18
#define NUM_LEDS 26
#define COLOR_ORDER RGB

CRGB leds[NUM_LEDS];

char var[27] = "abcdefghijklmnopqrstuvwxyz";

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

  FastLED.clear();
  FastLED.show();
  delay(8000);
  Serial.println("Starting setup...");
  FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);

}

void loop(){
  Serial.println(var);

  for (int i = 0; i <= 26; i++) {
    char letter = var[i];
    ITERATE(letter);
  }

}

void ITERATE(char letter) {
  FastLED.clear();
  FastLED.show();
  switch(letter){
    case 'a':
      leds[0] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("a");
      delay(1000);
      break;
    case 'b':
      leds[1] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("b");
      delay(1000);
      break;
    case 'c':
      leds[2] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("c");
      delay(1000);
      break;
    case 'd':
      leds[3] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("d");
      delay(1000);
      break;
    case 'e':
      leds[4] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("e");
      delay(1000);
      break;
    case 'f':
      leds[5] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("f");
      delay(1000);
      break;
    case 'g':
      leds[6] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("g");
      delay(1000);
      break;
    case 'h':
      leds[7] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("h");
      delay(1000);
      break;
    case 'i':
      leds[8] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("i");
      delay(1000);
      break;
    case 'j':
      leds[9] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("j");
      delay(1000);
      break;
    case 'k':
      leds[10] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("k");
      delay(1000);
      break;
    case 'l':
      leds[11] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("l");
      delay(1000);
      break;
    case 'm':
      leds[12] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("m");
      delay(1000);
      break;
    case 'n':
      leds[13] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("n");
      delay(1000);
      break;
    case 'o':
      leds[14] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("o");
      delay(1000);
      break;
    case 'p':
      leds[15] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("p");
      delay(1000);
      break;
    case 'q':
      leds[16] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("q");
      delay(1000);
      break;
    case 'r':
      leds[17] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("r");
      delay(1000);
      break;
    case 's':
      leds[18] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("s");
      delay(1000);
      break;
    case 't':
      leds[19] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("t");
      delay(1000);
      break;
    case 'u':
      leds[20] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("u");
      delay(1000);
      break;
    case 'v':
      leds[21] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("v");
      delay(1000);
      break;
    case 'w':
      leds[22] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("w");
      delay(1000);
      break;
    case 'x':
      leds[23] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("x");
      delay(1000);
      break;
    case 'y':
      leds[24] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("y");
      delay(1000);
      break;
    case 'z':
      leds[25] = CRGB (0,255,255);
      FastLED.show();
      Serial.println("z");
      delay(1000);
      break;
    default:
      FastLED.clear();
  }

  FastLED.show();
  FastLED.clear();
}

I'm sure there is a much better way to go about doing this, if you have any suggestions please feel free to send them my way. I am just curious why the serial print statements work but the FastLED.show() after setting the LED value doesn't.
abcdefghijklmnopqrstuvwxyz
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

This is the output
Thank you

Not sure this is your problem, but calling clear() and show() before addLeds<...>() looks suspicious to me.

there is no reason to use Serial.println("a"); inside the case block ... use Serial.println(letter); in all case blocks ... now do you see how you can simplify your code?

Please try to light up a single fixed LED at the end of setup(). Does that work as expected? (This step can narrow down the problem further)

I think you might have the wrong pin assignment or hardware connection issue. As far as I can tell, the code (although could be reduced significantly) work perfectly fine as it supposed to do (i.e. sequence through the LED based on each character within the var every 1 second).

Hey Edgar, just after I posted this code, I removed the show() just before the addLeds portion and it allowed me to clear the led strip. I am still confused on this however becuase from what I have read, even if you clear the leds, it won't turn them off until you tell the leds to show that they have been cleared, but it works to not have show so I won't complain there.

fair enough jsotola, I wasn't thinking about that when writing the code, however since the individual cases were still reached I don't think its an issue of the letter character, I should still get the same output on the serial monitor right?

chrisl I will do that as soon as possible and come back with the results. I appreciate that idea!

hcheung I was thinking the same thing potentially but I ran code that would simultaneously turn on the first 30 leds and have them be different colors and that didn't have any issues communicating to the individual leds.

hcheung The other code that I have tested only calls FastLED.show() after setting all of the leds to their designated light values. Could it be an issue of the program trying to do too much on my end? I know that arduinos can handle a decent bit of load, but its the only thing I can think of at the moment.


text:
Bending pins of HC-SR04
I got a question regarding the ultrasound sensor (HC-SR04) connecting to the arduino. I have a project, and the space is really tight, so i will have to bend the pins of the HC-SR04. Is this okay to do, and if yes, how should i go about and do this ?

The easiest things to do if space is a premium is to unsolder (or cut) the pins and then solder directly the wire to the corresponding spots.
Otherwise, you can also just get straight pins and replace them, You can also choose on which side of the board, as the holes are though it.
Lastly, about bending, it's doable with pliers if you want to make the pins face "forward" but depending on the quality of your pins they might break in the operation.


text:
ESP 12 unusable pins
The ESP 12 board has 22 pins
Are all of them usable?
I understand that there is an external flash memory that is accessed through SPI, but I'm not sure what the impact on the pins is.
And if it is so, then why are the pins available?
Is there a sort of a decoder board that receive as an input, let's say 3 SPIOs and outputs 8 GPIOs?
Is there a way to obtain more GPIO pins?

Like this one?  https://researchdesignlab.com/esp8266-esp-12-breakout-board.html

The flash memory is connected to io 6 to io 11 if it is connected in QIO mode. DIO mode lets two of the pins free. According to Arduino core reference the two pins are 9 and 11. The flash pins are labeled SD and most of them are the first SPI interface of the esp8266. You can't use this SPI pins as digital pins, but supposedly you can connect another SPI device.
Some of the esp8266 'free' pins have some restrictions. Boot configuration pins io 0, io 2 and io 15 need to have some state at boot. io2 not LOW, io 15 LOW and with io 0 flashing mode is activated. The A0 is ADC only pin. And you can't count power, EN, Reset and ground as 'pins'.
You can use a multiplexer or an I2C expansion board to get more pins.


text:
Dimming multiple leds with pot meter
I'm working on a small project. I have 13 leds which need to be controlled individually (turn on or turn off);
Since I don't have 13 pwm pins I used a potentiometer to change the brightness.
This works fine for as long as all of the leds stay in the state they are. But once one led turns on or off it affects the brightness of all other leds.
In the picture below you can see how I did connect them.
I have the analog pins A0, A1, A2 and A3 occupied by some buttons.
Does anyone know how I can dim the leds in a way where the leds themselves don't affect the brightness?
(note: I am a programmer and not so much of an electrical engineer. Code-related answers are (usually) easy for me to understand. ones about the hardware are not.);

Maybe an extention board like this one from Adafruit, which gives you 16 individual PWM outputs

from Tour: "Don't ask about...    Any question that doesn't require knowledge about the Arduino platform to answer (try Stack Overflow for general coding questions or Electrical Engineering for general electronics questions)"

@chrisl Thanks for that suggestion! It is a bit expensive, but I'll look into it. Do you by any chance know if I can connect multiple I2C boards to an arduino?

@Juraj I guess you're right. Chrisl's suggestion does require a bit of arduino knowledge though, and because I don't have a complex circuit I personally think this forum would be a better place. I want a solution to this problem, and it doesn't have to be purely an electrical engineering solution :)
(I'll keep it in mind for next time though. Thank you for mentioning it)

Read the pot with analogRead(). Do not connect it to the LEDs at all, just 5v, Gnd and wiper to A5 (any of the analog input pins).
LEDs just go from resistor on one leg to Gnd on the other (or 5V, depends on whether anode or cathode is connected to the resistor).
Then use software PWM to control the LEDs.
For example:
byte potPin = A5;
int potValue;
byte ledPin[] = {2,3,4,5,6,7,8,9,10,11,12,13,14};
byte x;

void setup(){
  for (x=0; x<13; x=x+1){
  pinMode (ledPin[x], OUTPUT);
  }
}
void loop(){
potvalue = analogRead (potPin); // 0 to 1023 value
for (x = 0; x<13; x=x+1){
  digitalWrite (ledPin[x], HIGH);
  delayMicroseconds(potValue);
  // 0 = max brightness, 1023 (1.023mS) will be dimmest
  // manipulate potValue if 1023 is not dim enough - double it, triple it, etc.
  digitalWrite (ledPin[x], LOW);
  delayMicroseconds(potValue);
  }
 }

From here, you can play with other setups for controlling the brightness.

the question is "But once one led turns on or off it affects the brightness of all other leds.". Does this solve it?

@Juraj It works like normal pwm, but this would make it rather tricky to do while the arduino needs to do other things, especially ones where 'delay()' is used. It is the main reason why I don't think his suggestion would be suited for my project. Otherwise I think it should work.

Wouldn't be hard to change this to Blink Without Delay style of code, and getting rid of the delayMicroseconds().

but doesn't the overall brightness problem origin in wiring of the LEDs (serial v. parallel)?

The LEDs as pictured only share a common Gnd or +5. They are not wired in serial or parallel - each has its own driver (an Arduino output pin).

The other code takes up time, and the leds will be max brightness when I'm doing some light effects, but after some tweaking I managed to find a working hand-written PWM-ish way to change their brightness. It took me a couple of days before I came up with the idea how I could implement it, but it works almost perfectly now. Thank you for the suggestion!

Glad you got it working well.


text:
How do I get the request params from a ESPAsyncWebServer?
I currently have the following code
server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("ON hit.");
    String message;
    Serial.println(request->url());
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = " not specified";
    }
    request->send(200, "text/plain", "On, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);
....

When sending in a request I get the out put, "Device not specified".
I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:
server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("OFF hit.");
    String message;
    int params = request->params();
    Serial.printf("%d params sent in\n", params);
    for (int i = 0; i < params; i++)
    {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isFile())
        {
            Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
        }
        else if (p->isPost())
        {
            Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
        }
        else
        {
            Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
        }
    }
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = "not specified";
    }
    request->send(200, "text/plain", "Off, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);

and get the output now of
1 params sent in
_POST[device]: puddle
Device not specified

If I try to do something like request->getParam(0)->value().c_str()
I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.

try hasParam("device", true)

usually params are for GET while POST has a separate interface

@Juraj that was it. Want to make an answer? Lol, feel pretty silly.

just in case, someone finds this snipplet:
In addition to @Juraj (correct) answer: If you want to access this param you also have to inform the function, that you want the url parameters:
message = request->getParam("device", true)->value();

For POST request the hasParam needs to know if you want to test the url parameters or x-www-form-urlencoded parameters in body of the POST request. The second parameter of the hasParam is boolean post and it has default value false. Use hasParam("device", true).


text:
Having some issues with an array
I am having an issue that I can't seem to get my head wrapped around.  What I am trying to accomplish is to have a minutes worth of sensor data in an array (reading every 5 seconds) so I'll have 12 values in this after one minute.
I want to keep the array to 12 values so I need to keep moving all the values in it down one index per new value hitting index [0] to make sure that each reading has a lifetime of 60 seconds on the array.  Here is my code so far:
void add_readings_to_averages() {
  // At this point, I am moving values down the array to make room at the beginning.
  for (int a = 11; a >= 0; a--) {
    Serial.print("The value at temperature_c_minute_avg[");
    Serial.print(a);
    Serial.print("] is ");
    Serial.print(temperature_c_minute_avg[a]);
    Serial.println();
    if (a == 11) {
      Serial.println("At 12 so need to overwrite this value");
    }

    if (a <= 10) {
      Serial.print("a is ");
      Serial.println(a);
      temperature_c_minute_avg[a] = temperature_c_minute_avg[a + 1];  // This moves each entry down one index in the array creating an empty space at index[0]
    }

    if (a == 0) {
      temperature_c_minute_avg[a] = temperature_c;
    }
  }

I've loaded my array at the time of initialization with some dummy data so I could see what was going on.  First run displays as you would expect.
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 110.00
a is 10
The value at temperature_c_minute_avg[9] is 100.00
a is 9
The value at temperature_c_minute_avg[8] is 90.00
a is 8
The value at temperature_c_minute_avg[7] is 80.00
a is 7
The value at temperature_c_minute_avg[6] is 70.00
a is 6
The value at temperature_c_minute_avg[5] is 60.00
a is 5
The value at temperature_c_minute_avg[4] is 50.00
a is 4
The value at temperature_c_minute_avg[3] is 40.00
a is 3
The value at temperature_c_minute_avg[2] is 30.00
a is 2
The value at temperature_c_minute_avg[1] is 20.00
a is 1
The value at temperature_c_minute_avg[0] is 10.00
a is 0
2018/11/2 11:4:39  -  Running for a total of 0 hours 0 minutes and 7         seconds

But the second time through the loop() my array is trashed.
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 120.00
a is 10
The value at temperature_c_minute_avg[9] is 120.00
a is 9
The value at temperature_c_minute_avg[8] is 120.00
a is 8
The value at temperature_c_minute_avg[7] is 120.00
a is 7
The value at temperature_c_minute_avg[6] is 120.00
a is 6
The value at temperature_c_minute_avg[5] is 120.00
a is 5
The value at temperature_c_minute_avg[4] is 120.00
a is 4
The value at temperature_c_minute_avg[3] is 120.00
a is 3
The value at temperature_c_minute_avg[2] is 120.00
a is 2
The value at temperature_c_minute_avg[1] is 120.00
a is 1
The value at temperature_c_minute_avg[0] is 0.00
a is 0
2018/11/2 11:4:44  -  Running for a total of 0 hours 0 minutes and 12     seconds

The entire array was overwritten with the last value and the new value was not added.  The array itself is setup as a global variable.  The initialization at the top.
float temperature_c_minute_avg[12] = {10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0,120.0};

What am I missing here?  Been staring at this for some time, but this is the first time I've tried to use an Arduino array so I can totally believe the issue is PBKAC! :)

I'm voting to keep this question open. According to this page: https://arduino.stackexchange.com/help/on-topic, "On topic" includes "Specific questions about Arduino boards, code…".

Your issue is a C programming issue and has nothing to do with the Arduino specifically.  You should research how to implement a circular buffer.  You don't want to move around the values within the array, but rather just increment array index values.  Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded.  Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment.  When the array index exceeds the maximum array size it wraps back to 0.

Guys, thanks for the assistance.  I've gone down the path of a circular buffer to solve this.

In your if (a <= 10) block, you are inside a for loop that is decreasing and replacing each value with the value inside index+1. This means that as you are going down the indices, you are carrying the 11th index value with you. Here is how it is without variables (allow me to shorten the variable name to t):
t[10] = t[11];
t[9] = t[10];
t[8] = t[9];

And so forth. Whatever was in a[11] is being dragged through each of the variables of lower indices.
I strongly suggest going the other way around with either your loop or which way you are pushing the data. For instance (continuing with array name t):
for (int i = 11; i >=0; i--) {
    if (i > 0)
        t[i] = t[i-1]; // shift data from index 10->11, 9->10, etc.
}
t[0] = arbitrary_data; // fill in new 'empty' space

Or, alternatively if you still want to put new data in index 11:
for (int i = 0; i <= 11; i++) {
    if (i < 11)
        t[i] = t[i+1]; // shift data from index 1->0, 2->1, etc.
}
t[i] = arbitrary_data; // fill in new 'empty' space

This is my solution for your current data management method. Another answer suggested a circular buffer where you simply keep track of which datum is being changed at a time and is far more efficient.


text:
Is there a way to have the LED switch on after 10 readings or say a minute?
I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.
I have tried doing various if loop much to my failure, below is the code I am currently using:
#include <RFID.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED_PIN A0

RFID rfid(SS_PIN, RST_PIN);
int serNum[5];
String cardno;
int interval = 15000; // millisec
long now = 0;
long lasttime = millis();
// change Reader ID to your name
String readerID = "Reader_001";

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
  pinMode(A0, OUTPUT);
}

void loop() {
  now = millis();
  if (now > lasttime + interval) {
    lasttime = now;
    Serial.print(readerID);
    Serial.print(":");
    Serial.println("I am alive");
  }
  if (rfid.isCard()) {
    if (rfid.readCardSerial()) {
      lasttime = now;
      cardno = String(rfid.serNum[0]) +
               String(rfid.serNum[1]) +
               String(rfid.serNum[2]) +
               String(rfid.serNum[3]) +
               String(rfid.serNum[4]);

      Serial.print(readerID);
      Serial.print(":");
      Serial.println(cardno);
    }
  }
  rfid.halt();
  delay(10000);
}

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

first thing to do is to correct the indentation of your code so that the code blocks are clearly visible ...... that will help in determining where to place the code that counts the number of repetitions

Ditch the delay() and work only with millis(). Use a counter variable, that is incremented on every read. In the loop you can check for it being >=12 and turn on the LED.

since I am a beginner would it be too much to ask for an example?

You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:
Inside your void loop() function you use the millis() coding style (refer to the BlinkWithoutDelay example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:
#define READ_INTERVAL 10000
int read_counter = 0;
unsigned long read_timestamp=0;
String last_identifier="";
void loop(){
    if(millis()-read_timestamp>READ_INTERVAL){
        // Read the chip
        if(card_identifier == last_identifier)
            read_counter++;
        else
            read_counter = 1;
        if(read_counter>=12){
            digitalWrite(LED_PIN, HIGH);
        }
    }
}

Be sure to use unsigned long with the millis() function, to prevent it from overflowing to a negative value.

Do you also have any suggestions for connecting two arduinos? both my arduino projects are rfid access control, this being the first one the second one is simple rfid but the access on that needs to depend on the output of the first rfid

i am thinking of doing a SPI master and slave? would you recommend that

Yes, that should be possible. This also depends on the distance between the Arduinos