body:
I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?

my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

title: How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry?

Answers: 1

body:
It is not clear what you mean by “digital port”. The simplest mean to
communicate from the Arduino to the Raspberry is to use the Arduino's
serial port, which gets into the Raspberry Pi through USB. Just like you
would do if you had a PC instead of the Raspberry:

```c++
/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}
```

This program will continuously output a text stream like this:

    0 145
    1 220
    2 865
    0 142
    1 223
    ...

where the first column is the analog channel number and the second
column is the ADC value. How you handle this stream on the Raspberry
side is up to you.


body: I got a Arduino Uno awhile ago and it took me awhile to set up but it worked when I downloaded the IDE. This time when I bought an Arduino Nano it doesn't pop up with the driver. Doesn't show up anywhere in device manager. I've tried to reinstall the IDE to see if that would work but it didn't. What should I do/try next?

title: Arduino Nano drivers

Answers: 0


body:
So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like [this][1] below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins)  and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.

EDIT:
The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.

Edit: For anyone wondering how to use the sensor, the datasheet is [here][2] and it shows the positions of the collector, emitter, anode and cathode.

  [1]: https://uk.rs-online.com/mobile/p/products/1612156/?grossPrice=Y&cm_mmc=UK-PPC-DS3A-_-google-_-3_UK_EN_Reflective Optical Sensors_Vishay_Exact-_-Vishay - Reflective Optical Sensors - 1612156-_-vishay vcnt2020&matchtype=e&kwd-383452625495&s_kwcid=AL!7457!3!237533593421!e!!g!!vishay vcnt2020&gclsrc=aw.ds&&gclid=Cj0KCQjw6IfoBRCiARIsAF6q06seXlEYZ00YPNVyDWBQ2_7uM_WEoWEcBqtlp74rwz92QOQBfZsglC8aAkTpEALw_wcB
  [2]: http://www.vishay.com/docs/84285/vcnt2020.pdf

title: Measure position of gear with arduino

Answers: 1

body:
If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.

Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.

So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your `loop()` function.

If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the `loop()` function.

Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.

Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.

One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like `int x = 1000;` will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute `x = 1000` will all take just one clock tick.

Others will vary the amount of instructions that are generated to execute them. For example
`
float x = 1.0;
x = x + 2.0;
`

will likely take more instructions to execute than it's integer counterpart:
`
int x = 1;
x = x + 2
`

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.


body: I have an old wireless RCA output camera. I was wondering if I can convert its analog input to a digital one and have it saved on a file in my laptop?

title: Is it possible to convert RCA(video only) to Arduino Uno then to a computer?

Answers: 0


body:
I have a project where I need to state from leds turning on and off to another one that will have all the leds turned on and send data and I was wondering how should I do that, this the code I have:

    #include <CapacitiveSensor.h>

    CapacitiveSensor cs_11_10 = CapacitiveSensor(11,10);

    int state_s1 = 0;
    int state_s2 = 0;
    int state_s3 = 0;
    int state_s4 = 0;
    int state_prev_s1 =0;
    int pin_s1 = 12;
    int val_s1 = 0;

    const unsigned int ledPins[]={2,3,4,5,6,7,8,9};
    const unsigned int lenledPins=9;

    unsigned long t_s1 = 0;
    unsigned long t_0_s1 = 0;
    unsigned long t_s3 = 0;
    unsigned long t_0_s3 = 0;
    unsigned long t_0_s4 = 0;
    unsigned long t_s4 = 0;
    unsigned long t_s2_4 = 0;
    unsigned long tiempo = 250;

    unsigned long bounce_delay_s1 = 5;

    long total = 0;

    void setup()
    {
      pinMode(pin_s1, INPUT_PULLUP);
      Serial.begin(9600);

      for(int i=0; i<(9); i++)
      {
        pinMode(ledPins[i], OUTPUT);
      }

      cs_11_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
      Serial.begin(9600);

    }

    void loop()
    {

      MBoton();          //MAQUINA DE ESTADO

     MaquinaGeneral();

      if(state_s2 == 1)
      {
        led();
      }

      if(state_s1 != state_prev_s1)
      {
        Serial.print("state =");
        Serial.println(state_s3);
      }

      if(state_s4 == 6)
      {
        for(int i=0; i<lenledPins; i++)
        {
          digitalWrite(ledPins[i],HIGH);
        }
      }

      Serial.print("");

    }

    void MaquinaGeneral()
    {
      switch(state_s2)
      {
        case 0:
        if(state_s1 == 4)
        {
          state_s2 = 1;
        }
        break;

        case 1:

        break;
      }
    }

    void MBoton()
    {
      state_prev_s1 = state_s1;
      switch(state_s1)
      {
        case 0:         //RESET
        state_s1 = 1;
        break;

        case 1:        //START
        val_s1 = digitalRead(pin_s1);
        if(val_s1 == LOW)
         {
          state_s1 = 2;
         }
        break;

        case 2:         // GO!
        t_0_s1 = millis();
        state_s1 = 3;
        break;

        case 3:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= bounce_delay_s1)
        {
          state_s1 = 5;
        }
        break;

        case 5:         //ARMED
        val_s1 = digitalRead(pin_s1);
        if(val_s1 == HIGH)
         {
          state_s1 = 4;
         }
        break;

        case 4:       //TRIGGERED
        state_s1 = 0;
        break;

      }
    }

    void led()
    {

      switch(state_s3)
      {
        case 0:         //OFF
        for(int i=0; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],LOW);
        }
        for(int i=1; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],HIGH);
        }

        t_0_s3 = millis();
        state_s3 = 1;
        break;

        case 1:         //WAIT
        t_s3 = millis();
        if(t_s3 - t_0_s3 >= tiempo)
        {
          state_s3 = 2;
        }
        break;

        case 2:         // ON
         for(int i=0; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],HIGH);
        }

         for(int i=1; i<lenledPins; i=i+2)
        {
          digitalWrite(ledPins[i],LOW);
        }

        t_0_s3 = millis();
        state_s3 = 3;
        break;

        case 3:         //WAIT
        t_s3 = millis();
        if(t_s3 - t_0_s3 >= tiempo)
        {
         state_s3 = 0;
        }
        break;

      }

      }

    void Capacitor()
     {

      switch(state_s4)
      {

        case 0:         //RESET
        state_s4 = 1;
        break;

        case 1:        //START
        total = cs_11_10.capacitiveSensor(10);
        if(total >= 1000)
         {
          state_s4 = 2;
         }
        break;

        case 2:         // GO!
        t_0_s4 = millis();
        state_s4 = 3;
        break;

        case 3:         //WAIT
        total = cs_11_10.capacitiveSensor(10);
        if(total < 1000)
         {
          state_s4 = 0;
         }

        t_s4 = millis();

        if(t_s4 - t_0_s4 >= 2000)
        {
          state_s4 = 5;
        }

        break;

        case 5:         //ARMED & WAIT
        t_s2_4 = millis();
        total = cs_11_10.capacitiveSensor(10);
        if(total < 1000)
         {
          state_s4 = 4;
         }

         if(t_s2_4-t_s4 >= 1000)
         {
          state_s4= 6;
         }
        break;

        case 4:       //TRIGGERED
        state_s4 = 0;
        break;

        case 6:     // ARMED 2
        Serial.println("Entro al estado 6");
        total = cs_11_10.capacitiveSensor(10);
        break;

    }
    }

title: Change From One State Machine To Another

Answers: 2

body:
If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

* FSM 1 states: `STATE_A`, `STATE_B`, `STATE_C`
* FSM 2 stages: `STATE_D`, `STATE_E`
* global states: `FSM_1_RUNNING`, `FSM_2_RUNNING`

Then the combined FSM will have the states `STATE_A`, `STATE_B`,
`STATE_C`, `STATE_D` and `STATE_E`, and all the transitions of both
initial FSMs.

body:
Similar to what others have commented, this is not the best implementation of a Finite State Machine (FSM). You should establish clear states and define what happens during all transitions of your system.

Follow Edgar's advice on using enumerators for your states.

Nick Gammon's guide will surely be of great help: https://www.gammon.com.au/statemachine


body:
I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.)
I'm new to Matlab, so any help would be greatly appreciated.

title: Sending sine wave from MATLAB and reading on Arduino Uno

Answers: 1

body:
No, you can't. The Arduino Uno has no analog outputs to start with and,
as you guessed, it cannot run two programs at the same time.

Maybe you should search for a solution of the _initial_ problem instead.
You should be aware that you cannot get consistent timings with
`analogRead()`. You will have to read the datasheet of the ATmega328p,
especially the section dedicated to the ADC. Then you will configure the
ADC yourself, at the register level. It has a feature called
“auto-trigger” which is intended to provide perfectly consistent
timings. This is what you are looking for.


body: Silly question but how would a circuit be set up with Arduino where two different resistors are in series but one has an unknown value (i.e. is just a piece of metal for example) and so how would we be able to find the current through each, collage through each and thus find the value of the resistance of the unknown wire.

title: Arduino simple resistors in series

Answers: 2

body:
Just a math exercise really.

Say you had a 5V source, two Resistors R1 and R2, and an Arduino.
5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino.
R1 is unknown.

Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2)
Vout (R1+R2) = 5VxR2
R1+R2 = 5VxR2/Vout
R1 = 5VxR2/Vout - R2

Vout = ~ 0.00488mV x Analog In reading. (5V/1024)
If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1:
(5V x 5000)/3V- 5000 = 3333 ohm.

Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V

