message:
Unexpected output for simple code involving calculating a time interval of 10ms

I had written some code that involved doing something after 10 milliseconds had elapsed, however it was performing unexpectedly. Upon debugging, I think I have identified the error, and I wrote some code with *just* that block:

    unsigned long int newtime=0;
    unsigned long int prevtime=0;
    int time;
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
    newtime=millis();
    time=newtime-prevtime;
    if(time==10){
      Serial.println(prevtime);
      prevtime+=10;
    }

    }
The serial monitor "freezes on 150. it shows the values 0,10,20...as expected but it freezes on 150...and then nothing happens.

What exactly is causing this?

body:
your logic is just tricky to confuse. It is repeatable because along as you not change the if logic, the code is going to run till it displays 150. then it will stop. You can also check the same behaviour [here][1]

Once the time difference is not exactly equal to 10, the if part will not be executed. Hence, the `prevtime` will not catch up with the `newtime` anymore. newTime will soon grow to be bigger and the difference will always be greater than 10.

I suggest visiting https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay to get some hints on tracking time in a safer way.

  [1]: https://wokwi.com/arduino/projects/297224412670722569


sender: user

sender: assistant

body:
The problem is, that you are filling up the Serial buffer rather fast, because you try to send ASCII numbers every 10ms at only 9600ms. When the buffer is full, `Serial.println()` will wait, until there is enough space free in the buffer for the current data. That makes your loop lasting significantly longer.

In that case the time, where the `time` is exactly 10 is missed. Thus the code does nothing at that point, until time rolls over and gets 10 again (48 days I think).

