message:
Having an issue accessing values from a pointer

# 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

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.


sender: user

message:
Send serial data at custom voltage using PWM

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

sender: assistant

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.


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

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.

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.


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

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.)

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.


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

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.

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.


message:
Controller freezes

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.

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


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

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.

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.


message:
can't return float value from function

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;
      }
    }

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");
      }
    }


message:
Constant ADC sampling rate on ESP8266 or ESP32

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.

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.


message:
How to automatically reset the NRF24L01 module

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

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


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

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++;}

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;


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

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

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.


message:
How to create a wired ESP8266 range extender?

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

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.


message:
Garage door button with delay feature

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.

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!


message:
Changing the light state

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);
        }
   }

```

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.


message:
atmega328: external crystal oscillator and uart

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?

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


message:
The arduino can't seem to output correctly

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**

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']):


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

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?

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.


message:
Problems with controlling LED with soil moisture sensor

I'm a beginner at Arduino.

I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.

What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.

The moisture detection or the value mapping works perfectly fine.

Does the issue lie on my code or my LED wiring?
[![enter image description here][1]][1]

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

Code:
<!-- language-all: lang-cpp -->

    int mostMoist = 180;
    int leastMoist = 600;
    int percent;
    int raw;
    const int threshold = 50;

    void setup() {
      Serial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);

      if (percent < 0){
        percent = 0;
      }

      if (percent < threshold){
        digitalWrite(LED_BUILTIN,HIGH);
      } else {
        digitalWrite(LED_BUILTIN,LOW);
      }

      Serial.println(percent);
      delay(2);
    }

body:
A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

```
if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}
```


message:
How to repeat an IF statement

My LCD info is called from an IF statement but since it's clock and temperature info i don't want to just show the information but update the information constantly in real time.
i don't want to use (while) loop or any other "code-blocking".

Here's the whole code:

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

    #define ONE_WIRE_BUS 2
    int Heater= 3;
    int Switch1= 4;

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

    // Push button

    boolean oldSwitchState = LOW;
    boolean newSwitchState = LOW;
    boolean lcdScroll = LOW;
    boolean lcdBacklight = LOW;
    boolean lcdWelcome = LOW;

    unsigned long previousMillis = 0;
    const long BacklightTime = 10000;

    void setup() {
      Serial.begin(115200);
      pinMode(Heater, OUTPUT);
      pinMode(Switch1, INPUT);
      lcd.begin();
      rtc.begin();
    }
    void loop() {
      float testTemp = sensors.getTempCByIndex(0);
      sensors.requestTemperatures();
      t = rtc.getTime();
      if(lcdWelcome == LOW){
          lcd.setCursor(0,0);
          lcd.print("Welcome, Admin!");
          lcd.setCursor(0,1);
          lcd.print("press Start");
      }

      // LCD
      newSwitchState = digitalRead(Switch1);
        if (millis() - previousMillis >= BacklightTime) {
          lcd.noBacklight();
          lcdBacklight = LOW;
        }
        else if ( lcdBacklight == LOW ){
          lcd.backlight();
          lcdBacklight = HIGH;
        }
        if ( newSwitchState != oldSwitchState ) {
           if ( newSwitchState == HIGH ){
           previousMillis = millis();
           lcdWelcome = HIGH;
           lcd.clear();
          if ( lcdScroll == LOW ){
            lcd.setCursor(0,0);
            lcd.print(testTemp);
            lcd.print("   ");
            lcd.print(rtc.getTimeStr());
            lcdScroll = HIGH;
          }
          else{
            lcd.setCursor(0,0);
            lcd.print(rtc.getDOWStr());
            lcd.print("   ");
            lcd.print(rtc.getDateStr());
            lcdScroll = LOW;
          }
           }
           oldSwitchState = newSwitchState;
        }
    }

How can i update the functions inside the `if(lcdScroll == LOW){}` and `else{}` statements constantly to show on display?

body:
Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag `bool a_flag` in this `if(lcdScroll==LOW)` clause and checking `if(a_flag)` in the highest scope of the `loop()` section. This is where you `print("test");`.

In respect to your code this will look like:

    bool a_flag=false;
    void loop() {
      // some irrelevant stuff
      if ( newSwitchState != oldSwitchState) {
        // some stuff
        if ( lcdScroll == LOW ){
          // stuff you would handle here
          a_flag=true;
        }
        else {
          // stuff you would handle here
          a_flag=false;
        }
      }
      if (a_flag) Serial.println("lcdScroll is LOW");
      else Serial.println("lcdScroll is HIGH");
    }

Beside this general solution you could simply do the following in your specific case:

    loop(){

      // your actual code

      if (lcdScroll) Serial.println("lcdScroll is LOW");
      else Serial.println("lcdScroll is HIGH");
    }


message:
How to upgrade ESP8266 NodeMCU SDK from V2.5.2 to V3?

ESP.getFullVersion() output:

    SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020Connecting to DO_231455

I upload sketches from the Arduino IDE. How do I update the SDK?

I have the flasher tool but I can't seem to find documentation on what to do from this point:
[![enter image description here][1]][1]

I've downloaded the [assets][2] from Github

  [1]: https://i.stack.imgur.com/E4KFS.png
  [2]: https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v3.0

body:
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Presumably you've already followed the instructions to put the URL for the ESP8266 Arduino Core in the preferences for the Arduino IDE.

Once that's there, to update the ESP8266 Arduino SDK, go to the Tools menu, select Board, then select the Boards manager (the first item in the menu).

That will bring up a dialog listing all the board families your Arduino IDE knows how to build for. You can limit the list to those with updates available by selecting "Updatable" in the "Type" field. Or just scroll down or search till you find the ESP8266 entry. Click it and if there's an update available you'll see an "Update" button appear on it. You can also reinstall older versions by choosing a version and clicking the "Install" button.

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

However, there is no version 3 as yet. At the time that I'm writing this, 2.5.2 is the most recent release of the SDK.

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


body:
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Choose it in Tools menu. It is available only if you select "Generic ESP8266 module".

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

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


message:
Servo Motor in function

I have a project with 9 servo, I want to make a function to control each separate. Only that he is not accepting the servo as a parameter.
Can someone tell me if it is possible to pass the servant as a parameter, and how? Thank you!!
Example:

    Servo s1,s2,s3;

    void toMove(Servo obj,int inPosition, int forPosition){
    var i = 0;
      for(i = inPosition; i<forPosition; i++){
       obj.write(i);
      }
    }

    void loop(){
      if(true){
         toMove(s1,0,180);
         toMove(s2,0,180);
      }
    }

body:
Yes, it is possible, and you've done it *almost* right. I made a minor correction in the `toMove()` function ("int" instead of "var"), and supplied the `setup()` function which you didn't show. It compiles without error. I didn't check it for correct operation as it looks like you had reduced your code to the minimum example necessary to demonstrate your question -- and thanks for that! Here is what I compiled:

    #include <Servo.h>

    #define SERVO1  9
    #define SERVO2  10

    /*****< External and Global Declarations >*****/
    Servo s1, s2;
    void toMove(Servo obj, int inPosition, int forPosition);

    /*****< Local Function Prototypes >*****/

    void toMove(Servo obj,int inPosition, int forPosition){
    int i = 0;
      for(i = inPosition; i<forPosition; i++){
        obj.write(i);
      }
    }

    void setup()
    {
     s1.attach(SERVO1);
     s2.attach(SERVO2);
    }

    void loop() {
       toMove(s1, 0, 180);
       toMove(s2, 0, 90);
    }


body:
You have not use attach() function:

     s1.attach(pin_1);
     s2.attach(pin_2);

See [how to use servo motor][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-servo-motor


message:
Help combining digital and analog code in arduino programming

So I'm making a device that does 3 things,

1. Measures frequency of an audio signal through a microphone
2. Checks whether there is a weight placed on a pressure pad (my pressure sensor works through the resistance of the material changing when a weight is placed on it)
3. Measure ambient room temperature

I have coded each individual section and tested them individually to find them work great, here are the sketches.

Frequency sketch :

    // runs every time thru the loop
      setInputState();

      // count every transision HIGH<->LOW
      if (inputState != lastInputState) {
        count++;
        lastInputState = inputState;
      }

      if (millis() - previousCountMillis >= countMillis) {
        previousCountMillis += countMillis;

        // show Hz on Serial too if available
        Serial.print(count);
        Serial.println(" Hz");
        ledtest = count;
        // reset to zero for the next half second's sample
        count = 0L;
      }
      if (ledtest >= 400 && ledtest <= 850){
        digitalWrite(A2, HIGH);
      }
      else if (ledtest < 400 || ledtest > 850){
        digitalWrite(A2, LOW);
      }
    }

Here is the pressure sensor sketch

    int Vin = 5;
    float Vout = 0;
    float raw1 = 0;

    int R1 = 770;

    int R2old1 = 0;

    int R2new1 = 0;

    int R2avg1 = 0;

    int pressurelog = 0;

    void setup() {
      pinMode(A0, INPUT);             //Receive pressure voltage
      pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
    }

    void loop() {
      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2old1 = Vout*R1/(Vin-Vout);

      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2new1 = Vout*R1/(Vin-Vout);

      R2avg1 = (R2new1+R2old1)/2;

      Serial.print("Resistance: ");
      Serial.println(R2avg1);

      if (R2avg1 >= 1000){
        digitalWrite(A1, LOW);
        pressurelog = 0;
      }
      else if (R2avg1 <= 1000){
        digitalWrite(A1, HIGH);
        pressurelog = 1;
      }
    }

here is the temperature code

    float raw = 0;
    float tempC = 0;
    float tempF = 0;

    void setup() {
      pinMode(A5, INPUT);
      pinMode(A1, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
     raw = analogRead(A5) * 0.004882814;
     tempC = (raw - 0.5) * 100.0;
     tempF = (180.0/100.0)*tempC + 32.0;

     Serial.print("temp: ");
     Serial.println(tempF);
     delay(1000);
    }

I coupled the "void loop" of all three and defined everything and ran the code to give a peculiar output. It does the temp and pressure reporting just fine but seems to constantly skip the frequency measurement. It seems to like doing the pressure and temperature measurement like 50 times then do an audio measurement which doesn't make sense as it should do it sequentially.

I TRIED:

1. adding a delay between the frequency measurement and the other two. This didn't work as now the audio measurement work, as it relies on the millis () function
2. adding the 3 components in 3 different functions and calling them sequentially. This results in the exact same stupid output.

Does anyone have an idea or solution?

    Combined code:

    int Vin = 5;
    float Vout = 0;
    float raw1 = 0;

    int R1 = 770;

    int R2old1 = 0;

    int R2new1 = 0;

    int R2avg1 = 0;

    int pressurelog = 0;

    const byte inputPin = 2;

    boolean inputState = false;
    boolean lastInputState = false;
    long count = 0L;
    int ledtest = 0L;

    unsigned long previousCountMillis = millis();
    const long countMillis = 500L;

    void setInputState() {
      inputState = digitalRead(inputPin);
    }

    int crylog = 0;

    float raw = 0;
    float tempC = 0;
    float tempF = 0;

    int templog = 0;

    void setup() {
      pinMode(inputPin, INPUT);       //Receive microphone data
      pinMode(A0, INPUT);             //Receive pressure voltage
      pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
      pinMode(A2, OUTPUT);            //Blue led, FREQUENCY/CRYING
      pinMode(A3, OUTPUT);            //Green led, TEMPERATURE
      pinMode(A4, OUTPUT);            //Red led, MAX WARNING
      Serial.begin(115200);
    }

    void loop() {
      Serial.println("HI");
      Cryometer();
      delay(2);
      Serial.println("YO");
      Pressure();
      Temperature();

      // WARNING SETUP
      if (pressurelog == 1 && templog == 1){
        digitalWrite(A4, HIGH);
      }
      else {
        digitalWrite(A4, LOW);
      }
    }

    void Pressure() {
      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2old1 = Vout*R1/(Vin-Vout);

      raw1 = analogRead(A0);
      Vout = raw1*5/1024;
      R2new1 = Vout*R1/(Vin-Vout);

      R2avg1 = (R2new1+R2old1)/2;

      Serial.print("Resistance: ");
      Serial.println(R2avg1);

      if (R2avg1 >= 1000){
        digitalWrite(A1, LOW);
        pressurelog = 0;
      }
      else if (R2avg1 <= 1000){
        digitalWrite(A1, HIGH);
        pressurelog = 1;
      }
    }

    void Cryometer(){
      // runs every time thru the loop
      setInputState();

      // count every transision HIGH<->LOW
      if (inputState != lastInputState) {
        count++;
        lastInputState = inputState;
      }

      if (millis() - previousCountMillis >= countMillis) {
        previousCountMillis += countMillis;

        // show Hz on Serial too if available
        Serial.print("Frequency: ");
        Serial.print(count);
        Serial.println(" Hz");
        ledtest = count;
        // reset to zero for the next half second's sample
        count = 0L;
      }
      if (ledtest >= 400 && ledtest <= 850){
        digitalWrite(A2, HIGH);
        crylog = 1;
      }
      else if (ledtest < 400 || ledtest > 850){
        digitalWrite(A2, LOW);
        crylog = 0;
      }
    }

    void Temperature() {
       raw = analogRead(A5) * 0.004882814;
       tempC = (raw - 0.5) * 100.0;
       tempF = (180.0/100.0)*tempC + 32.0;

       Serial.print("Temperature (F): ");
       Serial.println(tempF);
       Serial.println();

      if (tempF >= 75 && ledtest <= 50){
        digitalWrite(A3, HIGH);
        templog = 1;
      }
      else if (ledtest < 50 || ledtest > 75){
        digitalWrite(A3, LOW);
        templog = 0;
      }
    }

body:
Your approach is globally sound. However, the code that measures the
input frequency is very time sensitive. Thus, you have to make sure this
piece of code is never delayed by anything else. This means that
everything in your sketch should be fast and _non-blocking_.

I see a few instances of blocking behaviour you should get rid of: the
call to `delay()` and the serial prints. The first is particularly
useless, so just remove it. Printing to the serial port is fine as long
as you do not try to print _too much_. If you try to print at every loop
iteration, you end up filling the output buffer. From there on every
print becomes a blocking call: the serial library has to wait for the
port to send out the data, until there is enough room in the buffer for
what you want to send. The solution is to throttle down the output rate
by only printing once in a while. You have done this brilliantly in the
frequency-meter code:

    if (millis() - previousCountMillis >= countMillis) {
      previousCountMillis += countMillis;
      Serial.print("Frequency: ");
      Serial.print(count);
      Serial.println(" Hz");
      // ...
    }

Now you just have to apply the same technique to _every_ instance of
`Serial.print()` and `Serial.println()`. Well, maybe the "HI" "YO" could
just be removed instead...

Once you remove these blocking behaviors from your sketch, it will
probably run fast enough for the frequency counting to perform
correctly. There is still something you may want to optimize though: the
computations in `Pressure()` are horribly inefficient, especially
considering that you have an 8-bit CPU with no hardware floating point
support. If you need to average, I suggest you average the analog
readings rather than computed resistances. Also note that computing the
voltage at the analog pin is completely useless:

    void Pressure() {
        int raw = analogRead(A0) + analogRead(A0);
        float R = (float) R1 * raw / (2048 - raw);
        // ...
    }

You may even replace `float` by `long` if you don't need a resolution
better than 1 Ω.


message:
USing arrays, binary data and bitRead

This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:

    @code1=('10101010', '01010101');
    $bit=$code1[0][0] (..through to..) code1[0][7]
    $bit=$code1[1][0] ... code1[1][7]

So this is my Arduino code. Welcome to suggestions.

    int pinArray[]={2,3,4,5,6,7,8,9};
    int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
    int count=0;
    int split=0; // Counter for the bit loop
    int led; // Store bit data
    byte x;  // Used to store the binary data in code1

    void setup(){
     for (count=0; count<8; count++){
     pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
     ]
    }

    void loop(){
     for (count=0; count<6; count++){
     x=code1[count];
     ledDisplay(x);
     }
    }

    void ledDisplay(){
     for (split=7; split>=0; split--){
     led=bitRead(x,split);
      if (led == 1){
      digitalWrite(split+2,HIGH);
      }
      else{
      digitalWrite(split+2,LOW);
      }
     }
    }

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value.  Does this need to be enclosed in brackets,ie (split+2) ?

body:
There are only two errors I can spot in your program:

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

1. A block of code should be delimited by curly braces:

        for (count=0; count<8; count++){
            pinMode(pinArray[count],OUTPUT);
        }  // ← ‘}’ instead of ‘]’

2. If a function expects to be passed arguments, these should be
   declared as parameters in the function prototype:

        void ledDisplay(byte x){  // ← mind the “byte x”
            // ...
        }

Other than that, here a few suggestions to make the code look nicer, and
hopefully more maintainable:

* indent consistently
* use `const` to qualify constants
* use named constants instead of magic numbers
* keep variables local if possible
* note that an int that is either 0 or 1 is equivalent to a boolean
* use `pinArray[]` for accessing the pins

Applying those suggestions, I get the following:

    const int PIN_COUNT = 8;
    const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
    const int CODE_COUNT = 6;
    const int code1[CODE_COUNT] = {
        B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
    };

    void setup() {
        for (int count = 0; count < PIN_COUNT; count++) {
            pinMode(pinArray[count], OUTPUT);
        }
    }

    void loop() {
        for (int count = 0; count < CODE_COUNT; count++) {
            ledDisplay(code1[count]);
        }
    }

    void ledDisplay(byte x) {
        for (int split = 7; split >= 0; split--) {
            if (bitRead(x, split)) {
                digitalWrite(pinArray[split], HIGH);
            } else {
                digitalWrite(pinArray[split], LOW);
            }
        }
    }


message:
Arduino controlled LCD 16x2 is very very dim

I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.

Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.

FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

[![My LCD][1]][1]

[![One from google][2]][2]

  [1]: https://i.stack.imgur.com/Brlt5.jpg
  [2]: https://i.stack.imgur.com/19TyJ.jpg

body:
I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).

It will light up when the backlight is correctly connected, which is impossible to tell from your photo.


message:
Serial communication questions

I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

Thank you

body:
> 1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

The Arduino has a 64 byte (software) buffer.  You will get the numbers in sequence up until that buffer overflows. Then it's not easy to predict what the results will be.

Probably something like:

 121212121[...]2121212121212111111111111111

> 2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

If there is nothing in the buffer the read function returns -1.  That can be mapped (IIRC) into ASCII (depending on your software) as ÿ so you would get:

    1ÿ1ÿ1ÿ1ÿ1ÿ...

You should read [my tutorial on reading serial on the Arduino](https://majenko.co.uk/blog/reading-serial-arduino).


message:
Arduino USB host + RS232

I'd like to get a word of advice regarding the subject. Basically there's a COM port based device which I need to connect to an Android tablet via USB. The tablet will be exchanging data packages with the COM device, but a) Arduino may need to do same transformation of the packages b) the tablet should not leverage OTG feature and shouldn't be a master itself.

So, my questions are

1) Which Arduino board is the best fit?
2) Is it an option to use Chinese boards for the sake of cost optimization?
3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

Apology for this quite a noob question but that's exactly who I am for Arduino platform. Appreciate any answers.

body:
> 1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.

Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is *not* used by the USB communication.

Then you need to convert the UART into RS232 using (for example) a MAX232 board.


message:
Public IP for Arduino with Ethernet shield and Arduino Uno

I'm new Arduino and I would like you to help me. I would like to have a public IP so that anyone can get access to it, not only from domestic domain. What could I do?. I'm using Arduino Uno, Arduino Ethernet Shield w5500 and a RTC.
My code:

    #include <SPI.h>
    #include <Ethernet.h>
    #include "RTClib.h"
    #include <EEPROM.h>

    #define time 1
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    IPAddress ip(192, 168, 0, 177);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);
    //----------------------------------------------------------------------------------------------------------------
     int i=0;
    String hora="";
    String readString;

    RTC_DS1307 RTC;

    void setup() {

      pinMode(2,OUTPUT);
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
    RTC.begin(); // Inicia la comunicaci¢n con el RTC

    RTC.adjust(DateTime(__DATE__, __TIME__)); // Establece la fecha y hora (Comentar una vez establecida la hora)

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Sistemas Digitales");

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);

      // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield no se encontro.  No se puede correr el programa sin el hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("El cable Ethernet no esta onectado.");
      }

      // start the server
      server.begin();
      Serial.print("El servidor esta en: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients

    delay(1000);
    DateTime now = RTC.now(); // Obtiene la fecha y hora del RTC

      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
    //---------------------------------------------------------------------------------------------------------------------------------
            char c = client.read();

    if(i==11 || i==12 || i==16 || i==17){
     if(i==16){
      hora +=':';
     }
      hora += c;
    }

            if(readString.length()< 100){
              readString += c;
            }
            i++;
            //Este escribe el texto en pantalla letra por letra
            Serial.write(c);

            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n') {
                Serial.println("acabo lectura");

                Serial.println(hora);
                 Serial.println(readString);

    client.println("HTTP/1.1 200 OK"); // Enviar una respuesta tipica
                 client.println("Content-Type: text/html");
                 client.println("Connection: close");
                 client.println("Refresh: 10");
               client.println();
               client.println("<!DOCTYPE HTML>");
              client.println(" ");
              client.println("");
              client.println("<meta charset='UTF-8'><title>Sistemas Digitales</title>");
              client.println("");
              client.println("
");
    client.print("
Fecha y hora del servidor:");
    client.print(now.day(), DEC);
    client.print('/');
    client.print(now.month(), DEC);
    client.print('/');
    client.print(now.year(), DEC);
    client.print(' ');
    client.print(' ');
    int horini;
    horini=now.hour();
    String horartc = "0";
    if(horini<10){
      horartc += horini;
    }else{
    horartc= String(horini);
    }
    client.print(horartc);
    client.print(':');
    int minuto;
    minuto=now.minute();
    String mainut;
    if(minuto<10){
      mainut='0'+ String(minuto);
    }else{
    mainut= String(minuto);
    }
    client.print(mainut);
    client.println("
");
    client.println("<form method='get'>");
    client.println("

¿A que horas le quiere dar de comer al chucho?

");
    client.println("<input type='time' name='hora'>");
    client.println("

que dias lo quiere alimentar?

");
    //dias en checkbox
    //client.println("<input type='checkbox' name='cbox1' value='?LunesOn'>Lunes
<input type='checkbox' name='cbox2' value='?MartesOn'>Martes
<input type='checkbox' name='cbox3' value='?MiercolesOn'>Miercoles
<input type='checkbox' name='cbox4' value='?JuevesOn'>Jueves
<input type='checkbox' name='cbox5' value='?ViernesOn'>Viernes
<input type='checkbox' name='cbox6' value='?SabadoOn'>Sabado
<input type='checkbox' name='cbox7' value='?DomingoOn'>Domingo
");
    client.println("<input type='submit' value='Enviar' id='enviar'> ");
    client.println("</form>");
    if (readString.length() >0) {
    Serial.println("hora del rtc");
    String horiux = horartc +':'+ mainut;
    Serial.println(horiux);
    EEPROM.put(0, hora);

    if(EEPROM.get( 0, hora ) == horiux){
    digitalWrite(2, HIGH);
    delay(10000);
    digitalWrite(2, LOW);
    delay(60000);
    }
    readString="";
    i=0;
    hora="";

              client.println("");
              client.println("");

              delay(1);
        // close the connection:
        client.stop();

            }

          }
        }

      }

      }
    }

There it is  a part of the code:

    IPAddress ip(192, 168, 0, 177);

I would like to make that IPto be public domain so you can get access anywhere instead of neededing to be in the same ethernet connection.

Any help would be wonderful, thanks for your time.

body:
There is a discussion about the same topic [in Arduino's Forum here](https://forum.arduino.cc/index.php?topic=333328.0). The most valuable comment was this:

> To get an internet static IP address, contact your ISP. You will probably have to pay extra for that. Most people use a dynamic IP service such as www.noip.com to forward traffic to your current internet IP address. You put your dynamic ip address url in your web page so the browser request get routed properly.

I assume (by the address) that you want to do something like this:

>The NAT device might have a port forwarding feature.
You can use that.
Assume the WAN ip is 198.51.100.1 and the server's ip is 10.1.1.1, the server is listening on port 80.
So the port forwarding configuration will be something like :
198.51.100.1 80 ---> 10.1.1.1 80
From the outside you connect to the public IP - 198.51.100.1 80
When the NAT device receives packet, it forwards it to 10.1.1.1.
**more info** [here](https://www.quora.com/How-to-connect-to-a-server-behind-NAT)

This is direct copy from source. So in your case WAN IP is the static IP (or another else) that is visible about you outside your network and the private one is that 192.168.0.177 which you used. Like stated in first yellow box, you can use dynamic ip service, too.


message:
Using use the STM32F103C8T6 board with the Arduino

last two days I am trying to program my blue pill with Arduino IDE, helplessly...
Actually, I managed to install simple blink program, but after that, all other attempts ended up with:

> Failed to init device.
stm32flash Arduino_STM32_0.9

> http://github.com/rogerclarkmelbourne/arduino_stm32

> Using Parser : Raw BINARY
Interface serial_posix: 115200 8E1

> An error occurred while uploading the sketch

I crawled internet but no help so far... I followed simply tutorial:
https://www.youtube.com/watch?v=K-jYSysmw9w just as this https://github.com/rogerclarkmelbourne/Arduino_STM32/wiki/Installation, and as I said, first time was problem but finally successfully upload it. However, after that when I wanted some real working program to install failed.
All mappings ftdi -> stm32 are correct, jumper booto is set to 1 mode, for programming, I have required files within /etc/udev/rules.d, stm32 library folder in sketch folder, and yet the error above is happening for a last 20 hours... (I am using Ubuntu 16.04)
Please, if anyone point me what is wrong (why first time worked and second wont), or to give me precise steps to perform in order to work, I appreciate.

EDIT: Blinking program works just fine when I move jumper to 0, and supply power via usb.

body:
thanx for help... It turns out that I have been sold crappy additional pins to plugin into breadboard. Even STM32 blink, turns out that one of the tx/rx has no contact with board (probably for microns).
However, firmed them altogether without breadboard, and it works...I spent 15 hours with this issue...


message:
Water pump controlled by soil moisture sensor

I'm just learning to code in Arduino.

The purpose is that first the sensor measures the moist level (I mapped the reading values from 0 to 100). If the value is less than threshold 70, then it will turn on a water pump. As soon as the value goes beyond 70, the pump stops pumping water.

The problem is that even when the value is less than 70, the pump doesn't work.

I tried replacing the pump with a LED, it turns on a the right moment. I tested the pump itself, and it also works perfectly.
<!-- language-all: lang-cpp -->

    //for mapping values
    int mostMoist = 100;
    int leastMoist = 600;
    int percent;

    //direct value from sensor
    int raw;

    //threshold for minimum percentage to turn on pump
    const int threshold = 70;

    //initial state of water pump
    bool dosomething = false;

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop() {
      //if it's not pumping water:
      while (dosomething == false){
      //check sensor value, map out of 100, and display on monitor
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);
      if (percent < 0){
        percent = 0;
      }
      Serial.println(percent);
      Serial.println("dosomething is set to false");

      //check if percentage moist is less than threshold. if so, set dosomething true, orelse, loop dosomething false
      if (percent<threshold){
        dosomething = true;
      } else{
        dosomething = false;
      }
      delay(2);
      }

      //if it's pumping water:
      while (dosomething==true){
      //check sensor value, map out of 100, and display on monitor
      raw = analogRead(A0);
      percent = map(raw,leastMoist,mostMoist,0,100);
      if (percent < 0){
        percent = 0;
      }
      //turn on pump
      digitalWrite(13,HIGH);
      Serial.println("dosomething is set to true");
      //check if percent moist is less than threshold value, if so, loop dosomething true, orelse, set dosomething false
        if (percent<threshold){
        dosomething = true;
      } else{
        dosomething = false;
      }
        Serial.println(percent);
      delay(2);
      }

    }

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

[![enter image description here][2]][2]

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

  [1]: https://i.stack.imgur.com/Yc6Qy.jpg
  [2]: https://i.stack.imgur.com/5yBr0.jpg
  [3]: https://i.stack.imgur.com/GVhYC.jpg

body:
I don't see a second power-supply in your photo. If you're trying to run the pump directly from an Arduino pin, it is highly likely that the pump needs way more current than the pin can supply.

It may be possible to power the motor from the USB but 1) the Uno board doesn't make that readily available, 2) it puts your PC at some risk (of back-EMF or of over-drawing the port's capability. But the ideal would be a separate power supply (don't forget to connect that supply's ground to the Uno's ground).

Also, if you tested the pump while dry it may have been able to run, yet with water in it, have been unable pull enough starting current to get going.


body:
To control the pump you will need either a transistor or a relay board to handle the current. The arduinos pins can only drive 20 mA which is not enough for most pumps, even very small ones.

If the pump can run on 5 V and with <400 mA a transistor (FET) may suffice an power could come from VCC or so. Otherwise an extra supply with a relay is one simple solution.

You [could start here](https://arduinogetstarted.com/tutorials/arduino-controls-pump) for instance.

Look for tutorials, there are so many out there to be found with search engine, it's worth :)