body:
While [CrossRoads' answer](https://arduino.stackexchange.com/a/66288/17196) got the math sorted out that is likely not the kind of measurement you are aiming for if the unknown resistor has a rather low resistance (*i.e. is just a piece of metal*). Assume the same circuit: 5V - R1 - R2 - GND.

Consider R1 to be a strand of copper wire of ribbon cable, AWG 26, i.e. with a diameter of 0.4 mm (0.016 inch) and a cross section of 0.13 mm², and a length of 3 inches (7.62 mm), being that "piece of metal". Its resistance will be 0.001 Ohms. To have any meaningful readings you'd want to have the other resistor (R2) in the same range otherwise the output voltage of the voltage divider will just be close to VCC (or GND if R1 and R2 are reversed). So assuming R2 to be 0.001 Ohms too, the total resistance of both resistors in series is therefore 0.002 Ohms. Connecting these to a 5V power supply (i.e. a voltage source) we find using Ohm's Law a current of 2500 A - which of course an ordinary Arduino wall plug will not provide. The power supply will either limit the current or its output voltage will be reduced or both - either way not a desirable situation in a measurement setup. Another approach of direct measurement is to apply a known current to the unknown resistor and measure the voltage across it. For any reasonable current that voltage will be rather small (i.e. 1 mV at 1 A) and would need to be amplified before being measured with an Arduino's ADC.

In short, measuring low resistances is difficult and might require a dedicated setup such as a [Wheatstone bridge](https://en.wikipedia.org/wiki/Wheatstone_bridge). Best answers are likely to be found at [Electrical Engineering](https://electronics.stackexchange.com) but need additional input on measurement range and required accuracy.


body:
I have an esp32 which is running a web page together with a java script and using socket I update some values on the web page. I am doing this very fast (like each 50ms). Now I am serving all the html/java script code stored in a string variable but I am wondering which is the best? To store this html in spiff or in code ? and why?
Thank you very much

title: How is better to store html / java script / in code or in flash on esp32

Answers: 2

body:
It depends on your definition of "better".

Directly inlined in your code will probably be faster - it will be subject to the caching mechanisms of the execution pipeline, whereas SPIFFS will have to make specific SPI calls to read the data from the flash chip at the time it's required.  However SPIFFS will be easier to maintain since you are just working with files.

I would probably choose SPIFFS for larger files like graphics or big chunks of Javascript. Things that the client can download once and then cache (as long as your web server supports that kind of functionality - not sure what facilities the default ESP32 web server code has). The rest, the more dynamic things that change often, have as inline string literals.

body:
Best is to store static files in SPIFFS and serve them with Expires header set, to let the browser cache the html, css, js files and pictures files.

How to build the Expires header:

    unsigned long expires = now() + SECS_PER_YEAR;
    bp.printf(F("Expires: %s, "), dayShortStr(weekday(expires))); // two printfs because ShortStr functions share the buffer
    bp.printf(F("%d %s %d 00:00:00 GMT"), day(expires), monthShortStr(month(expires)), year(expires));

And use AJAX method to show data on the page. Make the request with `XMLHttpRequest` object:

    function getData(cmd) {
      var xhr = new XMLHttpRequest();
      xhr.onerror = function(e) {
        alert(xhr.status + " " + xhr.statusText);
      }
      xhr.onload = function(e) {
        showValues(xhr.responseText);
      };
      xhr.open("GET", "http://" + host + ":" + restPort + "/" + cmd, true);
      xhr.send();
    }

`showValues` would be your function to fill the data into page

In ESP32 build the response as JSON for simple handling of the data in JavaScript.

Here is [the WebServer in my project][1]. It uses the basic Arduino Server class, not the esp WebServer. It has `#ifdefs` for SD or SPIFFS. The static files of my project including the js file are [here][2].

  [1]: https://github.com/jandrassy/Regulator/blob/b6ef120c6f8963979268d8d17b56e5632336f317/Regulator/WebServer.ino#L22
  [2]: https://github.com/jandrassy/Regulator/tree/master/Regulator/data


body:
I'm trying to get a HC-05 connected as master to a Bluetooth ELM327 OBD scanner.

The HC-05 is accepting AT commands, no problem. This is the sequence I use:
<!-- language-all: lang-cpp -->

    AT+RMAAD (Clear any paired devices)
    AT+ORGL  (Set factory defaults)
    AT+ROLE=1 (Set role to master)
    AT+RESET (reset needed after role change)

    AT+CMODE=0 (allows connection to any device)
    AT+INQM=0,5,9  (set inquiry to search for up to 5 devices for 9 seconds)
    AT+INIT  (Inits BT)
    AT+INQ  (searches for BT devices)

    AT+PAIR=1D,A5,68988A,9 (Pairs to the address of the ELM327, timeout in 9 secs)
    AT+BIND=1D,A5,68988A (Binds the address)
    AT+CMODE=1  (HC-05 will now only connect with the paired device)
    AT+LINK=1D,A5,68988A (Connect to device)

Everything is fine, until the last step: AT+LINK.
What happens is:

    >at+link=1D,A5,68988A
    FAIL
    +INQ:1D:A5:68988A,1F00,7FFF
    OK
So it fails the AT+LINK, then for some reason, it starts inquiry mode.
I saw a guide which had CMODE=1/0 swapped. I have tried both, anyway, doesn't make any difference to the result. I should be in full AT command mode, I connected 3.3v to pin 34. The password for the ELM327 is 1234, and the default password for the HC-05 is 1234.

If I skip the link stage, then re-power the HC-05 in comms mode, then the ELM327 flashes its green LED which means its transmitting. The HC-05 flashes rapidly, then slowly, then rapidly, then slowly, and so on. But I get nothing in the serial monitor, not even garbled text.

[This is the OBD reader I have][1]

[This is the HC-05 I have][2]

So I don't know what the problem is, I have connected the HC-05 to my phone as a slave, and can send messages to and from it though the serial monitor. So its working. And the ELM327 is working fine when connected to my phone. So both are working fine.

So my guess is, either I'm missing something, like, maybe the outgoing password/pin is set with a different AT Command other than AT+PSWD? Or, maybe this particular HC-05 for some reason isn't capable of master mode? Or maybe the ELM327 I have for some reason will never accept a connection from something other than an android phone?

I just wondered if anyone has some experience with this, and can advise, before I go off and buy another HC-05 and another ELM327. Thanks in advance for any help.

Just for more information, I'm using an ESP32, which I know has bluetooth and I wanted to use it, but I couldn't find how to enter it's AT Commands (at least, not easily), it was just easier to buy a HC-05. So since the ESP32 has 3.3v outputs I don't use a voltage divider. I use the 5V out for the VCC on the HC-05, and I use the 3.3v out to go directly to pin 34. Here's the sketch I use to enter AT Commands:

    #include "HardwareSerial.h"
    #define RXD2 16                //Arduino pin connected to Tx of HC-05
    #define TXD2 17                //Arduino pin connected to Rx of HC-05

    HardwareSerial BTSerial(2);

    char c=' ';
    boolean NL = true;

    void setup()
    {
      // initialize the 2 serial ports:
      Serial.begin(38400);  //For the arduino to communicate with the PC
      Serial.print("Sketch:   ");   Serial.println(__FILE__);
      Serial.print("Uploaded: ");   Serial.println(__DATE__);
      Serial.println(" ");

      BTSerial.begin(38400, SERIAL_8N1, RXD2, TXD2); //-> HC-05 AT mode baud rate is 38400
      Serial.println("BTserial started at 38400");
      Serial.println(" ");
    }

    void loop() {

      // Read from the Bluetooth module and send to the Arduino Serial Monitor
      if (BTSerial.available()) {
        c = BTSerial.read();
        Serial.write(c);
       }

      // Read from the Serial Monitor and send to the Bluetooth module
      if (Serial.available()) {
        c = Serial.read();
        BTSerial.write(c);

        // Echo the user input to the main window. The ">" character indicates the user entered text.
        if (NL) { Serial.print(">");  NL = false; }
        Serial.write(c);
        if (c==10) { NL = true; }
      }
    }

  [1]: https://www.amazon.co.uk/Torque-Pro-Elm-327-Bluetooth/dp/B01AC7I7BO/
  [2]: https://www.amazon.co.uk/DSD-TECH-HC-05-Pass-through-Communication/dp/B01G9KSAF6/

title: HC-05 Bluetooth fails AT+LINK

Answers: 0


body:
I recently bought a wemos d1 mini pro to toy with wifi and bought a oled shield with it. I've been looking on youtube and github for software and I finally found the software and got it to load onto the board. however, the shield is only on for a fraction of a second and I don't know why.

here is the code

    #include "SPI.h"
    #include "Wire.h"
    #include "Adafruit_GFX.h"
    #include "Adafruit_SSD1306.h"

    #define OLED_RESET 0  // GPIO0
    Adafruit_SSD1306 display(OLED_RESET);

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

    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    // init done

    display.display();
    delay(2000);

    // Clear the buffer.
    display.clearDisplay();

    // text display tests
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,10);
    display.println("Hello");
    display.println("World");

    display.display();
    delay(10000);
    display.clearDisplay();
    }

    void loop() {

    }