While you can mitigate the problem by using a higher baudrate, the main problem is still

    if(time==10){

You have only provided an example code. Your real code might sometimes take longer than 10ms out of some other reason (actually this already gets critical, when the loop takes longer than 1ms, since it then might already miss the one moment, where `time` is 10). To futureproof your code and make sure, that you don't hunt down the same bug again and again, you should do, what you were told in the comments, and use

    if(time>=10){

Depending on your code the event will still happen after 10ms the absolute most of the time. But this variant also doesn't break, if the loop takes longer than 10ms sometimes.


message:
How do I make my Arduino do a specific action when the computer is locked/unlocked?

I have a windows computer connected to my Arduino Uno. I work in a area with a bunch of cubicles and we leave our desk fairly regularly to go and troubleshoot other computers (I'm a service desk technician).
When we leave we are instructed to raise and lower a small flag so management can see whether or not we are sitting at our desk. I've attached my arduino to a servo motor with the following code.

```

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =0;    // initial angle  for servo
int angleStep =20;
const int minAngle = 0;
const int maxAngle = 90;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Nathan's Status flag");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }
}

```

We also have a policy that we need to keep our computers locked for obvious reasons. I learned my lesson with that early on. I would like to edit my code so that when I lock my computer the flag goes down, then when my computer is unlocked it goes back up. That way as long as I remember to keep my computer locked when I'm away I don't have to worry about the flag. Here is my breadboard/arduino layout.
[![Arduino Layout][1]][1]
I also have processing on my computer and am planning on using that. (https://processing.org/)

Any help is greatly appreciated.

  [1]: https://i.stack.imgur.com/Khat5.png

body:
Read a value through serial (what exactly is entirely up to you) to do the same job the button does now.

Use `Serial.read()` to get that data, and `Serial.available()` to know if there is any data to read.

How you generate that value on the PC to send through serial we cannot help you with, as that is outside the scope of this site.


message:
Why is my Arduino Nano's buzzer clicking?

[![enter image description here][1]][1]

EDIT: I'm so sorry but the clicking wasn't coming from the Arduino **but from the piezo buzzer!** I was wrong and I'm so sorry for misguiding you!

I recently bought an Arduino Nano so that I could downsize my arrangement with my Arduino Uno so I soldered everything together and when I plugged in the Nano I extra made sure that nothing was shorting each other out. But the buzzer attached to it kept making this clicking noise. Does anyone know why? Do I actually have a short-circuit?

Here is the code:

```

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

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

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

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

}

void loop() {

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

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

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

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

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

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

case 6:

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

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

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

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

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

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

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

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

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

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

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

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

  case 19:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);

      tone (11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,329.63);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone (11,196.00);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone (11,493.88);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11, 329.63);
      delay(150);

noTone(11);

old = state;
state = 0;
old = 0;

    break;

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

    old = 0;

    break;
}

}

  }
```

Here is a video of the clicking:
https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

  [1]: https://i.stack.imgur.com/d95tA.jpg

body:
The simpler piezos click when a voltage is applied, and again when it is removed. To make it buzz, it needs a pulse-train: many clicks makes a buzz. There are piezos that have that feature built-in, but I'm guessing yours hasn't. That's actually a Good Thing in disguise: it allows you to make tones by making pulse-trains at different frequencies. The easiest way to do that is to connect it to one of the PWM pins (5, 6, 9, 10, or 11) and use the `tone()` library-function (look it up if you need to). Of course, you can do it "manually", too, on any output pin, just by switching it HIGH and LOW at rates that you choose, but that will pretty much tie up your processor, at least for higher frequencies.

Update:

> Just why wasn't it clicking when I connected it to the Arduino Uno?

I can't tell without seeing the two sketches but in your video, it sounds like it is being turned on or off, or pulsed, once per second.

Please add your code (both of them, if they're different) to your question. Wiring diagram(s) of the piezo connection to the Arduino boards would help, too.


message:
Is it possible to read extended ASCII from the serial port?

My project requires that `Serial.read()` be able to accept extended ASCII characters (`0x80` <=> `0xFF`). For example, I would expect reading the character `¥` to yield the decimal value `157`. Instead, the `read()` command has two successful reads, with the values: `194` and `165`. Of course, I could create a lookup table and convert, but this is not a viable option. I am conforming to the `Grbl` standard protocol, which uses these single-byte extended ASCII characters as **interrupts**. Such a two-byte structure precludes a simple peek/read approach necessitated by the protocol.

**Edit** I tried to simplify the question for this context, but failed to account for the fact that the Arduino IDE will send the input as Unicode. Regardless, it still does not work when sending bytes directly. Namely, if I send the byte `0x93` via C# as `Serial.Write("\u0093")`, the Arduino's `Serial.read()` does not see any bytes available. Sending normal ASCII, e.g., `Serial.Write("\u0018")`, works fine.

body:
Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.

Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.

If you want to use the Grbl protocol, send interrupts as _bytes_, do not
think about them as “characters”.


message:
Simulate motor encoder quadrature signals using an Arduino UNO

I'm supposed to write a raspberry pi and arduino code to read the RPM of a motor with an encoder attached to it. However, I'm having weird numbers and I'm unsure about the specs on the motor and the encoder. So I thought it would be smart to use a second arduino to simulate the motor with encoder.

The simulator would need to produce a 2 signals representing the two signals from the encoder. I want to be able to set the frequency and phase shift of these signals in software to imitate changes in speed and direction of the motor rotation. Forward would have one signal 90 degrees ahead, and then reverse having that same signal to be 90 degrees behind. So phase difference of plus or minus 90 degrees.

I'd like to eventually have the simulator be able to simulate motor actions like oscillating between forward and reverse 5 seconds each, or forward for 5 seconds and then stop completely.

I found this [code by bigjosh][1] which is more or less what I want to do. However, that code doesn't allow for a shift of -90 deg by default. I know there's a comment there to change it, but I'm not knowledgeable enough to understand what's going on exactly. I'd like someone to help me with that.

  [1]: https://electronics.stackexchange.com/a/174759/33966

body:
Wow, that turned out to be way harder than I expected. It is very hard to do cleanly on the AVR timer. But I was able to come up with this working function, which I think is what you are looking for...

```
// freq_hz is frequency in hertz from 122 to 4,000,000
// shift_deg is phase shift between output A and output B in degrees (values outside -180 to +180 are normalized)

// Note that at frequencies above 44KHz you will loose precision on phase shift. At 4Mhz, everything is rounded to just 0 or +/-90 degrees.
// Note that all timing happens in 1/16Mhz increments, so frequencies that do not land on integer multipules of that will be aproximiate.
// Use startWaveforms() directly for more precise control.

void startQuadrature( unsigned long freq_hz , int shift_deg  );
```

It can glitch at start-up, shutdown, and changes in speed and direction... but so can a motor encoder so I guess that is ok. It would be possible to create a glitch-free version but more work.

Github repo here...
https://github.com/bigjosh/Quadrature

So, to simulate a motor going forward with 50KHz pulse rate, you would use something like...

`startQuadrature( 50000 , +90);`

...and the same pulse rate going backwards would be...

`startQuadrature( 50000 , -90);`

Do note that if you connect an Arduino UNO output pin to a Raspberry Pi input pin that it will likely damage the Pi. This is because the UNO outputs 5 volts for a "1" signal, but the Pi can only tolerate a maximum 3.3V on any pin. You can google "5V 3.3V level shifting" for solutions to this problem.


message:
unexpected behaviour of encoder with increasing rpm

I am using a DC motor with encoder, and I am trying to calculate how many pulses are  recorded in every one second interval. (note that the power source is of 12V for the motor)

**Circuit and code:**

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/NpmQC.jpg

    int encpin=3;
    volatile long npc=0; //new pulse count
    volatile long opc=0;  //original pulse count
    volatile long pulsecount;
    unsigned long int newtime;
    unsigned long int prevtime=0;
    unsigned long int time;
    void setup()
    {
      pinMode(encpin, INPUT_PULLUP);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
    }
    void function(){
      npc++;
    }
    void loop()
    {
     newtime=millis();
     time=newtime-prevtime;
     pulsecount=npc-opc;
      if(time==1000){
        Serial.println(pulsecount);
        prevtime+=1000;
        opc=npc;
      }
    }

It seems to be rather intuitive that increasing the rpm should increase the number of pulses recorded in one second. However, the results are rather erratic:

     RPM  PULSECOUNT
      26    2365
      32    2367
      38    2400
      44    2375
      52    2400
     116    2412
     142    2384
     195    2416
     280    2406
     350    3008
     416    1580
     520    1975
     624    2370
     730    2334
    2737    2188

**Increasing RPM sometimes increases the pulsecount, but sometimes decreases it....what could be the reason for this behaviour?**

body:
I think the problem is in the tinkercad simulation:
The encoder is attached to the motor and the motor is always rotating at the same speed. Selecting a different RPM on the component changes the gear ratio and the RPM of the shaft, but not of the motor. That means that the number output after 1s should be always the same.
Why it is not exactly the same, only the programmers of the simulation can tell.
It might have to do with simulation speed, because I get totally different numbers there.

To tell exactly what is going on, a documentation of the components in the simulation and of the simulation would be necessary.


body:
One important principle to learn when working with interrupts is that of *atomic operations*.  It is vital, when working with any data that cannot be manipulated by one single assembly instruction, that you protect against that data being changed midway through any reading of that data.

In your situation you are working with 32-bit values. On an 8-bit microcontroller those take many many instructions to manipulate, and at any time during that manipulation the interrupt can be triggered and change the value, corrupting your readings.

There is a concept in programming called *critical sections*. These are "blocked off" bits of code where no interrupts are allowed to happen while you do whatever is needed to your shared variables. For obvious reasons you want to keep those sections as brief as possible.

Also you don't need to calculate the pulse count by comparing it to the previous count - just start from 0 each second. And on the topic of a second, it's best to check if *at least* a second has passed. There's always a chance you may see 1001ms instead of 1000ms. A slim chance, but best to be safe.

Here's an example, using your code as a base:

```c++
void loop() {

    if (millis() - prevtime >= 1000) { // you should check for more time passing than you expect
        prevtime += 1000; // Don't assume you always had 1 second, force it instead

        // This block is the "critical section". Keep it as short as possible
        // so just grab the data and reset the count.
        noInterrupts(); // Stop any interrupts happening
        uint32_t currentCount = npc; // Grab this second's count
        npc = 0; // And reset the count to zero
        interrupts(); // Release the block on interrupts

        // And output the results.
        Serial.println(currentCount);
    }

}
```


message:
void declaration error

I am new to Arduino and C++ and I was practicing with a traffic light project.

This is my code:
```cpp
int red = 10;
int yellow = 9;
int green = 8;

void setup() {
  pinMode(red,OUTPUT);
  pinMode(yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  changelights();
  delay (15000);
}

void changelights{
  // 1st action: green off to yellow
  digitalWrite(green, LOW);
  digitalWrite(yellow, HIGH);
  delay (3000)
  // 2nd action: tellow to red
  digitalWrite(yellow, LOW);
  digitalWrite(red, HIGH);
  //3rd action: caution light
  digitalWrite(yellow, HIGH);
  delay (3000)
  //4th action: caution to go
  digitalWrite(red,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, HIGH);
}
```
I tried compiling it and returned an error message that said that I did not declare my "changelights" function. What should I do to fix this?

Thank you very much

body:
You forgot to put the parenthenses `()` after the name of the function `changelights`. They are there to declare variables you can use later in the code like that:
```cpp
void function(int a){
  a+=1;
  return a;
}
```
To fix your error just change
```cpp
void changelights{
```
to
```cpp
void changelights(){
```
Keep in mind if you want to program C++ (which would be Off-Topic here, but you mentioned it in your question) you have to declare the function in the beginning or mention it.


message:
Arduino ADC converter calculation

I am trying to choose a wire encoder for my project. So far, I found this wire encoder (see [link][1]). Assuming the measurement range of my cylinder is 1 m. Then, with a 10 bit ADC converter of my Arduino Mega2560, I would have a resolution of 0.09cm (= 100cm/1024). But, lets say some cylinder only have a measurement range of 0.5m. Then the resolution would be 0.048 (=50cm/1024).

I can see that I am missing something here, because the resolution of the later case should be worse than the case with the full measurement range 1m. I would be appreciate for any tipps.

--------

Edit:

 - Cylinder's movement range 0~1m
[![enter image description here][2]][2]
 - Wire encoder's measurement range 0~1.25m
[![enter image description here][3]][3]
 - Wire encoder's analog output 0~10v
 - ADC resolution 10 bit

  [1]: https://www.sick.com/de/en/encoders/wire-draw-encoders/ecoline/bcg05-l1km01pp/p/p332388
  [2]: https://i.stack.imgur.com/kYyvf.png
  [3]: https://i.stack.imgur.com/ekvLy.png

body: Your calculation is not correct. The encoder has its 0 to 10V output voltage distributed over the whole distance, that the cable can reach, so 1.25m. And that gives you the resolution: `1.25m/1024 = 1.22mm`. The resolution doesn't change, if you use less than the maximum length. It's still the same resolution of about 1.22mm. The encoder doesn't care, if you are only using 1m of its range.


message:
Node MCU not functioning correctly

i have a node mcu and i uploaded one example code to test it for rf signal decoding it worked. so after that i have written a code based on that and when i uploaded the code my node MCU suddenly isn't working as it should be. It is giving out some random things onto the serial monitor like this:

```
⸮L⸮⸮⸮ՋR(⸮⸮^⸮̓#⸮⸮;'⸮⸮(Zs"⸮⸮Z|⸮⸮⸮'⸮⸮⸮'⸮⸮⸮!#⸮⸮⸮G⸮⸮⸮⸮⸮h⸮y⸮⸮⸮⸮'⸮⸮LD⸮⸮J⸮*J⸮⸮⸮⸮⸮⸮⸮LD⸮⸮⸮⸮F(⸮y⸮⸮؁'1⸮L⸮⸮⸮
```

THE CODE:
```
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <RCSwitch.h>
BlynkTimer clocktime;

#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

#define VPIN_BUTTON_1    V12
#define VPIN_BUTTON_2    V13
#define VPIN_BUTTON_3    V14
#define VPIN_BUTTON_4    V15

RCSwitch mySwitch = RCSwitch();

int relayfanstate = HIGH;
int relaylightstate = HIGH;
int relaylightbstate = HIGH;
int relayrandomstate = HIGH;
int mainstate = HIGH;
long code;

char auth[] = "rJUG7fhgXk9Y7OlowTontA1C2irfpgs2";

const char *ssid =  "Nag";
const char *pass =  "87654321";

BLYNK_CONNECTED()
{
  Serial.println("blynk connected first function");
  Blynk.syncVirtual(VPIN_BUTTON_1);
  Blynk.syncVirtual(VPIN_BUTTON_2);
  Blynk.syncVirtual(VPIN_BUTTON_3);
  Blynk.syncVirtual(VPIN_BUTTON_4);
}

BLYNK_WRITE(VPIN_BUTTON_1)
{
  Serial.println("blynk write");
  relayfanstate = param.asInt();
  digitalWrite(relayfan, relayfanstate);
}

BLYNK_WRITE(VPIN_BUTTON_2)
{
  Serial.println("blynk write");
  relaylightstate = param.asInt();
  digitalWrite(relaylight, relaylightstate);
}

BLYNK_WRITE(VPIN_BUTTON_3)
{
  Serial.println("blynk write");
  relaylightbstate = param.asInt();
  digitalWrite(relaylightb, relaylightbstate);
}

BLYNK_WRITE(VPIN_BUTTON_4)
{
  Serial.println("blynk write");
  relayrandomstate = param.asInt();
  digitalWrite(relayrandom, relayrandomstate);
}

void setup()
{
  Serial.begin(9600);
  mySwitch.enableReceive(0);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
  WiFi.begin(ssid, pass);
  Serial.println("wifi config done");
  Blynk.config(auth);//, ssid, pass);
  Serial.println("Blynk config done");
}

void loop()
{

  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Not Connected");
    Serial.println("Without internet rf code recieving started");
    delay(500);
    if (mySwitch.available())
    {
      Serial.println("Switch available");
      code = mySwitch.getReceivedValue();
      if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
    }
  }
  else
  {
    Serial.println(" Connected");
    Blynk.run();
    with_internet();
  }
  clocktime.run();
}

void with_internet()
{
  Serial.println("With internet rf code recieving started");
  delay(500);
  if (mySwitch.available())
  {
    Serial.println("Switch available");
    code = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_1, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        Blynk.virtualWrite(VPIN_BUTTON_1, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        Blynk.virtualWrite(VPIN_BUTTON_1, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
  }
}
```
can anyone tell me what is wrong with my code or my nodemcu module?
Is it because i uploaded two codes one after the other and messed up the module?

body:
> Can anyone just try to upload this code to their node MCU with
> changing the WiFi credentials and the blynk Auth token to one of your
> own project by following the blynk guide and check if it is connecting
> to blynk and it's only a problem with my module or there is some
> problem in my code

This might be necessary to see more problems.  But it isn't necessary to see at least one important one.  Here's what I cut your code down to:

```c++
#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

void setup() {
  Serial.begin(9600);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
}

void loop() {
  Serial.println("loop()");
}

```

So, you have:
```c++
#define relaylight 6
```

One thing to make clear about here is that this is **GPIO**6, and **not** `D6`, which would [be mapped to][1] GPIO12, which would make more sense.  GPIO6 is actually used internally to the ESP8266 module to access the SPI flash chip that stores your code.  Basically when you do this:

```c++
pinMode(relaylightb /* GPIO6 */, OUTPUT);
```

you're kind of ripping the rug out from underneath the the microcontroller inside the ESP8266 module.  It's a bit like reaching into a computer and pulling out harddrive while it's running.  It's trying to load code and data from the SPI flash, but you've reconfigured that pin.

The ESP8266 brings code from SPI flash into some smaller chunk of internal RAM that it executes the instructions from.  So, I suppose it might be possible to get in the situation where you're continuing to run cached instructions while trying and failing to load data from the spi flash, which maybe could explain part of why the problem manifests the way it does for you.

In case you're wondering, it is possible to get the microchip used in the ESP8266 to load code from sources other than SPI flash, in which case GPIO6 might actually be available for your own general purposes, but not with the way most of modules are set up and used.  If you look at the pinout for the common ESP8266 modules, the smaller board mounted to your NodeMCU board, you'll notice GPIO6 doesn't actually leave the module; it just goes from the microcontroller to the SPI flash chip, which is all hidden away under the RF shield on the NodeMCU.

There *may* be other problems here with pin selection.  E.g., GPIO7 is not mentioned in the pin mapping, nor does it seem to leave common modules, so `#define relaylightb 7` is a bad sign.  Have a look through [this guide][2] with regard what you can do with each pin and what sort of behaviours they have at boot.  E.g. GPIO2 (your `relayrandom`) is "pin is high on BOOT, boot failure if pulled LOW" according to the guide.  So perhaps it will pulse your relay which you might not like.  And it may be that whatever circuit you have for the relay tugs GPIO2 toward LOW, which would also be bad.  Do keep in mind that the D# labeling is different from the GPIO# labeling.

---

I just checked GPIO7 (`randomlightb`), and like GPIO6 (`randomlight`), it was sufficient to execute `pinMode` with `OUTPUT` on it cause a reset.

  [1]: https://github.com/esp8266/Arduino/blob/2.7.4/variants/nodemcu/pins_arduino.h#L40
  [2]: https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/


message:
ESP8266: Interfacing MAX485 TTL-to-RS485 on serial port

I am using the ESP8266 NODEMCU.
I am aware that the CH341 on the NodeMCU is bridged to the serial pins GPIO3(Rx) and GPIO1(Tx).
Hence, any data send on Rx and Tx is also visible on the serial monitor.

I need to interface MAX485 TTL-to-RS485 to the ESP8266 on different serial pins (other than GPIO3 and GPIO1).

Is there a way to configure other pins as Rx and Tx?

Please suggest any other ways to achieve this.

EDIT-1:
I need to use two serial ports at the same time (one with the CH341 and another with TTL-to-RS485). Please help with this.

body:
You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.

Also you need to use the MAX**3**485 on 3.3V devices. The MAX485 is for 5V devices.


body:
Regarding this:

> Please suggest any other ways to achieve this.

The `SoftwareSerial` mention in Majenko's answer is one of those other ways.

[There's also][1] a `.swap()` function on the Serial interface that will remap the UART from its normal position talking to the host to GPIO15 and GPIO13.  If you only need to talk to one device at a time, that may also be an option.

There's also a second transmit-only UART (also mentioned in previous link), so if you only need to transmit on one of the interfaces, that is an option.  And there's the possibility of using the transmit-only UART together with using `SoftwareSerial` (or something like it) to complete the receive half.

Another option might be interpose a SPI-interfaced UART chip, between the ESP8266 and the RS485 transceiver, so that it's just SPI from the ESP8266 side.  It is also possible to find chips that are combined SPI-UART/RS485-transceiver, although the only one I've noticed thus far is a 5V part.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/reference.html#serial


message:
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back

Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.

I just cant seem to figure out the mapping or setup for the code for this part.
I remember seeing it done before but my google skils are failing me and i cant seem to find it again.
Thanks

body:
You can use the `map` function, see [Arduino Map Function][1].

So in your case, assuming a `value` of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get

    int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).

  [1]: https://www.arduino.cc/reference/en/language/functions/math/map/

**UPDATE**

It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).

For this you need two maps depending on the value:

    int mappedValue = 0;
    if (value < 512) // Backwards
    {
        mappedValue = map(value, 0, 511, 180, 0);
    }
    else // Forward
    {
        mappedValue = map(value, 512, 1023, 0, 180);
    }


body:
Try this one although, the others answered you properly :

    #include <Servo.h>
    Servo myservo;
    int potpin = 1;
    int val;

    void setup () {
        myservo.attach(9);
    }

    void loop () {
        val = analogRead(potpin);
        val = map(val, 0, 1023, 0, 360);
        myservo.write(val);
        delay(20);
    }

Connect the signal wire of your Servomotor to PWM pin number 9 of Arduino
Connect the output of your joystick to A1 pin of your arduino

Actually i'm not sure about one of that lines and i forgot the correct form, if didn't work, change this line :

    val = map(val, 0, 1023, 0, 360);

To this :

    val = map(val, 0, 1023, -180, 180);

I think both of them works

Good luck


message:
Using millis() in unsynchronized manner

I am assuming millis() is a Timer ISR function.
If so :
When using millis() as mentioned in Arduino Reference :
unsigned long currentMillis = millis();
What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.

Cheers and TIA

body:
> I am assuming millis() is a Timer ISR function.

It is a function that retrieves a value that is updated by and ISR.

> What would happen if the ISR asynchronously changes the value being
> read in a function.

Cannot happen: the value is read with interrupts disabled.

See for example, [in the AVR core][avr]:

```c++
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;
```

> I mean if I have read one byte into currentMillis, but millis had
> changed the value before the remaining 7 bytes are read.

An `unsigned long` is only 4 bytes. That is, until someone comes with a
64-bit Arduino platform.

[avr]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/wiring.c#L70-L74


message:
How do I get the size of my program at runtime?

(This question is specific for the Arduino Due, but maybe there's a general answer to the question)

I'm using [DueFlashStorage][1] to store application data in the flash memory of my Arduino Due. That works quite nicely. The Due has two flash blocks with 256k each. By default, the library writes data to the second flash block. The first flash block is used for the program. My program currently uses around 160k of flash (as the compiler tells me). That leaves about 96k of flash unused, which I could really use to store more application data. I managed to adjust DueFlashStorage to allow writing to the full memory range, but how do I detect where it is safe to write to? (Obviously, I must not overwrite any part of the program)

I have tried something like:
```cpp
  // this returns the logical address of the first byte in flash (0x80000)
  byte* startAddr = dueFlashStorage.readAddress(0);
  Serial.println((unsigned int)startAddr, HEX);
  int bytes = 0;
  while (bytes < 512 * 1024) // That's the size of the flash
  {
    int* data = (int*)(startAddr + bytes);
    if (*data == 0xFFFFFFFF) // empty flash is initialized with FF's
     {
       Serial.print("Free block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
     else
     {
       Serial.print("Used block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
    bytes+=512;
  }
```
This seems to work, as the first block detected as "free" is just above the size of the program. However, this approach has some major drawbacks:

- It's slow. Running over the whole address space to find the end of the program uses time (and maybe I shouldn't just test the first word of each block)
- It's not reproducible. After I have written data to the detected first free block, it's no longer free, so I need another approach (like some magic number) to detect the first data block after the CPU is reset.

Is there a better way for this (like, in the ideal world, a constant I could use)? I don't want to hardcode the data start, because as the program grows (and it's still in development) I would forget to adjust that constant and booooommmm....

  [1]: https://github.com/sebnil/DueFlashStorage

body:
Just to warn you, I minimally tested this, but it seems to work.

In the [Due's linker script][1] there are these relevant lines, containing the named `rom` section.

```
MEMORY
{
 rom (rx)    : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K */
```

Below you'll see:

```
SECTIONS
{
    .text :
    {
        . = ALIGN(4);
        _sfixed = .;
```

`_sfixed` is a symbol they've created to mark the current location, which happens to be the start of the `rom` section in this case, `0x00080000`.  At the bettom of the brace matching the one following `.text`, you'll see:

```
} > rom
```

showing that section goes into ROM, which is why `.` at the beginning of the .text section refers to the `rom` section start address.

If you look near the last thing placed in `rom`, you'll see:

```
    . = ALIGN(4);
    _etext = .;
```

So, they've set another symbol there, the one of interest, `_etext`, the address of which should be the byte of ROM not used, or so I thought the first time through this; turns out it isn't.  I gather you have no use for start of ROM symbol, since it's a static value and at the beginning, so I'll ignore that, but if you cared to make use of it it could be done the same way as follows for `_etext`.

These symbols don't have any type, but you can make them whatever you want.  If you want to perform arithmetic on a pointer that results, it makes sense to use a char type, so:

```c++
extern "C" unsigned char _etext;
```

I thought this was the end of the story, could just take the address of this symbol, but there is more to it.  Following the regular code is this section:

```
    .relocate : AT (_etext)
    {
        . = ALIGN(4);
        _srelocate = .;
        *(.ramfunc .ramfunc.*);
        *(.data .data.*);
        . = ALIGN(4);
        _erelocate = .;
    } > ram
```

They're placing code for the [`banzai` (reset) function][2] (and perhaps other things), which goes into ram ultimately, at this location in ROM.  So, presumably in the start code this is copied from the end of the normal program code into some place in ram.

So, there are two more symbols of interest here, `_srelocate` and `_erelocate`.  Declarations for them:

```c++
extern "C" unsigned char _srelocate;
extern "C" unsigned char _erelocate;
```

These symbols resolve to addresses in RAM, so they can't be used directly, but can have their addresses subtracted to get the size of the image in ROM that gets relocated to RAM, leading to:

```c++
const unsigned char *rom_end = &_etext + (&_erelocate - &_srelocate);
Serial.print("The end of used ROM is : 0x");
Serial.println((uintptr_t)rom_end, HEX);
```

When I compile and run a simple test like this and check the serial monitor connection, I see output like:

```
The end of used ROM is : 0x82FF8
```

If look at the .bin file produced by the compiler:

```
$ wc --bytes  build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin
12280 build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin
```

And 0x82FF8 - 0x80000 == 12280.

When I hex dump flash around this address I can see what looks like it padding out the flash sector with 0x00 bytes before the next unprogrammed flash sector shows as 0xFF.  So you would need to round this up yourself, and if you want be somewhat safer, maybe add some margin.

I don't know how common that configuration in the linker script is.  It's likely that most linker scripts place a symbol there, if they've had some forethought.  But I wouldn't necessarily expect it have the same name.  It's possible they modify it to add more stuff after that symbol.  But for now, for the Due, that would seem to work fine.  It is a bit messy though.

  [1]: https://github.com/arduino/ArduinoCore-sam/blob/adac7b8/variants/arduino_due_x/linker_scripts/gcc/flash.ld#L49
  [2]: https://github.com/arduino/ArduinoCore-sam/blob/790ff2c852bf159787a9966bddee4d9f55352d15/cores/arduino/Reset.cpp#L26


message:
using RTOS SDK - crashes when adding another task

(I hope this is the right place to ask questions about the ESP8266_RTOS_SDK)

I have a program that I've taken from the samples directory (protocols/tcp_client) in the RTOS SDK and added code from the uart sample just so I can use the keyboard to tell the client when to start. The tcp_client task simply does a socket send to & recv from the server (a simple sockets server running on a linux desktop). It runs great until I tried to add another sample task:

     static void test_task(void *pvParameters)
        {
         vTaskDelay(MYDELAY2);
         ESP_LOGI(TAG, "asdf 123");
        }

And then, in the app_main(), I create the task:

    xTaskCreate(test_task, "test", 2048, NULL, 10, NULL);

I try to run it and it either locks up and then crashes or just crashes as soon as it connects to the server. It usually crashes right after it prints out the message in the test_task.

     #include <string.h>
        #include <sys/param.h>
        #include "freertos/FreeRTOS.h"
        #include "freertos/task.h"
        #include "esp_system.h"
        #include "esp_log.h"
        #include "esp_netif.h"
        #include "esp_event.h"
        #include "protocol_examples_common.h"
        #include "nvs.h"
        #include "nvs_flash.h"
        #include "lwip/err.h"
        #include "lwip/sockets.h"
        #include "lwip/sys.h"
        #include <lwip/netdb.h>
        #include "freertos/queue.h"
        #include "driver/uart.h"

        #define HOST_IP_ADDR CONFIG_EXAMPLE_IPV4_ADDR
        #define MYDELAY1 (75 / portTICK_PERIOD_MS)
        #define MYDELAY2 (125 / portTICK_PERIOD_MS)
        #define MYDELAY3 (250 / portTICK_PERIOD_MS)
        #define MYDELAY4 (500 / portTICK_PERIOD_MS)
        #define MYDELAY5 (1000 / portTICK_PERIOD_MS)
        #define MYDELAY6 (2000 / portTICK_PERIOD_MS)
        #define MYDELAY7 (5000 / portTICK_PERIOD_MS)
        #define PORT CONFIG_EXAMPLE_PORT

        static const char *TAG = "example";
        #define EX_UART_NUM UART_NUM_0
        #define BUF_SIZE (1024)
        #define RD_BUF_SIZE (BUF_SIZE)
        static QueueHandle_t uart0_queue;
        unsigned char state;
        int sock;

        static void test_task(void *pvParameters)
        {
         vTaskDelay(MYDELAY2);
         ESP_LOGI(TAG, "asdf 123");
        }

        static void tcp_client_task(void *pvParameters)
        {
         char rx_buffer[128];
         char send_buff[100];
         char addr_str[128];
         int addr_family;
         int ip_protocol;
         int i = 0;
         char xbyte = 0x21;
          int len, err;

         struct sockaddr_in destAddr;
        // destAddr.sin_addr.s_addr = inet_addr(HOST_IP_ADDR);
        // can set ip address either explicitly or using 'make menuconfig' and go to 'example      configuration'
         destAddr.sin_addr.s_addr = inet_addr("192.168.88.103");
         inet_ntoa_r(((struct sockaddr_in *)&destAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) -     1);
         ESP_LOGI(TAG, "address : %s", addr_str);
         destAddr.sin_family = AF_INET;
         destAddr.sin_port = htons(PORT);
         addr_family = AF_INET;
         ip_protocol = IPPROTO_IP;
         inet_ntoa_r(destAddr.sin_addr, addr_str, sizeof(addr_str) - 1);

         sock =  socket(addr_family, SOCK_STREAM, ip_protocol);
         if (sock < 0)
         {
          ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
          state = 51;
         }
         ESP_LOGI(TAG, "Socket created %d",sock);

         memset(send_buff,0,sizeof(send_buff));
         for(i = 0;i < 99;i++)
         {
          send_buff[i] = xbyte;
          if(++xbyte > 0x7e)
           xbyte = 0x21;
         }
         send_buff[99] = 0;

         ESP_LOGI(TAG,"press '1' to connect, then press '2' to start client, '3' to shutdown");

         while (1)
         {
          switch(state)
          {
           case 0:
           vTaskDelay(MYDELAY3);
        break;
       case 49:
        err = connect(sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
        if (err != 0)
        {
         ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno);
         close(sock);
         vTaskDelay(MYDELAY1);
         state = 0;
        }
        ESP_LOGI(TAG, "Successfully connected %d",err);
        state = 0;
        break;
       case 50:
        //ESP_LOGI(TAG, "starting...");

        err = send(sock, send_buff, 80, 0);
        if (err < 0)
        {
         ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
         state = 0;
         break;
        }
        //ESP_LOGI(TAG,"send returned: %d",err);

        vTaskDelay(MYDELAY1);

        len = recv(sock, rx_buffer, 80, 0);
        // Error occured during receiving
        if (len < 0)
        {
         ESP_LOGE(TAG, "recv failed: errno %d", errno);
         state = 0;
         break;
        }
        else
        {
         rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
         //ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
         ESP_LOGI(TAG, "%s", rx_buffer);
        }

        vTaskDelay(MYDELAY1);

        if (sock == -1)
        {
         ESP_LOGE(TAG, "Shutting down socket, press '1' to restart...");
         shutdown(sock, 0);
         close(sock);
         state = 0;
        }
        break;
       case 51:
        ESP_ERROR_CHECK(example_disconnect());
        break;
       case 52:
        shutdown(sock,0);
        close(sock);
        ESP_LOGI(TAG,"shutdown - deleting task");
        vTaskDelete(NULL);
        break;
       default:
        ESP_LOGI(TAG,"press '1' to connect, then press '2' to start client %d",state);
        vTaskDelay(MYDELAY3);
        state = 0;
        break;
      }
     }
    }
    //#if 0
    static void uart_event_task(void *pvParameters)
    {
        uart_event_t event;
        int i;
        uint8_t *dtmp = (uint8_t *) malloc(RD_BUF_SIZE);

        for (;;) {
            // Waiting for UART event.
            if (xQueueReceive(uart0_queue, (void *)&event, (portTickType)portMAX_DELAY)) {
                bzero(dtmp, RD_BUF_SIZE);
                //ESP_LOGI(TAG, "uart[%d] event:", EX_UART_NUM);

                switch (event.type) {
                    // Event of UART receving data
                    // We'd better handler data event fast, there would be much more data events than
                    // other types of events. If we take too much time on data event, the queue might be full.
                    case UART_DATA:
                        ESP_LOGI(TAG, "[UART DATA]: %d", event.size);
                        uart_read_bytes(EX_UART_NUM, dtmp, event.size, portMAX_DELAY);
                        state = dtmp[0];
                        ESP_LOGI(TAG,"state: %d",state);
    //                    uart_write_bytes(EX_UART_NUM, (const char *) dtmp, event.size);
                        break;

                    // Event of HW FIFO overflow detected
                    case UART_FIFO_OVF:
                        ESP_LOGI(TAG, "hw fifo overflow");
                        // If fifo overflow happened, you should consider adding flow control for your application.
                        // The ISR has already reset the rx FIFO,
                        // As an example, we directly flush the rx buffer here in order to read more data.
                        uart_flush_input(EX_UART_NUM);
                        xQueueReset(uart0_queue);
                        break;

                    // Event of UART ring buffer full
                    case UART_BUFFER_FULL:
                        ESP_LOGI(TAG, "ring buffer full");
                        // If buffer full happened, you should consider encreasing your buffer size
                        // As an example, we directly flush the rx buffer here in order to read more data.
                        uart_flush_input(EX_UART_NUM);
                        xQueueReset(uart0_queue);
                        break;

                    case UART_PARITY_ERR:
                        ESP_LOGI(TAG, "uart parity error");
                        break;

                    // Event of UART frame error
                    case UART_FRAME_ERR:
                        ESP_LOGI(TAG, "uart frame error");
                        break;

                    // Others
                    default:
                        ESP_LOGI(TAG, "uart event type: %d", event.type);
                        break;
                }
            }
        }
        free(dtmp);
        dtmp = NULL;
        vTaskDelete(NULL);
    }
    //#endif

    void app_main()
    {
     ESP_ERROR_CHECK(nvs_flash_init());
     ESP_ERROR_CHECK(esp_netif_init());
     ESP_ERROR_CHECK(esp_event_loop_create_default());

     ESP_ERROR_CHECK(example_connect());
      uart_config_t uart_config = {
      .baud_rate = 115200,
      .data_bits = UART_DATA_8_BITS,
      .parity = UART_PARITY_DISABLE,
      .stop_bits = UART_STOP_BITS_1,
      .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
        };
        uart_param_config(EX_UART_NUM, &uart_config);

        // Install UART driver, and get the queue.

        uart_driver_install(EX_UART_NUM, BUF_SIZE * 2, BUF_SIZE * 2, 100, &uart0_queue, 0);

     xTaskCreate(test_task, "test", 2048, NULL, 10, NULL);

        xTaskCreate(uart_event_task, "uart_event_task", 2048, NULL, 12, NULL);

     xTaskCreate(tcp_client_task, "tcp_client", 2048, NULL, 5, NULL);
    }

When I added the task for the uart it works, but when I add the task to print the test message and do the time delay, it crashes.

body:
I didn't have the task as an infinite loop. It should be:

    static void test_task(void *pvParameters)
    {
        while(1)
        {
            vTaskDelay(MYDELAY6);
            ESP_LOGI(TAG, "test 123");
         }
    }


message:
Simple LCD countdown timer

I tried to modify the basic "hello-world" sketch for the LCD that is a part of the examples section in the IDE. I intended to make a countdown timer using the LCD.

The original code simply prints "Hello World" in the first line, and then makes use of the `millis()` function to print the time elapsed in the next line.

So I tried a simple modification to make it count *down* from 20. Instead of printing `millis()/1000` , I printed `20-millis()/1000`, and also added a `while()` to only print till `millis()<=20,000`. (so that it does not go beyond `00)`

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {

      lcd.begin(16, 2);

      lcd.print("time left");
    }

    void loop() {

      while(millis()<=20000){

       lcd.setCursor(0, 1);

       lcd.print(20- millis() / 1000);
      }

    }

 It seemed to work till `10`. but instead of `9`, it printed `90`, and likewise `80,70..` for `8,7...`etc till `00`.

 **How can I get rid of these extra zeros?**

body:
> instead of `9`, it printed `90`

No, it didn't: it printed “9”. However, it did not _erase_ the previous
value before printing “9”. Before printing the 9, the LCD had:

    ┌────────────────┐
    │time left       │
    │10              │
    └────────────────┘
     ^cursor position

When you printed “9”, that character replaced the “1”, and you end up
seeing “90”.

The fix, as pointed out by Juraj, is to add a space after printing the
numbers.

An alternative is to prepend a space (or a zero), but only when the
number to be displayed is less that 10:

```c++
int count = 20 - millis() / 1000;
if (count < 10)
    lcd.print(' ');  // alternatively: '0'
lcd.print(count);
```


message:
Float switch is not detected

[![my set up][1]][1]

  [1]: https://i.stack.imgur.com/IIuOG.png

Good day everyone, forgive me for the shabby drawing I am just panicking, why my float switches are suddenly undetected by my Arduino mega. I've tested all the float switches one by one to confirm if everything is working just before installing it..

i have 18 sets of float switches, 5 pumps being controlled by the relay, my main PSU is 12V 20A.
The yellow rectangle stands for the float switch, the purple line is connected to digital pins from between and 10k ohm resistor and the switch. the green line is a common ground connection from the 5.2V buck (psu for devices that need 5 to 5.5v) to the Arduino mega's gnd.

here's my code, and its not the project code, just a simple test sketch because my float switches are suddenly acting weird:

    #include <OneWire.h>
    #include "OneButton.h"
    #include <DallasTemperature.h>
    #include "GravityTDS.h"
    #include <EEPROM.h>
    #include "Wire.h" // Include the I2C Wire Library
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x27,20,4);

    #define bp1 (uint8_t) 10 /*Button 1*/
    #define bp2 (uint8_t) 11 /*Button 2*/
    #define bp3 (uint8_t) 12 /*Button 3*/

    OneButton btn1 = OneButton(bp1,false,false); uint8_t bx1 = 0;
    OneButton btn2 = OneButton(bp2,false,false); uint8_t bx2 = 0;
    OneButton btn3 = OneButton(bp3,false,false); uint8_t bx3 = 0;

    //Float Switches...........
    /*Collector Float Switch*/
    #define CT_Fs2 (uint8_t) 9

    /*Sieve & Cloth*/
    #define SC_Fs1 (uint8_t) 8

    /*Primary Test Tank*/
    #define PT_Fs1 (uint8_t) 7
    #define PT_Fs2 (uint8_t) 6

    /*Grease Trap*/
    #define GT_Fs1 (uint8_t) 5

    /*First Filtration*/
    #define FFP_Fs1 (uint8_t) 4
    #define FFP_Fs2 (uint8_t) 3

    /*Sediment Filter*/
    #define SD_Fs1 (uint8_t) 2

    /*Second Filtration Passed*/
    #define SP_Fs1 (uint8_t) 24
    #define SP_Fs2 (uint8_t) 25

    /*Final Test Tank*/
    #define FT_Fs1 (uint8_t) A7
    #define FT_Fs2 (uint8_t) A8

    /*Tank A*/
    #define TA_Fs1 (uint8_t) 45
    #define TA_Fs2 (uint8_t) 47

    /*Tank B*/
    #define TB_Fs1 (uint8_t) 42
    #define TB_Fs2 (uint8_t) 43

    /*Tank C*/
    #define TC_Fs1 (uint8_t) 40
    #define TC_Fs2 (uint8_t) 41

    void setup()
    {
      Serial.begin(9600); /* Show Serial Monitor */
      lcd.begin(); /* LCD Screen Set Up */

    //---------------------------------------------------------------------dont forget to set up the pins
    //ALL DIGITAL PINS ARE INPUT AS DEFAULT, DECLARE ONLY IF MODE IS OUTPUT:
      pinMode(FT_Fs1,INPUT);
      pinMode(FT_Fs2,INPUT);

    //----------------------------------------------------------------------One Button Single Click event attachment
      btn1.attachClick(handleClick1);
      btn2.attachClick(handleClick2);
      btn3.attachClick(handleClick3);

    }

    //simple show txt on LCD Screen
    void lcd_print(String txt ,uint8_t a, uint8_t b)
    { lcd.setCursor(a,b); lcd.print(txt);}

    void loop()
    {
      FSTester();
    }

    void FSTester() // to check FLOAT SWITCH
    {
      if (digitalRead(CT_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("CT_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(SC_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("SC_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(PT_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("PT_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(PT_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("PT_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(GT_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("GT_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(FFP_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("FFP_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(FFP_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("FFP_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(SD_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("SD_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(SP_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("SP_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(SP_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("SP_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(FT_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("FT_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(FT_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("FT_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TA_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("TA_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TA_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("TA_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TB_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("TB_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TB_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("TB_Fs2 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TC_Fs1) == 1)
      {
        lcd.clear();
        lcd_print("TC_Fs1 Detected",0,1);
        delay(5000);
      }
      else if (digitalRead(TC_Fs2) == 1)
      {
        lcd.clear();
        lcd_print("TC_Fs2 Detected",0,1);
        delay(5000);
      }
      else
      {
        lcd.clear();
        lcd_print("NOTHING",0,1);
      }
    }

I've checked for continuity and everything is fine. why is it weird?

somebody please correct my mistakes

body:
It is difficult to determine from the diagram if the green wire is at the same voltage as the black wire supplying power to the Arduino board. Even if they are connected, it is difficult to say if the current is nominal. As there is a power supply of unknown design involved for both the Arduino and the float switch.

This could cause unexpected results and may even permanently damage sensitive parts.  Consider using a design with only one power supply thereby mitigating the risk of unexpected results.


message:
Servo noise during program flash on Arduino

I'm running serveral servos using a driver A4988 and external power supply. Everything works fine.
I've just noticed one issue that I can't explain.
As soon as I upload a new program version on my arduino uno, while the external power supply is one, the servo makes some strange noises. After the upload has finished, the noise disappears.

Without any further details, can you explain this behavior? Does the arduino set some Pins to HIGH during flashing?

Thanks!

body:
It would depend on which Arduino and what bootloader it's running.  Generally MCUs have their pins in INPUT mode when they reset.  Sometimes the bootloader will leave some pins configured for a particular mode by the some the sketch runs.  E.g. the Leonardo seems to leave pin 13 set to OUTPUT mode.

You usually want devices connected to your Arduino to have stable signals when the Arduino MCU is in reset, or in the bootloader, so it makes sense to pull the signal pins, that will later be output from the Arduino sketch, to known levels.  So maybe pulling your servo driver enable signal to inactive (HIGH) is appropriate.

Looking at the A4988, it has an EN (enable) pin, which seems to be active low.  So putting a high(ish) value resistor, say 5k or 10k, on it to VDD/HIGH (to inactive) is probably the thing to do.  When the Arduino is not driving the enable line to its low (active) state, that is when it's in the bootloader or being held in reset, the A4988 should stop its activity.


message:
How to calculate required amperage of multiple motors?

I a very simple question about calculating the amperage I need to run 5 stepper motors from my Arduino Uno.

If I have **5 28BYJ-48 stepper motors**(which are **5V** and are said to require about **240mA** each) all plugged into **5 separate ULN2003 driving boards**, and I wire 4 signal wires from the boards to the Arduino, and connect the two power wires for the board to 5V and GND on the Arduino. **What voltage and amperage I need to supply to my Arduino for everything to run properly?**

I'm worried because I read that the Arduino cannot handle over one amp but 0.24*5>1, although I don't know if the amperage is additive with each additional motor.

Thanks for any answers!

body:
> I don't know if the amperage is additive with each additional motor

Yes, amperage is additive.

> the Arduino cannot handle over one amp but 0.24*5>1

That is correct. But the stepper motors should never be powered through the Arduino. You should connect a fitting power supply directly to the stepper drivers. That way the needed current flows past the Arduino, not through it.

> What voltage and amperage I need to supply to my Arduino for everything to run properly?

The Arduino runs at 5V, though you can provide 7-12V to Vin/barrel jack. When your motors are rated for 5V, you should provide them with 5V. So it would be fitting to buy one 5V power source to power the Arduino (through the 5V pin or USB) and the stepper drivers.

For the current: A good measure is the stall current of a motor, so the current, that flows, when the motor is driven, but cannot move (due to being physically stuck). Add a bit headroom to this. The mentioned motors are often badly documented, so that you might not be able to find a stall current value. Add more headroom in that case. So I would suggest adding up all the amps and then multiply this value with 1.5 or even 2. Let's take 250mA per motor (for ease of calculation) with 5 motors gives 1.25A. Take at least a 2A power supply. When you want to make sure go directly to 3A. The price difference in that range isn't that much anyway.


message:
Converting ESP32 SPI code to Arduino for MAX6921 IV-18 driver board

I purchased a [IV-18 VFD][1] tube [driver module][2], which came with some [example code][3] for an ESP32 board. The driver module has a 20 output [MAX6921][4] serial chip to drive the vacuum tube. I want to use this driver module with an Arduino Uno and then eventually a Raspberry Pi.

I think I have a very rough understanding of the electronics and [demo code][3], but cannot seem to get my SPI calls to work. Rather than trying to translate the demo code in its entirety, my first goal is to just get one segment to light up.

**Quick background**

The IV18 tube has 9 grids. The first grid has only a dot and a dash, but the remaining 8 grid have 7 segments and a decimal point.

[![IV-18 Tube][5]][5]

To light a segment, you provide power to the segment pins / decimal point and to the grid for that segment. To display several numbers, you have to quickly cycle through lighting each of the grid positions and the relevant segments for that position. If you cycle through this fast enough, the human eye sees the whole grid with numbers (persistence of vision).

What I have tried

So far, I have made the connections from the Arduino Uno to the driver board

    Driver GND  - Uno GND
    Driver 5V  - Uno +5V
    Driver Din  - Uno digital pin 11 / MOSI
    Driver CLK  - Uno digital pin 13 / SCK
    Driver LOAD  - Uno digital pin 2
    Driver BLANK - Uno digital pin 3
    Driver Dout  - Not connected

The example code has hex codes which I believe are then translated to a 24 bit buffer (although only 17 bits are required) to send via SPI to set the MAX6921 outputs HIGH or LOW.

I think the bits required are as follows:

| 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  | 9     | 10    | 11    | 12    | 13    | 14    | 15    | 16   | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| -- | -- | -- | -- | -- | -- | -- | -- | ----- | ----- | ------| ----- | ----- | ----- | ----- | ---- | -- | -- | -- | -- | -- | -- | -- | -- |
| G7 | G6 | G5 | G4 | G3 | G2 | G1 | G0 | SEG_G | SEG_F | SEG_E | SEG_D | SEG_C | SEG_B | SEG_A | SIGN |    |    |    |    |    |    |    | DP |

So to light the number 8 in the righthand most grid, I assumed I'd need the 8th bit high (grid) and bits 9,10,11,12,13,14 and 15 for the 7 semens for the "8".

In my setup function, I call `SPI.begin` and then `SPI.transfer` with what I assumed was the matching binary data (from right to left, I think because of the bit order LSB/MSB?):

`SPI.transfer(0b000000000111111110000000);`

This lights the first grid (the one after the degree and minus sign) but not what I want - I see some segments in the leftmost grid (the full grid, not the grid with the dot and minus) but these light in a different pattern each time  (varies each time I reset or re-upload which I think is to be expected as I'm pushing data to the MAX6921 each time).

**This is my code so far**

    #include "SPI.h"

    #define DISP_CLK 13   // White - SPI SCK
    #define DISP_DATA 11  // Yellow - SPI MOSI
    #define DISP_LOAD 2   // Blue
    #define DISP_BLANK 3  // Green

    void setup() {
      Serial.begin(9600);
      Serial.println("IV18 Test");

      SPI.begin();

      pinMode(DISP_BLANK, OUTPUT);
      digitalWrite(DISP_BLANK, LOW);

      pinMode(DISP_LOAD, OUTPUT);
      digitalWrite(DISP_LOAD, HIGH);

      SPI.transfer(0b000000000111111110000000);
    }

    void loop() {

    }

I'm pretty sure the two fundamental things I have wrong here are the bits of data to send and then the correct use of the SPI.

Can someone please help me to understand the ESP32 code properly, and ideally help me get the correct data to send via SPI so that I can light up the segments & grid positions that I expect to.

  [1]: https://github.com/blinken/nixie-clock/blob/main/datasheets/iv-18/IV-18.pdf
  [2]: https://www.amazon.co.uk/Antique-display-vacuum-integrated-Arduino/dp/B08TX6CSZ5
  [3]: https://github.com/blinken/nixie-clock/blob/main/examples/esp32/src/esp32_demo.c
  [4]: https://datasheets.maximintegrated.com/en/ds/MAX6921-MAX6931.pdf
  [5]: https://i.stack.imgur.com/CRGGL.jpg

body:
So it turns out that I got a few things wrong.

UPDATE: [Working code is now on my GitHub][1] if anyone is interested.

Firstly, I misunderstood the example code and made a mess of the bits to send to the MAX6921. To work out the correct mapping, I went and probed each pin of the IV-18 and noted the connection to the pins / outputs of the MAX6921 which gave me this table:

| BIT     | 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  | 9  | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| ------- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| IV-18   | G9 | G8 | G7 | G6 | G5 | G4 | G3 | G2 | G1 | A  | B  | C  | D  | E  | F  | G  | DP |    |    |    |    |    |    |    |
| MAX6921 | 0  | 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  | 9  | 10 | 11 | 12 | 13 | 14 | 15 | 16 |    |    |    |    |    |    |    |

Note that the MAX6921 value is the OUTPUT number and not the PIN number

This then gave me the correct order for each bit to send, as noted in the top row of the table.

The next mistake was trying to send all 24 bits in one go. Instead, I broke each byte into a separate `SPI.transfer()` call which finally let me display the segments in the grid position that I expected.

For example, to display "HELLO", my loop function has this:

    void loop() {
      //             XXXXXXXDP                 GFEDCBA1                  23456789
      SPI.transfer(0b00000000); SPI.transfer(0b11101100); SPI.transfer(0b10000000); delay(1);
      SPI.transfer(0b00000000); SPI.transfer(0b11110010); SPI.transfer(0b01000000); delay(1);
      SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00100000); delay(1);
      SPI.transfer(0b00000000); SPI.transfer(0b01110000); SPI.transfer(0b00010000); delay(1);
      SPI.transfer(0b00000001); SPI.transfer(0b01111110); SPI.transfer(0b00001000); delay(1);
    }

[![IV-18 with hello message][2]][2]

I have setup TIMER1 to use instead of the loop/delay code, so hopefully I can finish converting the rest of the example code to Arduino.

  [1]: https://github.com/alexholsgrove/nixie-clock
  [2]: https://i.stack.imgur.com/WyTU9.jpg


message:
How to call multiple delayed functions using a single millis()

I am working in a project where I need to call more than 1 functions actually 4 functions using a single millis()

Here is the code below.

     unsigned long then = 0;

     void loop(){

      unsigned long now = millis();

      if(now-then >=0){

       Serial.println("Function 1 called");

      }else if(now-then>=2000){

       Serial.println("Function 2 called");

      }else if(now-then>=4000){

       Serial.println("Function 3 called");

      }else if(now-then>=6000){

       Serial.println("Function 4 called");

       Serial.println("The end");

       then = now;
      }
     }

All the functions above gets run successfully but not in a proper sequence.

The running sequence of the functions seem to be very improper and random.

The 'function 1' gets executed in a proper sequence and timing but rest of the others are making a messy output.

How can I fix it please?

Thanks.

body:
your `else` in that set of `if`'s is causing only a single if to be possible to be true at any one time, and once the `now-then` line up, only the first one in the line-up will ever execute. remove the `else` from your if block. treat each if as its own thing. i.e.

    if(now-then >=0) { /* do thing 1*/ }
    if(now-then >=1000) { /* do thing 2*/ }
    if(now-then >=2000) { /* do thing 3*/ }
    if(now-then >=3000) { /* do thing 4*/ }

that way, even if the conditions line up, all the blocks will be checked, and all the `if`'s that resolve true, will execute.


body:
The current structure with multiple if statements and on timestamp variable does only work, if you also check for `millis()-then` being smaller than the next interval. Otherwise the first if statement will always be executed.

I think it gets easier, when you use only one if statement, but put the intervals in an array. In that if statement you can either use a `switch` statement to execute the code for the corresponding interval, or use a function pointer. Somewhat like this (untested):

    unsigned long then = 0;
    unsigned long intervals[4] = {0, 2000, 4000, 6000};
    int current_interval_index = 0;

    ...

    void loop(){
        unsigned long now = millis();
        if(now-then >= intervals[current_interval_index]){
            switch(current_interval_index){
                case 0:
                    Serial.println("Function 1");
                    break;
                case 1:
                    Serial.println("Function 2");
                    break;
                case 2:
                    Serial.println("Function 3");
                    break;
                case 3:
                    Serial.println("Function 4");
                    break;
            }
        then = now;
        current_interval_index = (current_interval_index + 1) % 4; // increment index and wrap it back to zero, if it goes to 4
        }
    }

That way you can easily extent for more functions and the intervals are conveniently managed in an array. Note, that the intervals add up here. So function 4 executes after 2s+3s+6s = 11s.


message:
Accelerometer Orientation (LIS3DH)

Newbie here!
I’m trying to make a pocket level using an LIS3DH but I don’t know how to “reset” all the axis to start reading from a certain orientation since my LIS3dh won’t be mounted flat and will change often.
Ideally whenever the level starts it would start reading everything at 0 no matter the orientation.
I’m sure it’s just math, but it’s way over my head to begin to understand it.

Starting with the absolute basics I’m using the adafruit lib. I can easily get all the readings, and I understand they are acceleration forces. But how do I start them all from 0?

Initially I was thinking to take the very first reading and store it, then add or subtract the new readings from the originals based on if the new numbers are higher or lower than original (subjectively) but that only works in some instances which means that it wasn’t a good solution.

I don’t have specific code to share as I’m using the adafruit LIS3DH example.

Here’s a reading from the sensor of it not flat

```X: -11408 Y: -3152 Z: 10560 X: -6.87 Y: -1.87 Z: 6.27 m/s^2```

And here’s readings closer to a flat surface

```X: -80 Y: 704 Z: 16176 X: -0.02 Y: 0.46 Z: 9.86 m/s^2```

body:
Consider taking on this project in sever steps.  Some you might do now and other later if necessary

First, accelerometers do not usually need alignment.  But if accuracy and reproducibility is important, a project may benefit from finding any offset a single accelerometer may need and finding any magnitude adjustments between the three accelerometers.  Using gravity rotate each accelerometer through their maximum negative and positive values.  Use these values to find an offset such that the absolute values are equal for each individual accelerometer.  Then select one accelerometer as the bases and find the appropriate coefficients to normalize the other two accelerometers such that the absolute values of all maximums and minimum are equal.  As hinted, this is one of the step you can skip until later if necessary.  If you need a more thorough explanation you can find it in section 2 of [this STMicro document][1].

To find angles it would be best to consider the classic airplane example where pitch (nose up or down) and roll (rotation around the axis passing through the nose and tail).  [Here][2] is a good submersible Arduino project to consider. In this project the accelerometer Z axis is pointed down and the X to the side.  To find ROLL the author calculates the inverse tangent of the negative of the ratio of acceleration in the X direction over the acceleration in the Z direction.

[![enter image description here][3]][3]

The pitch calculation is a bit more involved.  This can be found by taking the inverse tangent of the acceleration in the Y direction over the square root of the sum of the square of the X plus Y acceleration.

[![enter image description here][4]][4]

That out of the way, now consider how to zero the angles out.  First decide on if you will adjust the roll or the pitch.  Let's consider the roll case.  Record the current roll angle and subtract it from the current calculated roll angle before displaying it as zero.  Now rotate your accelerometer such that you do it around the Y axis (remember, we are only considering the roll case and do not want to change the Y accelerometer's reading!).  If you have done the math correctly, the displayed angle will be the difference between when you started and finished your rotation.

All that out of the way, now consider what would happen if you rotated your accelerometer through a roll position where the acceleration in the Z direction falls to zero.  Your trigonometric inverse tangent function for roll would go to infinity!  In the physical world, where gimbals are used for air and space navigation, this is referred to as [Gimbal lock][5]!

What to do about Gimbal lock?!  Well, it's a story that starts in 1843 (yeah, that does sound odd doesn't it WRT air and space navigation).  In short, if you stop using classical trigonometry to convert acceleration to angle an start using [Quaternions][6] you avoid Gimbal lock entirely.  Quaternions use complex numbers to describe rotation in 3D space.  People who write 3D gaming programs absolutely love how Quaternions simplify their efforts.  This is another of those steps you don't have to do.  But doing so will make your project all the more robust.

 (BTW, [this is the STMicro LIS3DH data sheet][7].)

  [1]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjm6-qnsevwAhUFCs0KHY8uCk8QFjAAegQIAxAD&url=https://www.st.com/resource/en/application_note/dm00119044-parameters-and-calibration-of-a-lowg-3axis-accelerometer-stmicroelectronics.pdf&usg=AOvVaw22kLvmCx7xWx_J4t54VvCK
  [2]: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/
  [3]: https://i.stack.imgur.com/oAHmt.jpg
  [4]: https://i.stack.imgur.com/fxfZu.jpg
  [5]: https://en.wikipedia.org/wiki/Gimbal_lock
  [6]: https://en.wikipedia.org/wiki/Quaternion
  [7]: https://www.st.com/resource/en/datasheet/lis3dh.pdf


message:
How to show the distance in decimal use sensor TF-Luna Lidar or more specific value

I want to ask about TF-Lunar Lidar, I've written code to know the distance in cm by reading the array data, right now I need some help about how to read the data so it can be showing the more specific value (float or in decimal)
Or do you guys know what is the speed of the waves transmitted and captured by the lidar sensor, so that I can calculate it in a more specific form, such as using the method of calculating the distance on the Hc-srf04 sensor
I also have used this format to read the distance in mm, but It never works (image about array data)
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/e2mOV.png

body:
> so if i inputting the duration of the light travel from trigger to echo, i can find the distance?. will it work?

That's the basic working principle, but you cannot do that with an Arduino. Light is too fast, resulting in incredibly small travel times. You need specialized hardware for that. And thats, what a Lidar sensor (or other Time Of Flight sensor) are.

---

The TF-Lunar Lidar sensor supports different output formats. The distance in cm is just the default. There is also the format, that you showed in your question (9 byte mm), which gives you the distance in mm. The [manual of the TF-Lunar][1] also explains how to change the used output format (look at page 22: "5.Output format setting ID_OUTPUT_FORMAT=0x05"). How exactly this is done depends on your actual code and the used communication interface (Serial or I2C).

  [1]: https://www.robotshop.com/media/files/content/b/ben/pdf/tf-luna-8m-lidar-distance-sensor-instructions-manual.pdf


message:
Display upTime using `millis()` - Arduino Uno

I want to use the following function to display MCU's uptime, but after several hours I get error.

    void uptime(char *ret_clk)
    {
      byte days = 0;
      byte hours = 0;
      byte minutes = 0;
      byte seconds = 0;

      int sec2minutes = 60;
      int sec2hours = (sec2minutes * 60);
      int sec2days = (sec2hours * 24);

      unsigned long time_delta = millis() / 1000UL;

      days = (int)(time_delta / sec2days);
      hours = (int)((time_delta - days * sec2days) / sec2hours);
      minutes = (int)((time_delta - days * sec2days - hours * sec2hours) / sec2minutes);
      seconds = (int)(time_delta - days * sec2days - hours * sec2hours - minutes * sec2minutes);

      sprintf(ret_clk, "dd d:d:d", days, hours, minutes, seconds);
    }

after 2:55 hours I got a correct answer : `0d 02:55:27`

also after 4 hours, a correct answer : `0d 04:06:44`

but roughly after 12 hours i get an error: `1d 02:01:27`

and after roughly 20 hours I get : `2d 23:74:26`

What is wrong in `uptime` ?

body:
On an 8-bit Arduino an `int` can only hold values in the range -32768 to +32767. One day's worth of seconds is 86400, which is far outside that range.

You should replace your `sec2...` variables with literals, maybe `#define`d - and don't forget to force the length for longer values:

```c++
#define SEC2MINUTES 60
#define SEC2HOURS 3600
#define SEC2DAYS 86400UL
```


body:
The millis function increments rapidly, hence it easily exceeds the maximum value of int -  -32768 to +32767.

So, use unsigned long data types for millis and other stuff that's large.

4 billion and some change is the max value that unsigned long data types can store, hence no overflowing till about 49 days.


message:
Why is this extremely simple code not working?

I have a problem with a for loop, and ```Serial.print("Its Working")``` does not appear. Seems simple, I've done it before, now for whatever reason, its not working anymore

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

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

  for (int x = 0; x > 10; x++) {

    Serial.println("Its Working");
    delay(1000);
  }
}

body:
The problem is:

```c++
for (int x = 0; x > 10; x++) {
```

That can be rewritten, in pseudo code, as:

* X is zero
* While X is greater than 10:
  * Increment X

You see the problem? X is zero. It's not greater than 10, so it never increments.

I *assume* you actually wanted:

```c++
for (int x = 0; x < 10; x++) {
```

Also be aware that your `for` loop will be run over and over again, so you will never see it finish.  You should add

```c++
Serial.println("Loop done");
```

at the end so you know it's finished.


message:
Arduino , python , pyfirmata , standard firmata

Is there a way to change arduino analog reference to EXTERNAL IN PYTHON using pyfirmata or any other library ?
Necessary Links : https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

My sensor has a 3.3 volt operating voltage , my arduino has a 5 volt operating voltage.
As such in arduino using C++ and arduino module the scaling can be done using analogReference(External) and providing reference voltage to analog read?

IS there any equivalent to this in python, pyfirmata ?

body: No, not as far as I know. The firmata protocol does not include a command to set the analog reference. However, you can of course modify the firmata firmware to your liking. In the simplest case, just add the appropriate command to the `setup()` function of the main .ino.


message:
Arduino Yún causing power suge warning

Recently I got an Arduino Yún board that sends out a power surge error message everytime I connect it to my laptop through the USB cable. I tried two Arduino Leonardo and one Arduino Uno and there wasn't any problem with them or the USB port. Am I missing something or is the board faulty already?

body: Yún boards are more powerful boards than your average Arduino. Probably too powerful for your little laptop's USB ports. Use a powered hub or an external power supply to run the board.


body:
Use a USB tester to test the current consumption, it should be < 500ma

I recommend using a USB that has power of its own, eg. monitor USB


message:
Arduino Nano 33 BLE - use of flash to store data; how to expand a piece of sample code

I've been looking into how to store data in between restarts.  With an Arduino UNO, there are plenty of EEPROM libraries, but I'm not finding something 'off the rack' for the Arduino Nano 33 BLE.

I did manage to find a well documented example by Pete Warden, who recently put on github (https://github.com/petewarden/arduino_nano_ble_write_flash), and it can be compiled and downloaded, but I'm unclear as to how one would expand on it, to write a simple function that can store and read multiple values (integer, float, string, arrays).

The code is below, I'm a bit rusty on things, but I am thinking that the key is in the part:

      // Treat the first four bytes of the copy of our flash array as a 32-bit
      // integer.
      int32_t* counter_address = reinterpret_cast<int32_t*>(ram_buffer);

How would one add additional variables (and of different lengths) to this code, so you could write and read more than one variable?   Somehow, it would seem a command like:

    int32_t* another_variable = [modified version of:] reinterpret_cast<int32_t*>(ram_buffer);

... would do the trick, but I'm not quite sure about how this is done.

       * Copyright 2021 The TensorFlow Authors. All Rights Reserved.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    ==============================================================================*/

    // This sketch demonstrates how to initialize, read, and update flash memory
    // on an Arduino Nano BLE Sense 33. It contains a counter that starts at zero
    // when the sketch is first uploaded, and is incremented by one every time that
    // the board is reset without a re-flash. You can test this by uploading the
    // sketch, opening the serial monitor, and seeing "Counter=0" output initially.
    // If you then press the reset button, you should see "Counter=1", and so on as
    // the board is restarted.

    // This Mbed API lets us access flash memory, so we include the header. See
    // https://os.mbed.com/docs/mbed-os/v6.9/apis/flashiapblockdevice.html
    #include "FlashIAPBlockDevice.h"

    // One of the challenges I had with the existing examples I found of using flash
    // was that they didn't demonstrate how to set an initial value for the memory
    // when the sketch was first uploaded. This was essential for most use cases,
    // for example we want the counter to start at zero so the initial contents need
    // to be set when the program is flashed. I would typically try to use linker
    // scripts to set aside an area of memory and mark it so it's initialized during
    // flashing, but that's not very easy with the Arduino IDE. Instead I use a bit of
    // a hack, by:
    //  - Declaring an array of bytes as const, so I know it will end up in
    //    flash.
    //  - Forcing it to align with the block size of the flash, so it can be
    //    accessed by the API that works with whole pages of flash.
    //  - Adding an empty initializer list ({}) tells the compiler to zero out the
    //    contents in the binary that's flashed to the device.
    // The last point is a bit subtle, because you might think that doing it in a
    // constructor or setup() would work, but that would be called every time the
    // program is reset. What I needed was a way to create a binary with that area
    // already initialized before upload, which this approach offers.
    // Some other examples use hard-coded addresses for the flash, usually towards
    // the top of the address space so that they won't clash with the loaded program,
    // but this approach does have the advantage that your writable area is dealt with
    // in the same way as other variables, so you shouldn't have to worry about
    // overwriting anything.

    // From experimentation I know that the "page size" or "block size" of the flash
    // on the board is 4KB, and should match the reported get_erase_size() from the
    // block device object. In theory we should be able to use the
    // MBED_CONF_FLASHIAP_BLOCK_DEVICE_SIZE macro, but this seems to be set to zero.

        #include "FlashIAPBlockDevice.h"

        constexpr int kFlashBlockSize = 4096;

            // Your flash area needs to be a multiple of the block size. In this case I want
            // 64KB (even though I'm only using the first four bytes). You should make this
            // the smallest multiple of the block size that will hold your data.
            #define ROUND_UP(val, block_size) ((((val) + ((block_size) - 1)) / (block_size)) * (block_size))
            constexpr int kFlashBufferSize = ROUND_UP(64 * 1024, kFlashBlockSize);

            // As mentioned above, alignas ensures we get a valid block-aligned address,
            // const should make sure it's in flash, and the empty brackets mean the array
            // is filled with zeroes when the program is first uploaded.
            alignas(kFlashBlockSize) const uint8_t flash_buffer[kFlashBufferSize] = {};

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

                  // Beware! If you copy and paste this code into your own example, and try
                  // running it without the serial monitor attached, this line will hang forever.
                  // You'll need to remove this in production (and yes I have been caught by this
                  // myself far too often).
                  while (!Serial);

                  // The address of the array will be determined by the compiler, and we need to
                  // grab it as a 32-bit integer to use with the Mbed API.
                  const uint32_t flash_buffer_address = reinterpret_cast<uint32_t>(flash_buffer);
                  Serial.println(String("flash_buffer_address=0x") + String(flash_buffer_address, 16));

                  // Create the flash object we'll be using to access the flash memory.
                  static FlashIAPBlockDevice bd(flash_buffer_address, kFlashBufferSize);
                  bd.init();

                  // We'll need to copy the area of flash to RAM to modify it, so allocate an
                  // array of the right size.
                  uint8_t* ram_buffer = (uint8_t*)(malloc(kFlashBufferSize));

                  // Copy the existing flash contents into our ram buffer.
                  bd.read(ram_buffer, 0, kFlashBufferSize);

                  // We need to erase the flash area before we can write into it again.
                  bd.erase(0, kFlashBufferSize);

                  // Treat the first four bytes of the copy of our flash array as a 32-bit
                  // integer.
                  int32_t* counter_address = reinterpret_cast<int32_t*>(ram_buffer);

                  // Print out the value before any changes.
                  Serial.println(String("Counter=") + String(*counter_address, 16));

                  // Update our RAM copy of the counter integer.
                  *counter_address += 1;

                  // Write the whole copy of our RAM buffer back into flash.
                  bd.program(ram_buffer, 0, kFlashBufferSize);

                  // Shut down our flash access object.
                  bd.deinit();
                }

body:
I can't really help with the source code you found, but here is a simpler solution for your original problem: I wrote a library called NanoBLEFlashPrefs. It allows you to store parameters and preferences persistently between program restarts and even reprogramming.

The Arduino boards mentioned above use a nRF52840 microcontroller from Nordic Semiconductor. This chip features a very simple file system for flash storage. This is used in the library to store and retrieve an arbitrary struct of data of your program.

Please take a look at the [GitHub repository of NanoBLEFlashPrefs][1].

  [1]: https://github.com/Dirk-/NanoBLEFlashPrefs


body:
You can also try my [**FS_Nano33BLE** Library](https://github.com/khoih-prog/FS_Nano33BLE) with simple-to-use LittleFS / FATFS.

The filesystem access uses normal [POSIX APIs](https://www.tutorialspoint.com/c_standard_library/stdio_h.htm) or [mbed FileSystem APIs](https://os.mbed.com/docs/mbed-os/v6.10/apis/file-system-apis.html)