here is what it says when uploading

    Build options changed, rebuilding all
    Sketch uses 278084 bytes (26%) of program storage space. Maximum is 1044464
    bytes.
    Global variables use 27432 bytes (33%) of dynamic memory, leaving 54488
    bytes for local variables. Maximum is 81920 bytes.
    esptool.py v2.6
    2.6
    esptool.py v2.6
    Serial port COM5
    Connecting....
    Chip is ESP8266EX
    Features: WiFi
    MAC: b4:e6:2d:53:19:6b
    Uploading stub...
    Running stub...
    Stub running...
    Changing baud rate to 460800
    Changed.
    Configuring flash size...
    Auto-detected Flash size: 16MB
    Flash params set to 0x0290
    Compressed 282240 bytes to 204639...

    Writing at 0x00000000... (7 %)
    Writing at 0x00004000... (15 %)
    Writing at 0x00008000... (23 %)
    Writing at 0x0000c000... (30 %)
    Writing at 0x00010000... (38 %)
    Writing at 0x00014000... (46 %)
    Writing at 0x00018000... (53 %)
    Writing at 0x0001c000... (61 %)
    Writing at 0x00020000... (69 %)
    Writing at 0x00024000... (76 %)
    Writing at 0x00028000... (84 %)
    Writing at 0x0002c000... (92 %)
    Writing at 0x00030000... (100 %)
    Wrote 282240 bytes (204639 compressed) at 0x00000000 in 4.8 seconds
    (effective 467.5 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting via RTS pin...

and this is the monitor

    0⸮~?⸮4⸮!⸮⸮⸮⸮OCAG⸮⸮

thank you for your time

title: OLED shield for wemos d1 mini pro not staying on

Answers: 1

body: I fixed the problem. I was the one who did the soldering so i decided to make the soldering better and now it works. thank you juraj for your time


body:
# Context

This may be more of a C++ question than an arduino specific question, but it's dealing with arduino c++ so I thought I'd start here.

I'm building a class to abstract some simple melody playing that I want for a project. I got everything working in a procedural way, so I started moving everything out to a header and cpp file (still new-ish territory for me).

The general concept is that I want to call a public method on my class to allow my code to play a specific melody. I defined an enum for each melody available and in my `playMelody()` method I'm using a couple of pointers and a switch statement to get the specific frequencies and durations I need to play the specific melody. These frequency and duration values are stored in private arrays in the class.

Here's the header:

    // MelodyPlayer.h

    enum MELODY
    {
        SHAVE_AND_A_HAIRCUT = 0,
        IDLE,
        READY,
        PROCESSING,
        COMPLETE,
    };

    class MelodyPlayer
    {
        uint8_t speakerPin;

        int melody_shaveAndAHairCut[9];
        int durations_shaveAndAHairCut[9];
        int *activeMelody;
        int *activeDurations;

        void _playMelody();

    public:
        MelodyPlayer(uint8_t speakerPin);
        void playMelody(MELODY name);
    };

    MelodyPlayer::MelodyPlayer(uint8_t pin)
    {
        speakerPin = pin;

        int melody_shaveAndAHairCut[] = {
            NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4, 0};

        int durations_shaveAndAHairCut[] = {
            4, 8, 8, 4, 4, 4, 4, 4, 4};
    }

    void MelodyPlayer::playMelody(MELODY name)
    {
        switch (name)
        {
        case SHAVE_AND_A_HAIRCUT:
            Serial.println("Shave and a hair cut");
            activeMelody = melody_shaveAndAHairCut;
            activeDurations = durations_shaveAndAHairCut;
            break;
        }

        _playMelody();
    }

And here's the implementation:

    // MelodyPlayer.cpp

    void MelodyPlayer::_playMelody()
    {
        Serial.println("Playing Melody");
        // * pulled from the toneMelody arduino example
        for (int thisNote = 0; thisNote < 8; thisNote++)
        {

            int activeDuration = activeDurations[thisNote];
            int noteDuration = 1000 / activeDurations[thisNote];
            int noteFrequency = activeMelody[thisNote];

            Serial.println(thisNote);
            Serial.println(activeDuration);
            Serial.println(noteDuration);
            Serial.println(noteFrequency);

            tone(speakerPin, noteFrequency, noteDuration);

            int pauseBetweenNotes = noteDuration * 1.30;
            delay(pauseBetweenNotes);

            noTone(speakerPin);
        }
    }

And I call it in my `.ino` file like this:

    MelodyPlayer player = MelodyPlayer(SPEAKER);
    player.playMelody(SHAVE_AND_A_HAIR_CUT);

# The problem

I'll upload the sketch and everything fires. The problem I'm running into is that when I get to the private `_playMelody()` method the values I get for `activeDuration`, `noteDuration` and `noteFrequency` are all ultra wrong:

[![example output][1]][1]

I imagine I'm doing something wrong with the setting and getting of the values via the pointer variable I set in the switch statement, but I'm not sure where I'm going wrong.

You can see/pull down the actual code from the [abstracting-to-class branch of my repo][2] if you want to dig in.

I've done [a similar dynamic-selection-via-pointer][3] in a proof of concept before, but it was procedurally written, not classed. I can't seem to figure out where the difference is :|

Any ideas?

  [1]: https://i.stack.imgur.com/09N0i.png
  [2]: https://github.com/chris-schmitz/tone-without-delay/tree/abstracting-to-class
  [3]: https://github.com/chris-schmitz/pegasus/blob/master/prototypes-and-pocs/break-beam-and-rfid-poc/break-beam-and-rfid-poc.ino#L154

title: Having an issue accessing values from a pointer

Answers: 1

body:
As Majenko mentioned in the comment, you created new local arrays in the constructor, but never put anything in the member arrays of the classes. They have the same name, but are not the same variable. Responsible for creating the new variable is the keyword int. However, you cannot simply assign array values by just omitting the int. Therer are multiple possibilities:

 - You can fill the array for each index: `durations_shaveAndAHairCut[0] = 1;`

 - You can copy your local array to the member variable with memcpy: `memcpy((void*)this->durations_shaveAndAHairCut, (void*)durations_shaveAndAHairCut, 9*sizeof(int));`

 - You can declare the arrays static in the class declaration and initialize it outside of the constructor in MelodyPlayer.cpp:

        int MelodyPlayer::durations_shaveAndAHairCut[] = {
            4, 8, 8, 4, 4, 4, 4, 4, 4};
    I prefer the last option.


body:
I want to control the speed and position of stepper motor by a 4*4 keypad and monochrome graphic lcd interfaced with arduino. some open sources gave me good hint points to start controlling the distance and the speed of the stepper motor .
 I have made some modifications on the code in order to use it in both controlling the speed of motor and distance. I expect from the code either to:

1- change the position from 1 line to another and change the value at each parameter and see it on the graphic screen.

2- To change the page of the graphic lcd and modify each parameter separately in each page.

[I tried to code the first option but I faced the problem of changing the line to the next parameter without changing the written value, and that was a bit hard to me.]
The code contains of functions that changes the pressed keypad signal to a readable number to be able to draw it in the lcd, then these functions are called by case statements.

I have modified the code to have a number string for each parameter separated from the other one.

When I modified the loop code (as cleared below), I have seen that when I press 'A' or 'B' for the first time, one of the parameters screen is shown on the screen and the loop of this parameter is activated, and I can not change the parameter by pressing the other button.
 This is because of the While loop [While(1)] which frames me in one of the buttons loops forever.
When I remove this loop, the case statements are no longer valid, I just see the change in the screen but I can not add or remove any number.
So that I tried to change it this loop with other options like: while( keypressed == 'A') or [do -- while(0)] or if statements, but no results on the screen.
this is the part of the code.

    void loop()
    {

    char keypressed = customKeypad.getKey();  // Get value of keypad button if pressed

    if (keypressed != NO_KEY)     // If keypad button pressed check which key it was
    {
        if (keypressed == 'A')
        {
            Serial.println("A");
            draw3();
            while(1)
            {
                char key1 = customKeypad.getKey();
                if (key1 !=NO_KEY)
                {
                    switch (key1)
                    {
                        case '1':
                            checknumber(1);
                            break;
                        case '2':
                            checknumber(2);
                            break;
                        case '3':
                            checknumber(3);
                            break;
                        case '4':
                            checknumber(4);
                            break;
                        case '5':
                            checknumber(5);
                            break;
                        case '6':
                            checknumber(6);
                            break;
                        case '7':
                            checknumber(7);
                            break;
                        case '8':
                            checknumber(8);
                            break;
                        case '9':
                            checknumber(9);
                            break;
                        case '0':
                            checknumber(0);
                            break;
                        case '*':
                            deletenumber();
                            break;
                        case'#':
                            calculatedistance();
                            break;
                        }
                    }
                }
            }
            if (keypressed == 'B')
            {
                draw4();
                Serial.println('B');
                while(1)
                {
                    char key1 = customKeypad.getKey();
                    if (key1 !=NO_KEY)
                    {
                        switch (key1)
                        {
                            case '1':
                                checknumber(1);
                                break;
                            case '2':
                                checknumber2(2);
                                break;
                            case '3':
                                checknumber2(3);
                              break;
                            case '4':
                                checknumber2(4);
                                break;
                            case '5':
                                checknumber2(5);
                                break;
                            case '6':
                                checknumber2(6);
                                break;
                            case '7':
                                checknumber2(7);
                                break;
                            case '8':
                                checknumber2(8);
                                break;
                            case '9':
                                checknumber2(9);
                                break;
                            case '0':
                                checknumber2(0);
                                break;
                            case '*':
                                deletenumber2();
                                break;
                            case'#':
                               stepperspeed();
                               break;
                            }
                        }
                    }
                }
            }
        }

title: Arduino Stepper motor control programming problem

Answers: 0


body:
The Raspberry Pi has 3.3 V logic level and the Arduino has a 5V logic level.  It is warned against connecting the Arduino TX to the Pi RX:

> [Pi is 3.3v and the Arduino is 5v. Connect the two and you might conjure up some magic blue smoke][1]

I was wondering if without a logic level converter chip like the CD4050, you could use the PWM functionality of the Arduino plus a low-pass-filter to effectively produce 3.3 V TX signals that would be safe for the Pi RX to receive?

I have an Arduino Uno with an ATMega8 [according to the schematic][2].  It seems it is possible to [change the frequency of the PWM pins][3] to up to 32 kHz.  I assume it's possible to use the PWM with a low-pass-filter to effect a 3.3 V and as it runs at 32 kHz this frequency would then be more than enough to support 9600 baud rate.  Is this correct?  I'm finding it hard to search for "Arduino send serial using PWM".  The SoftwareSerial library requires any Digital IO pins so this sounds like it might not allow for using the PWM pins?  I've also read SoftwareSerial library can use the Analog Input pins for output i.e. TX?

  [1]: https://pinout.xyz/pinout/uart
  [2]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [3]: https://github.com/fizcris/PWM_frequency_Arduino_change

title: Send serial data at custom voltage using PWM

Answers: 2

body:
A simple voltage divider between the Arduino TX and the Pi RX should work to protect the Pi.

And thanks to Juraj's comment, it appears that the Pi's [3.3V high will be enough to trigger the Arduino][1] and it won't need to be boosted up to nearer 5 V.

  [1]: https://arduino.stackexchange.com/questions/66170/how-does-the-dual-5v-and-3-3v-output-on-the-uno-r3-work-exactly/66180#66180

body:
>  I assume it's possible to the change the value of the **voltage** the PWM is producing

This is not possible. PWM cannot output an analog voltage. Instead, it rapidly switches between 5 V and 0 V.


body:
I'm working on a project that consists of sending data from flex sensors from a master Arduino to a slave arduino that uses that data to control servo-motors. I am trying to start slow and just control an LED using a button.
I have gone through all AT commands, have set both a master and a slave and binded the addresses but when I try to light the LED on it for some reason doesn't work. My serial monitor keeps printing the letter "d" over and over again and I don't know what this is. Code is below:

    int val=0; //Master code
    #define button 3
    void setup() {
    Serial.begin(38400);
    pinMode(button,HIGH);
    }
    void loop(){
    val=digitalRead(HIGH);
    if(val==HIGH){
    Serial.write(100);
    delay(500);
    }
    delay(50);
    }
    }

 ------------------------------------

    #define led2
    int pos=0;
    int val;

    void setup(){
    Serial.begin(38400);
    pinMode(led,OUTPUT);
    }
    void loop(){
    if(Serial.available()>0){
    val=Serial.read();
    if(val==100 && pos==0)
    {
    digitalWrite(led,HIGH);
    pos=1;
    }
    else if(val==100 && pos==1)
    {
    digitalWrite(led,LOW);
    pos=0;
    }
    }
    }

If anyone can help i'd appreciate

title: Communication using two HC05 modules

Answers: 0


body:
I have a project that I hope to accomplish in the near future.
I want to transform a mobile home into automation mobile home.

The elements that make up my project are the following:
[![schema of hardware][1]][1]

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

 My idea is to supply the home with a solar installation, disregarding their potential (we can discuss the autonomy of the system later, uses and consumptions).

The idea is to keep an Arduino always running in order to monitorize the home and provide remote administration.(like geolocation, camera and sensors control,power management for hardware ...)

The laptop can be out of the system (when I take it with me). It could be connected to a secondary monitor.
The docker provide an easy way to charge the laptop, connect devices and provide a WOL utility.

The Arduino could have differents components like Ethernet, own battery, gps... And It could switch on/off the camera and sensors.
The laptop could be powered on/off by WOL and administrate remotely.

The camera could have a microSD to save media and it can be manipulated with Arduino by a remote connection.
Arduino could get info about sensors too(as proximity).

I have some doubts:

 1. Instead of using WOL , we could use Arduino to wake up the laptop?
 2. It's possible to connect the laptop and the arduino by wlan or ethernet interface? or we need to wire it (usb...)?

Thanks for the attention, I await your answer.

title: (Advice) Home Automation Project (Domotic mobile home)

Answers: 1

body:
The Arduino is not built or powerful enough to handle things like cameras and high-speed 4g connections for remote administration. I would suggest using something like a [Raspberry PI][1] 3 as it would be much better suited to the job.
  [1]: https://www.raspberrypi.org/

I would recommend asking this question again on the raspberry pi exchange.


body:
In the IRremote library, IR signals are decoded and held in **results.value**.  My project uses the NEC protocol which is 32 bits, so the IR code will always be 4 bytes.
<!-- language-all: lang-cpp -->

    uint32_t dCodedIR;
    //
    //  code exists here that we can ignore
    //
    dCodedIR = results.value
 This decoded signal is then sent out the serial port to a second MCU which will be waiting for incoming data:

    while (!Serial.available())  {
    }

After this, there will ideally be a complete code of 4 bytes waiting in the FIFO. I will allow for times when < 4 bytes are ready (check for more, timed out? NO:loop   YES:reset), but this should rarely happen. So I want to optimize the sending code so that the receiver has the best chance of avoiding split groups. In theory, is it better to write as single bytes and repeat 4 times, or make a 4-byte array to send once?

    Serial.write(dCodedIR & 255);
    Serial.write((dCodedIR >> 8) & 255);
    Serial.write((dCodedIR >> 16) & 255);
    Serial.write((dCodedIR >> 24) & 255);

or

    byte sendBuf[4];
    //
    //
    sendBuf[3] = (byte) dCodedIR & 255;
    sendBuf[2] = (byte) (dCodedIR >> 8) & 255;
    sendBuf[1] = (byte) (dCodedIR >> 16) & 255;
    sendBuf[0] = (byte) (dCodedIR >> 24) & 255;
    Serial.write(sendBuf, 4);

(Since there will be plenty of storage space for the code, with performance being the priority, I decided against using **for** loops because updating an index, testing it, and looping would seem to add overhead.)

title: Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1

Answers: 1

body:
Unless you are using very high baud rates, (at least higher than
115.2 kb/s), it should make no difference.

The reason is that either version of your code should run faster than
the UART. `Serial.write()` doesn't wait for the bytes to be sent out the
wire. Instead, it just stores those bytes in a ring buffer that belongs
to the HardwareSerial library. When the UART is ready to accept an
outbound byte, it triggers an interrupt. The corresponding ISR takes one
byte from the ring buffer and handles it to the UART. Since the UART
itself is double-buffered, all this happens while the previous byte is
being sent.

The end result is that, with either version of your code, you end up
with a continuous byte stream. The start bit of the second byte comes
_right after_ the stop bit of the first byte, and so on. The stream
doesn't pause until the full message is sent. That is, unless you have
somewhere in your program overly long critical sections that can impose
excessive latency to the whole process.

**Side note**: if your MCU is little endian (most Arduinos are), you
could also avoid one copy and just do

```c++
Serial.write((byte *) &dCodedIR, 4);
```

------------------------------------------------------------------------

**Addendum**: The details may depend on the MCU you are using. On an
Uno, or similar AVR-based boards, the UART has no knowledge of the
software ring buffer. It rises the `UDRE0` (data register empty) flag
whenever it is ready to accept an outbound byte in its sender data
register. When there is data in the buffer, the software enables the
data register empty interrupt, which is tied to the `UDRE0` flag.


body:
I am learning Arduino(uno)-ESP32 basics for a hobby project. In Arduino sketch, it's writing some random value(mimicking a sensor) to Arduino analog pin 9.

    const int analogInPin = A0;  // NOT CONNECTED
    const int outPin = 9;        // DIGITAL OUT. [ESP32 INPUT]

    // SETUP()
    randomSeed(analogRead(analogInPin));

    // LOOP()
    sensorValue = random(0, 1024);
    // 0 - 5v WHEN MEASURED
    // MAP VALUE OR JUST WRITE 'sensorValue'
    outputValue = map(sensorValue, 0, 1023, 0, 255);
    analogWrite(outPin, outputValue);

In ESP32 sketch, I'm trying to read this value

    int adc_value = 0; // EXPECTS A VALUE B/W 0 - 4095

    //SETUP()
    pinMode(26,INPUT);

    //LOOP()
    adc_value = analogRead(26);
    Serial.println(adc_value);// OUTPUT 2 VALUES; 0 AND 4095
    // MAP_VALUE = (adc_value * 5 ) / (4095);

The output is only 2 values, 0 and 4095. Is it due to ESP 3.3V and Arduino 0-5v output range or some other mistakes?

title: How to read voltage value from arduino to esp32

Answers: 0


body:
I am doing code of esp while switching hotspot for connecting esp i am getting some problem .
I am using this line of code:

    while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

but it is not working. Anybody please give me alternate how to use this type of looping.

title: How to use while loop in arduino for infinte loop

Answers: 1

body:
The `find` method reads the characters until the searched string is found or a timeout interval is passed.

In your case if the connection is not successful, **the first `find`** will not find "WIFI" and **will read all the input** including the "+CWJAP:3", then on timeout it returns false. The second `find` will wait until timeout and then return false.


body:
I am using atmega 2560 as main(master) controller and other 5 salve 2 atmega 8 and 3 atmega 328p, there is two device with analogue output connected to main controller atmega 2560 through ads1115 module ,ads1115 converts analogue signal into 16 bit digital data and give it to atmega 2560 via I2C,

also the main controller has serial communication with pc and I2C comm. with salves. and some motors are also connected with controllers.

Now, My issue is that there is one function which reads the data from ads1115 for fix instances and with fix time interval and prints it. for running code for some time lets say 4-5 hour , controller hangs in between that function. and after that no serial communication work. i have to switch of supply to restart the machine.

title: Controller freezes

Answers: 1

body:
It's hard to say anything for sure without seeing the code, but for a
program that freezes using I2C communication, I would seriously suspect
the Wire library. This library has a few loops here and there where it
waits for a specific condition on the bus, with _no timeout_. See
[twi.c][]. If, for whatever reason, the condition never happens, then
the program is stuck in the infinite wait.

You could try finding al alternative I2C library or, if you can tolerate
the occasional crashes, enable the watchdog in order to get out of the
freezes.

[twi.c]: https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/libraries/Wire/src/utility/twi.c


body: Baud rate is set to 115200 in both the serial monitor and in the setup() portion of the code. The output to the serial monitor just looks like a bunch of reverse question marks on MacOS and on Windows it's a bunch of gibberish characters. Any idea how to fix this and why it would have changed when the output used to be what I expected? Weird thing is the program on the board is still working because I'm seeing the proper output on my server but I want the serial monitor working for debugging if it's not making it to the server.

title: Serial monitor garbage output on both MacOS and Windows devices, output used to make sense

Answers: 0


body:
I'm a little bit confused. I'm running the same code on a ESP32 (Adafruit Huzzah32) and an Arduino (SparkFun Pro Micro). It works on the ESP32 but not on the Arduino.
Are there different API implementations?
It seems that the timings are not the same. The Arduino does not have the gaps between the bytes.

[![spi clock timing][1]][1]

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

title: SPI - different implementation / timing

Answers: 0


body: I am looking to build a device that can measure the dendrometry fluctuations of trees (etc). I essentially want to build this https://publiclab.org/notes/kinasmith/09-09-2016/dendrometers to a t but I don't know where to start. I have admittedly pretty limited knowledge of arduino/microcontrollers and microcontroller kits and sensors.

title: How to start a dendrometry dimension build (Dimensions of Trees) for research?

Answers: 1

body:
The measuring principle, that is describe in that link, is quite cool and simple.

The string is wrapped around the tree. One end is connected to a fixed point (here the casing of the sensor). The other end is connected to a spring, which in turn is again connected to a fixed point. As the tree get's bigger, it will pull at the string. At the first side of the string nothing happens (because it is a fixed point). But the end with the spring will move according to the force of the tree. Force and displacement have a linear relationship for a spring (as long as you don't overload it): `F = k*x` with the force `F`, the spring constant `k` and the displacement `x`.

The displacement of the springs end can be measured with a linear potentiometer. That is just a simple strip of resistive material with a glider, which can be set to any position at the strip. It will create a voltage divider, giving you an analog voltage depending on the position (most potentiometers are linear, but there are also others). Connect both ends of the potentiometer to Vcc (supply voltage) and ground respectively and the glider to an analog pin of the Arduino. Then you can measure the voltage with `analogRead()`.

As jsotola mentioned in his comment: Be sure to use a string, that will not stretch too much, as this will make your measurement less precise.


body:
I want to put a 2 seconds delay to temperature reading but the `millis()` delay is not applying.
<!-- language-all: lang-cpp -->

    #include <OneWire.h>
    #include <LiquidCrystal_I2C.h>
    #include <DS3231.h>
    #include <DallasTemperature.h>

    #define ONE_WIRE_BUS 2

    Time t;
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    DS3231  rtc(SDA, SCL);
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    const int OnHour = 23;
    const int OnMin = 42;
    const int checkTemp = 2000;
    const int checkTempinterval = 0;

    void setup() {
      Serial.begin(115200);
      pinMode(3, OUTPUT);
      lcd.begin();
      lcd.backlight();
      rtc.begin();
    }
    void loop() {
      t = rtc.getTime();
      float testTemp;
      testTemp = temperature();
      lcd.setCursor(0,0);
      lcd.print(testTemp);
      lcd.print("   ");
      lcd.print(rtc.getTimeStr());
      lcd.setCursor(0,1);
      lcd.print(rtc.getDOWStr());
      lcd.print("   ");
      lcd.print(rtc.getDateStr());
      if(testTemp >= 28){
        digitalWrite(3,HIGH);
      }else{
        digitalWrite(3,LOW);
      }
    //  if(t.hour == OnHour && t.min == OnMin){
    //    digitalWrite(3,HIGH);
    //  }else{
    //    digitalWrite(3,LOW);
    //  }
    }
    float temperature(){
      unsigned long currenttime = millis();
      if(currenttime - checkTempinterval >= checkTemp){
      sensors.requestTemperatures();
      float testTemp = sensors.getTempCByIndex(0);
      currenttime = checkTempinterval;
      return testTemp;
      }
    }

title: can't return float value from function

Answers: 2

body:
I see 2 problems with your code:

1. **Returning a value from a function:** If you want to return a value from a function, you will have to make sure, that in any case the `return x` statement is executed inside the function in the `temperature()` function you currently have this if statement:

        if(currenttime - checkTempinterval >= checkTemp){

    Inside of it is the only `return` statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).

    Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example `-300`; the error value should not be found inside valid data)? Then do so after the `if` statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the `if` statement.

    If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.

2. **Doing the `millis()` code correctly:** What you are doing wrong here, it that you update the wrong variable inside the `if` statement. Currently you write the value of `checkTempinterval` (which is the time of the last measurement) to the variable `currenttime`. The variable `currenttime` was declared locally (meaning inside the function) by using

        unsigned long currenttime = millis();

    Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the `return` statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.

    What you actually meant to do, was to do it vice versa:

        checkTempinterval = currenttime;

    `checkTempinterval` is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.

    **Very important:** Currently `checkTempinterval` is defined as `const int` meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use `int` here, because it's value range goes only up to 32767, which is 32 seconds when used with `millis()`. After that, it will overflow to negative values. Better use the type of `millis()` return value: `unsigned long`. It has 4 byte (instead of `int`s 2 byte) and will only overflow after 49 days. If you only use this variable type for things with `millis()`, even this overflow will not be a problem.

body:
You can use the `millis()` function to create a "timer" that will get the sensor reading every 2 seconds. The sketch `BlinkWithoutDelay.ino`, should come with the Arduino IDE, but if not, you can find it here: [BlinkWithoutDelay][1].

I've used that exact sketch with some modifications to display the results on the Serial Monitor instead of blinking an LED. When you are creating something, using the Serial Monitor can help you to De-bug your sketch.

Please read the code comments in the following sketch. Once you have this working with your code, then you could decide if you need a function or not.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
<!-- language-all: lang-cpp -->

    // Store the last time you checked the sensor.
    unsigned long previousMillis = 0;

    // interval at which to checked the sensor (milliseconds)
    const long interval = 2000;

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

    void loop() {
      // here is where you'd put code that needs to be running all the time.

      // Get the current time.
      unsigned long currentMillis = millis();

      // Check to see if it's time to check the sensor reading.
      if (currentMillis - previousMillis >= interval) {
        // save the last time you checked the sensor.
        previousMillis = currentMillis;

        // This is where you add the code that checks the sensor.

        // Test output.
        Serial.println("Checking Sensor");
      }
    }


body:
I want to sample Sound input with either an ESP8266 (preferred) or ESP32. As I'm using a low pass filter anyway, a sample rate of 1000-2000hz would be totally ok. What is more important, is that it is constant. Can I use DMA for that? If so: how? Or should i go via Timer interrupts?
I know about the wifi issue on the ESP8266, but I intend to just turn Wifi off as I don't need it for this project.

title: Constant ADC sampling rate on ESP8266 or ESP32

Answers: 2

body:
Have you looked "BlinkWithoutDelay" sample on Arduino? The most valuable part of it is the following:

    void loop() {

        unsigned long currentMillis = millis();   // NOTE: 1

        if (currentMillis - previousMillis >= interval) {  // NOTE: 2
             // save the last time you blinked the LED
             previousMillis = currentMillis;  //NOTE: 3
             .. do your thing here ..
        }
    }

Take into account the places from **NOTE 1** to **NOTE 3** I have marked in comments:

**NOTE 1:**

First thing in the loop where you mainly go is taking current time in millis. Should not take a lot of effort from Arduino to achieve.

**NOTE 2:**

Second thing is a comparison: is there enough time gone to make your thing ( = to take the sample) or not? If it is false, you make another round. If true, make it! Again, no big effort from computer.

**NOTE 3:**

Here you reset the timer, **BEFORE** doing anything else. So, your "sample interval clock" is quite precise, it consists of three little steps inside the computer and it should work in fractions of seconds accuracy (time estimate = (1 / Arduino clock speed) * some machine commands).

The other commands: taking sample, storing or sending it, should happen inside the one millisecond left from these commands. Do make a note, 1000 samples gives you 1ms time and 2000 samples 0.5ms time. This example fits perfectly to the 1000 samples case, as the accuracy of your clock is 1ms. I would go with that, if possible.

The time left, 1ms is quite long as a machine's executing time, but you have to make sure that some other components like a WiFi connection you mentioned, may be harmful for this approach. The other part of code inside the loop cannot take more than 1ms, otherwise it affects to the constant rate. Anything less than 1ms is ok, this algorithm makes no difference between 0.1ms or 0.9ms hard work inside the `if`, the accuracy of 1-10 machine words always holds.

*(I don't know exactly how long command `if` is, nor how long is function `millis()`. If you want to be very precise, you may take these in account, but IMHO you can omit their importance in calculations: whether they take some time or not, anyways the execution of these may be quite well taking the same on every round - in constant time!)*

**SOURCE:**

https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

body:
You have several options for controlling the sampling rate.

## Software only

This is the simplest, and the previous answer got it almost right. Here
is my take:

```c++
const SAMPLE_INTERVAL = 500;  // 500 microseconds

void loop() {
    static unsigned long last_sample_time;
    if (micros() - last_sample_time >= SAMPLE_INTERVAL) {  // note 1
         last_sample_time += SAMPLE_INTERVAL;  // note 2
         // Take your sample here.
    }
}
```

**Note 1**: On the AVR-based boards, `millis()` is _not_ accurate to the
millisecond. It tends to get late, then compensate for this by jumping
by two milliseconds at once. For controlling a process that should
happen every 1 ms exactly, `millis()` is very clearly _not_
suitable. I do not know how good is the ESP8266's `millis()`. It may
well be better than the AVR version. However, even a perfect `millis()`
will not be good for anything faster than 1 kHz.

The solution to this problem is pretty trivial: just count the time in
microseconds instead of milliseconds. The only drawback of using
`micros()` is that you cannot measure durations longer than about
71.6 minutes, which in turn means you cannot use it for sampling at
any rate slower than 233 µHz. Obviously this is not something you
should be concerned about. Note that the `micros()` rollover is not an
issue as long as you are sampling faster than the rollover period.

**Note 2**: It is impossible to have a steady sampling rate if it is
controlled by software. The best you can hope for is a tight control on
the _average_ sampling period. This is accomplished by updating
`last_sample_time` as

```c++
last_sample_time += SAMPLE_INTERVAL;
```

Note that this variable holds the time when the last sample was supposed
to be taken, not the time it was actually taken. The sample was probably
taken a little bit behind schedule, as anything the CPU does takes time.
Updating `last_sample_time` this way means that these timing errors _are
not cumulative_. They would be cumulative if you did it in the “Blink
without delay” style, namely

```c++
previousMillis = currentMillis;
```

The drawback of this software method is that it inherently has a
significant amount of jitter. The program tests the current time only
once per loop iteration, and it may have other things to do within that
loop that adds to its execution time.

## Software triggered by interrupts

I have never programmer an ESP timer but, if you can, it should provide
you better timings than the software-only version. Have the timer
deliver an interrupt at the desired sampling period, and use the ISR for
triggering the ADC. You may wait for the result inside the ISR, store it
in RAM, and set a flag to tell the main loop that a new sample is
available, as in

```c++
volatile int analog_sample;
volatile bool analog_sample_valid;

ISR(whatever_timer_interrupt)
{
    analog_sample = analogRead(ANALOG_PIN);
    analog_sample_valid = true;
}

void loop()
{
    if (analog_sample_valid) {
        int analog_sample_copy = analog_sample;  // note 1
        analog_sample_valid = false;
        // handle analog_sample_copy here
    }
}
```

**Note 1**: On an 8 bit Arduino, you would have to do this with
interrupts disabled. You shouldn't need to disable interrupts on a
32 bit platform.

This method should significantly reduce the jitter compared to the
software-only version. Now the sampling doesn't have to wait for the
program to run through the loop and reach the point when the time is
tested. Instead, whatever the program is doing, it will be immediately
interrupted for doing the sampling. Well... almost. From time to time it
will happen that the interrupt fires when the program is running with
interrupts disabled. This may be the case if it is already servicing
another interrupt. When this happens, the sampling will have to wait
until interrupts are enabled again. You end up with a jitter that is
_most of the time_ a small fraction of a microsecond, and then
occasionally a sample is late by several microseconds.

## Hardware only

On an AVR, you can configure the ADC to be automatically triggered by a
timer, or even to automatically trigger itself in the so called “free
running mode”. I do not know the specifics of the ADC in the ESP8266.
You may want to read the datasheet and see if it offer similar
functionality. If you can enable ADC auto-triggering, then you will have
_cycle-accurate_ timings. The steadiness of your sampling will be just
as good as the quartz crystal clocking your MCU. No software solution
can ever come close to this level of perfection. The only drawback of
this method is that you will have to study the datasheet of your ESP in
order to implement it.


body:
For my home-automation project I'm using several arduino nano's with each a NRF24L01+ module. Each module is able to both receive and transmit with one another. Everything seemed to be flawless for a couple of hours, but after a couple of hours it either stops transmission (completely frozen) of receives the last data repeatedly. In my design I'm using the RF24 and RF24Network libraries, I was wondering whether someone managed to automatically reset the NRF24L01 module using code, when one of these errors occured, and could share his/her code?

I already found this [form][1], but this is only using the standard RF24 library, whereas I'm also using the RF24Network library. Furthermore, in this [form][1] it is having a seperate TX and RX side, whereas I like to have each module to be able to both send and receive.

Some extra side information, I use a stable power supply with a capacitor connected to the module, also the wires are soldered to the module.

I hope somebody can help me with this,

Guido

  [1]: https://arduino.stackexchange.com/questions/55042/how-to-automatically-reset-the-nrf24l01-with-code?newreg=2fa5adae412e4ec186e60fe188a0335e

title: How to automatically reset the NRF24L01 module

Answers: 3

body:
This is a known problem with those chips (especially Chinese clones). It is caused when a chip gets stuck in TX mode waiting for an ACK that never arrives back.

The chips don't have a "reset", but switching them into low power mode and then back on again, which doesn't affect any register settings, aborts the current TX operation.

`RF24Network` is merely a protocol layer on top of the `RF24` library. That `RF24` library has `powerDown()` and `powerUp()` methods. Simply call powerDown followed by powerUp on your RF24 driver object.

body:
@Majenko thank you for your suggestion, I have been playing around a little bit with the powerDown() and powerUp() functions but unfortunately I haven't got it to work yet. Again, it seemed to work for a couple of hours and then again seem to get stuck. Therefore, I also included my code to see if I maybe made some major mistakes.
Furthermore, I assume that I'm having such Chinese clones of the NRF24L01+, as I have bought mine on Aliexpress.

I have included several parts of my code, the following part resets the NRF24L01+ module once a failure is detected. In here I also included the suggested powerDown and powerUp functions.

    void NetworkReconnect()
    {
      pinMode(CE_PIN, OUTPUT); digitalWrite(CE_PIN, HIGH);
      pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH);

      radio.powerDown();

      radio.begin();

      radio.powerDown();

      Network.begin(90, thisNode);

      delay(100);

      radio.setPALevel(RF24_PA_MAX);
      radio.setDataRate(RF24_1MBPS);

      radio.powerUp();
    }

The following code I have in my **void.loop()**, every 5 seconds I check the network connection, by calling **NetworkCheckConnection()** (see last part of included code). Which tries to figure out whether the module has crashed, I found this failure detection as a suggestion at a discussion form on the RF24 library on [GitHub Discussion][1]. Furthermore, the while loop is limited to only 500ms to avoid being in an infinite loop, if this is exceed, the function **NetworkReconnect()** is called again.

    void loop()
    {

      Network.update();

      if (millis() - Timer > 5000)
      {
        NetworkCheckConnection();
        Timer = millis();
      }

      if(radio.failureDetected){
        radio.failureDetected = false;
        delay(250);
        Serial.println("Radio failure detected, restarting radio");
        NetworkReconnect();
      }

      if (Network.available())
      {
        uint32_t failTimer = millis();
        while (Network.available())
        {
          if(millis() - failTimer > 500)
          {
            radio.failureDetected = true;
            Serial.println("Radio available failure detected");
            break;
          }

          ... The usual Network.read stuff ...

        }
      }

      ... Remainder of code ...

    }

And lastly the **NetworkCheckConnection()** code, this code is based on the [RF24 Failure handling example][2] and the principles used for checking connectivity of the RF24Mesh network [link][3] (see line 140).

    void NetworkCheckConnection()
    {
      if (radio.getDataRate() != RF24_1MBPS)
      {
        radio.failureDetected = true;
        Serial.println("CheckConnection FailureDetected");
        return;
      }
      // see line 140 of: https://github.com/nRF24/RF24Mesh/blob/master/RF24Mesh.cpp
      bool ok = 0;
      if(radio.rxFifoFull() || (Network.networkFlags & 1))
      {
        return;
      }
      RF24NetworkHeader header(otherNode, NETWORK_PING);
      ok = Network.write(header,0,0);
      if(ok) { Serial.println("Network Connected");       return;}
      if(!ok){ radio.stopListening(); NetworkReconnect(); return;}
    }

Lastly, I also call the **NetworkReconnect()** function if any of my Network.write functions fails.

I hope that you can give me some suggestions on how to get this module to work more reliable, any suggestion is welcome!

Thanks in advance :)

  [1]: https://github.com/nRF24/RF24/issues/5
  [2]: http://tmrh20.github.io/RF24/GettingStarted_HandlingFailures_8ino-example.html
  [3]: https://github.com/nRF24/RF24Mesh/blob/master/RF24Mesh.cpp

body:
Same issue; Simple work-around did it for me: (1) supply +3.3V power the nRF24L01 from a digital pin, using a forward bias diode/LED (with Vf in range 1.7-2.3V) to reduce voltage to compliant range (2.7-3.3V), then (2) in **setup** say, switch the pin to OUT/HIGH

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

Notes:

A) If you have 3.3V device then you can skip voltage reduction in (2)

B) nRF24L01 power consumption peaks at 13mA (quiescent is miniscule) so well within spec for output pin

C) Of course you can do (1) with a voltage divider, or a level converter chip, etc, but the appeal of the LED (I checked Vf across 100 ohm @5V to find a decent match) is that it is simple, passive and in-line and has the nice added advantage of a faint flash when transmitting or receiving!

Look here also [nRF24L01 reset][1]

  [1]: https://devzone.nordicsemi.com/f/nordic-q-a/72523/nrf24l01-reset


body:
I'd like to use an SD card to provide the login credentials to an ESP32. I've already got the ESP32 reading the relative data from the SD card and storing it as a char array on the ESP, but when I use those arrays in the WiFi.begin function it never connects.

Is this something to do with the way arrays work or am I doing something else wrong?

Respective code:
<!-- language-all: lang-cpp -->

    if (dataFile) {
    Serial.println("File is available");
    while (dataFile.available()) {
      byte currbyte = dataFile.read();
      if (currbyte == 58) {
        reading = 1;    //Begin reading data
        i = 0;
      }
      while (reading == 1 and s == 0) {
        byte currbyte = dataFile.read();
        //Serial.print(currbyte);
        //Serial.println(char(currbyte));
        if (currbyte == 13) {
          s = 1;
          reading = 0 ;
        }
        ssid[i] = char(currbyte);
        i++;
        //Serial.println(ssid);
      }
      while (reading == 1 and s == 1) {
        byte currbyte = dataFile.read();
        //Serial.print(currbyte);
        //Serial.println(char(currbyte));
        if (currbyte == 13) {
          s = 2;
          reading = 0 ;
        }
        password[i] = char(currbyte);
        i++;
        //Serial.println(password);
      }
    }
    dataFile.close();
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED and count < 20) {
    Serial.println("Connecting to WiFi..");
    delay(1000);
    count++;}

title: Connecting to WiFi on ESP32 using credentials from SD card

Answers: 1

body:
you add the '\13' to the SSID and password string instead of the terminating zero, because `ssid[i] = char(currbyte);` runs for 13 too

use readBytesUntil()

      char ssid[33];
      int l = file.readBytesUntil('\n', ssid, sizeof(ssid));
      if (l > 0 && ssid[l-1] == '\r') {
        l--;
      }
      ssid[l] = 0;


body:
Hi i am trying to make a comunication between theses device but when i am trying to run in my raspberry i have the follow error:

> Traceback (most recent call last):
  File "serial.py", line 1, in <module>
    import serial
  File "/home/pi/Desktop/serial.py", line 2, in <module>
    ser = serial.Serial('/dev/ttyACM0', 9600)
AttributeError: 'module' object has no attribute 'Serial'

i have the next code:

    import serial

    ser = serial.Serial('/dev/ttyACM0', 9600)

    while 1:

        if(ser.in_waiting >0):
            line = ser.readline()
            print(line)

 If any can help me, i will be thankfull

title: Error conecting raspberry with my arduino in a serial port

Answers: 1

body:
What's almost certainly happening here is that you've named your file `serial.py`, so the import is trying to load the library from your file within the current working directory.

To fix this problem, simply rename your `serial.py` script to something else, for example `serial_comms.py` or whatever other useful name you want.


body:
Context: I have a [NETGEAR][1] router on the first story of my home, the range doesn't extend to the ground floor. I do have a cable duct from my router(on the first story) to the ground floor.

Question:

Is it possible to **wire** a [Keyes ESP8266][2] to my router to act as a WiFi range extender?

Note: The length of the cable would be 10 meters.

  [1]: http://www.downloads.netgear.com/files/GDC/WGT624V3/WGT624v3h1_ds_12May05.pdf
  [2]: https://wiki.keyestudio.com/KS0367_keyestudio_ESP8266_WiFi_Board

title: How to create a wired ESP8266 range extender?

Answers: 1

body:
There's a project that calls itself a "wifi repeater" at

https://github.com/martin-ger/esp_wifi_repeater

It includes support for an ENC28J60 ethernet adapter connected via SPI.

It has some serious limitations.

First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.

Also, devices on the original network will not be able to originate connections to devices on the extended network.

But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.

Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.

Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.

I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.


body:
I am working on an art project that involves a garage door opener.  I am very new to Arduino, and electronics.  I have a starter kit with a ton of accessories.

The garage door opener has 2 screws (terminals?) designed to connect a button.  If I touch a wire between them, the opener will start.  I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.

I want to:

 1. press a button, and the Arduino connects the terminals on the opener, and then it starts
 2. button is then ignored (delayed) for a set amount of time (5 seconds for this example)
 3. after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

 - I can turn on an LED from a switch on the bread board, and use a `delay(5000)` to ignore any other button presses.  I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
 - In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT.  I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener.  I tested this a bit in code by reading the state of pin 6, and it appears to have worked.  However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff.  I just want to ignore a button press for 5 seconds after it has been pressed once.

I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener.  I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?

My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet.  I apologize in advance if I'm not thinking of something super-simple that would solve my problem.  I'm very new to this.

Thanks for your time!

Edited for spelling.  Elaborated on my attempts.  I'm going to read about what a relay is.

title: Garage door button with delay feature

Answers: 1

body:
I figure out a solution - I just needed to use a relay.

I didn't know what a relay was, and had a hard time figuring it out.  I've included some notes for anyone who finds this post in the future.

 - I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best.  Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
 - My relay looked different from most of the tutorials.  I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch.  Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

 - I connected my ~5 to one lead on the relay, and 5v to the other
 - The Common (middle) lead connects to one terminal on the garage door opener
 - The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

 - The button setup was just like all the other button tutorials
 - When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
 - I then run a `delay` for the set amount of time I want
 - All button presses are ignored until after the `delay` has finished

Now I can move on to the actual project.  Thanks!


body:
I am trying to modify on the menu code to be able to use a keypad shield and arduino for scrolling between lines. after uploading and trying the code the following has happened:
1- I can not scroll more than 2 lines.
2- If I press D, I can scroll to another 2 lines.
What is the problem in this code?

    include "String.h"
    include"AccelStepper.h"
    include "Keypad.h"
    include "U8glib.h"
    U8GLIB_ST7920_128X64_1X u8g(12, 11, 10, 13);

    //Keypad setup

    const byte ROWS = 4;

    const byte COLS = 4;

    char hexaKeys [ROWS][COLS] = {

    {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} };

    byte rowPins [ROWS] = {5, 4, 3, 2};

    byte colPins [COLS] = {9, 8, 7, 6};

    Keypad customKeypad = Keypad (makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    define KEY_NONE 0
    define KEY_PREV 1
    define KEY_NEXT 2
    define KEY_SELECT 3
    define KEY_BACK 4
    uint8_t keycode1 = KEY_NONE;

    uint8_t keycode2 = KEY_NONE;

    uint8_t keycode = KEY_NONE;

    void keymode(void){

    keycode2 = keycode1;

    char keypressed = customKeypad.getKey();

    if (keypressed != NO_KEY){

    switch (keypressed){

    case 'A':

    keycode1 = KEY_PREV;

    Serial.println("A");

    break;

    case'B':

    keycode1 = KEY_NEXT;

    Serial.println("B");

    break;

    case 'C':

    keycode1 = KEY_SELECT;

    Serial.println("C");

    break;

    case 'D':

    keycode1 = KEY_BACK;

    Serial.println("D");

    break;

    }

    if (keypressed != 'A' && keypressed != 'B' && keypressed !='C' && keypressed != 'D')

    keycode1 = KEY_NONE;

    }

    if (keycode2 == keycode1)

    keycode = keycode1;

    else

    keycode = KEY_NONE;

    }

    define MENU_ITEMS 4
    const char *menu_strings[MENU_ITEMS] = {"Start", "Hello", "Let's Go", "End"};

    uint8_t menu_current = 0;

    uint8_t menu_redraw = 0;

    uint8_t Last_key_code = KEY_NONE;

    void drawmenu(void){

    uint8_t i, h;

    u8g_uint_t w, d;

    u8g.setFont(u8g_font_6x13);

    u8g.setFontRefHeightText();

    u8g.setFontPosTop();

    h = u8g.getFontAscent()-u8g.getFontDescent();

    w = u8g.getWidth();

    for( i = 0; i < MENU_ITEMS; i++ ) {

    d = (w-u8g.getStrWidth(menu_strings[i]))/2;

    u8g.setDefaultForegroundColor();

    if ( i == menu_current ) {

    u8g.drawBox(0, ih+1, w, h);

    u8g.setDefaultBackgroundColor();

    } u8g.drawStr(d, ih, menu_strings[i]);

    } }

    void updatemenu(void){

    if (keycode != KEY_NONE && Last_key_code == keycode) {

    return; } Last_key_code = keycode;

    switch(keycode){

    case KEY_NEXT:

    menu_current ++;

    if (menu_current >= MENU_ITEMS)

    menu_current =0;

    menu_redraw = 1;

    break;

    case KEY_PREV:

    if (menu_current ==0)

    menu_current = MENU_ITEMS;

    menu_current --;

    menu_redraw = 1;

    break;

    } }

    void setup (){

    Serial.begin(9600);

    menu_redraw = 1;

    }

    void loop (){

    keymode();

    if (menu_redraw !=0) {

    u8g.firstPage();

    do{

    drawmenu();

    }while(u8g.nextPage());

    menu_redraw = 0;

    } updatemenu();

    }

title: Arduino menu coding problem by Keypad and 128*64 graphic LCD

Answers: 0


body:
I'm trying to re-use a piece of example code I found here:

https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/

And I only have 5 LEDs in my strip, so I changed the define NUM_LEDs to 5, but when compiling with that value, I get a compilation error. with the define at 6 it works tho, but the 5th LED wouldn't turn on. Here is my code:

    #include <FastLED.h>
    #define LED_PIN     7
    #define NUM_LEDS    6
    CRGB leds[NUM_LEDS];
    void setup() {
      FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

    }
    void loop() {

      leds[0] = CRGB(0, 10, 0);
      leds[1] = CRGB(10, 0, 0);
      leds[2] = CRGB(0, 10, 10);
      leds[3] = CRGB(10, 10, 0);
      leds[4] = CRGB(10, 10, 10);
      FastLED.show();
      delay(500);
      leds[0] = CRGB(0, 0, 0);
      leds[1] = CRGB(0, 0, 0);
      leds[2] = CRGB(0, 0, 0);
      leds[3] = CRGB(0, 0, 0);
      leds[4] = CRGB(0, 0, 0);
      FastLED.show();
      delay(500);

    }

So in the code, I've set the first LED to green, seccond one to red, third one to blue, 4th one to yellow, and the 5th one to white. As you can see in the picture they all light up correctly but the 5th one which stays blank, and I don't know why. I have tested this LED individually and it works perfectly well so it's not a hardware problem. I would encourage anyone who wants to test this code on 5 LEDs and let me know if it works for them, I'd be surprised it it did, but if you have a better solution for me, I would appreciate it.

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

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

title: 5th Led wont turn on (ws2812)

Answers: 0


body:
Can someone give me a solution to the following problem?
I have 1 IR remote, blynk app,some pushButtons and also 1 relay module.
(I set 1 pin of ATMega as input to be able to read what esp sends when I use the blynk app).
So basically what I want to do is this:
If I press btn1 from the IR Remote or PushBtn nr1, or I send 1 from blynk app
then relay 1 must turn on. For now that part works.
Anyway, what I want to do next is this:
If the relay is turned on (closed) I want to be able to turn it off using the same buttons (for which I have set a counter and I call that variable).
Now I can turn the relay off only if I use the same btn that previously I have used to turn it on. But I want to be able to turn it off the other way.
If I used the blynk app to turn it on then if I press the pushbtn second time - I want it to be off. Also if I don't press the pushbtn but I use the IR remote and press 1 2 times- the relay should be off.
```
if(cntbtn2 == 1 || cntPushbtn2 == 1)
      {
      digitalWrite(rel2,LOW);
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);

      if(cntbtn1 == 1 || cntPushbtn1 == 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.aprinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
          }

      else if(cntbtn1 != 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
          }

      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }

else if(cntbtn2 == 2)
    {
    if(cntbtn1 == 1 || cntPushbtn1 == 1)
        {
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.aprinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    else{
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    }

if(cntbtn2 == 1 && cntPushbtn2 == 2)
    {
    digitalWrite(rel2,HIGH);
    }

//ecran stanga
if(cntbtn1 == 1 || digitalRead(espPin) == 1 || cntPushbtn1 == 1)
    {
    digitalWrite(rel1,LOW);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.aprinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
    else
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }

   }

else if(cntbtn1 == 2)
    {
    digitalWrite(rel1,HIGH);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.stinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
        if(cntbtn2 != 1)
            {
            u8g.drawStr(73,23,"Dormitor");
            u8g.drawStr(75,60,"L.stinsa");
            u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
            }
        }
    else
        {
        digitalWrite(rel1,HIGH);
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
   }

```

title: Changing the light state

Answers: 1

body:
Split the logic and the buttons in separate parts and avoid code duplication.

First step is to determine what should control the relay state:

    // pseudo code follows
    if (pushButton.isPressed() || blinkApp.sentCommand() || conditionAlfa.isMet()) {
      // update condition is met, proceed to state change
      relayState = !relayState; // swap relay state
      updateRelay = true; // activate the part responsible for the change
    }

Once the new desired state is set, act on the relay and update the screen accordingly:

    // pseudo code again
    if (updateRelay == true) {
      updateRelay = false; // we are now going to update, don’t do it again if not necessary
      relay.setState(relayState); // update the relay, no matter what was the event source
      screen.drawGraphics(); // update the screen, no matter what was the event source
    }

If you split the two parts you start operating on logical conditions rather than on physical events, making your entire code cleaner and your task simpler.


body:
I need an clearity about external crystal oscilator. I got communication between esp32 and atmega8/88/328 processor, I use atmega wih internal oscillator and looks like it have problem with serial communication (some time it lose data, or replace it with nonsences).

So i have read that should use extercal crystal oscillator to achieve stable uart communication.

Question is that, what frequency to choose, and how that gonna effect uart, and atmega processor lifetime. I know if choose 16mhz processor gonna run faster, but assume it life time will decrease compated with 1mhz or 8mhz.
What about uart, which one of those frequences are best for it, or it make no difference?

title: atmega328: external crystal oscillator and uart

Answers: 1

body:
There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is **"Error"** column. **fosc** is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
 Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

[![enter image description here][1]][1]
[![enter image description here][2]][2]
or below:
[![enter image description here][3]][3]

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise.
 Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.

  [1]: https://i.stack.imgur.com/yJ3yg.png
  [2]: https://i.stack.imgur.com/y6oLu.png
  [3]: https://i.stack.imgur.com/NWOSR.png


body:
i am a beginner at python and I am average at Arduino and I had the idea of using both of them together for a project. I have been trying to make a **Arduino + Python** car which I can control with my computer. I have used Pyfirmata and the code seems perfect to me. When I run the code from CMD i have a weird bug/issue.
I have uploaded Standard Firmata to the arduino UNO. I get **no errors while uploading or running** its just that its output is messed up.

Here's the Python Code:

    from pyfirmata import Arduino, util
    import time

    board = Arduino("COM3")

    MotorLeft = board.get_pin('d:10:o') # Assigning output to PIN
    MotorRight = board.get_pin('d:11:o') # Assisging output to PIN

    play = True

    while play:
        control = input(
            print("Enter W, A or D to move forwards, left or right. Enter 0 to exit"))

        if control != 0:
            if control == "W" or "w":
                MotorRight.write(1)
                MotorLeft.write(1)
                time.sleep(1)
                MotorRight.write(0)
                MotorLeft.write(0)

            if control == "A" or "a":
                MotorLeft.write(1)
                time.sleep(1)
                MotorLeft.write(0)

            if control == "D" or "d":
                MotorRight.write(1)
                time.sleep(1)
                MotorRight.write(0)

            else:
                print("Invalid Commmand")

        else:
            print("Exited Succesfully")

        play = True

Currently I have not built the car, I am using a pair of LEDs to do what the motors function and to test out the code.

Heres the **CMD response**:
[![][1]][1]

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

Here is the link for the output video. I entered "W" which **should ideally turn on both of the LEDs** however, both of them turn on then off and then turn on off one by one.

**https://youtu.be/DjUkkpzF0so**

title: The arduino can't seem to output correctly

Answers: 1

body:
I cannot check it, but I guess you have to change the or commands like:

    if control == "W" or "w":

Change to

    if ((control == 'W') or (control == 'w'))

And similar for the other if statements.

Also, you can do not need to check for control == 0, since it will not be a character otherwise.

Besides that, the `elif` (else if) construct is normally used in Python, so instead of:

    if control != 0:
        if control == "W" or "w":
            MotorRight.write(1)
            MotorLeft.write(1)
            time.sleep(1)
            MotorRight.write(0)
            MotorLeft.write(0)

        if control == "A" or "a":
            MotorLeft.write(1)
            time.sleep(1)
            MotorLeft.write(0)

        if control == "D" or "d":
            MotorRight.write(1)
            time.sleep(1)
            MotorRight.write(0)

        else:
            print("Invalid Commmand")

You can write:

    if ((control == 'W') or (control == 'w')):
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    elif ((control == 'A') or (control == 'a')):
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    elif ((control == 'D') or (control == 'd')):
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

Also, you can combine the `or` in a list (but I cannot check it, no python compiler at hand), e.g.

    if (control in ['W', 'w']):


body:
I have an arduino project that reads a config file from SD and then receives data on a serial port that is specifed in the config file.

I therefore need to instantiate the Serial (Serial0), Serial1,..2,3, etc based on dynamic data.

I am using a mega2560 with 4x HardwareSerial. Serial (also Serial0) is the USB. Serial 1, 2, 3 are on specific hardware pins.

I started with code something like:

    uint8_t InitPort(uint8_t port) {
        switch (port) {
            case 0:
                if(Serial.begin(9600) return 1;
                break;
            case 1:
                if(Serial1.begin(9600) return 1;
                break;

            ... etc...

            default:
                return 0;
    }

However, this instantiates all Serialx objects (using 157 bytes of data/bss each).

I've since written a class wrapper that takes a referece to the desired serial object as an initialising paramter, but this just pushes the problem up-stack to the calling code.

Is there a way that a Serial object can be instanitated dynamically with a port number passed in, to only end up with one instance connected to the desired port?

title: Dynamic Serial port selection and use without instantiating all Serialx objects

Answers: 1

body:
You can create an instance of `HardwareSerial` referencing a hardware
port that depends on a function parameter, as in

<!-- language-all: lang-c++ -->

    void initPort(uint8_t port) {
        switch (port) {
            case 0: {
                HardwareSerial serial(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
                serial.begin(9600);
                break;
            }
            case 1:
                // etc...
        }
    }

However, since only a local variable can be created in this manner, it
is not of much use. Ideally, you would want to have a _global_ variable
for the serial port, and initialize it in `initPort()`, as

    HardwareSerial serial;

    void initPort(uint8_t port) {
        switch (port) {
            case 0:
                // Invoke fictional init() method.
                serial.init(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
                break;
            case 1:
                // etc...
        }
        serial.begin(9600);
    }

Alas, this is not possible, as the `HardwareSerial` class has no default
constructor. This means that binding the object to the hardware port can
only be done when it is constructed.

Short of modifying the Arduino core (adding a default constructor and an
`init()` method), the only option I can see is to have the global
variable be a _pointer_. Then, in `initPort()` the object is
instantiated while initializing the pointer. I tried this approach in
the example program below. There was a slight technical difficulty
though: since the object files from the core defining `Serial`,
`Serail1`, etc. will hopefully _not_ be linked to the program, the
interrupt service routines defined therein must be also defined in the
sketch itself. And since an ISR cannot be bound to an interrupt at run
time, the ISRs have to be defined for _all_ the ports, even though only
one ends up being actually used.

Here is my test program:

    #include <HardwareSerial_private.h>

    HardwareSerial *serial;

    ISR(USART0_RX_vect) { serial->_rx_complete_irq(); }
    ISR(USART1_RX_vect, ISR_ALIASOF(USART0_RX_vect));
    ISR(USART2_RX_vect, ISR_ALIASOF(USART0_RX_vect));
    ISR(USART3_RX_vect, ISR_ALIASOF(USART0_RX_vect));
    ISR(USART0_UDRE_vect) { serial->_tx_udr_empty_irq(); }
    ISR(USART1_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
    ISR(USART2_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
    ISR(USART3_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));

    void initPort(uint8_t port)
    {
        switch (port) {
            case 0:
                serial = new HardwareSerial(&UBRR0H, &UBRR0L,
                             &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
                break;
            case 1:
                serial = new HardwareSerial(&UBRR1H, &UBRR1L,
                             &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
                break;
            case 2:
                serial = new HardwareSerial(&UBRR2H, &UBRR2L,
                             &UCSR2A, &UCSR2B, &UCSR2C, &UDR2);
                break;
            case 3:
                serial = new HardwareSerial(&UBRR3H, &UBRR3L,
                             &UCSR3A, &UCSR3B, &UCSR3C, &UDR3);
                break;
        }
        serial->begin(9600);
    }

    void setup() {
        initPort(0);
        serial->println("Hello, World!");
    }

    void loop(){}

It should be noted that the ISRs do not take that mush flash space.
There are actually only two of them, even though each is referenced four
times in the interrupt vector table.