message:
Red LED not turning off on Adafruit Circuit Playground Classic

When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch `digitalWrite`ing pin 13 to high and low repeatedly works fine. The problem is when I try to use `CircuitPlayground.redLED(false)`. That has no effect, and the Circuit Playground specific `Hello_Blink` example doesn't work at all. The LED is just constantly on no matter what I do.

I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.

Not sure what else could be causing this.

This is the `Blink` sketch that's working:
<!-- language-all: lang-cpp -->

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

And this is the `Hello_Blink` sketch that is not working (LED remains on permanently):

    #include <Adafruit_CircuitPlayground.h>

    void setup() {
      CircuitPlayground.begin();
    }

    void loop() {
      CircuitPlayground.redLED(HIGH);
      delay(500);
      CircuitPlayground.redLED(LOW);
      delay(500);
    }

Changing `HIGH` and `LOW` to `true` and `false` does nothing.

I also have noticed two other strange things. The speaker does an audible click when the board resets when using the `Hello_Blink` sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines

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

to the `setup()` of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.

I am using [this library][1] with a atmega32u4.

  [1]: http://github.com/adafruit/Adafruit_CircuitPlayground

body:
This appears to be a bug in the Circuit Playground library. An issue was opened here.

https://github.com/adafruit/Adafruit_CircuitPlayground/issues/40

Edit: This indeed was a bug, it is now fixed in the library version 1.8.4.


sender: user

message:
Septic tank project

We are to make a project.We have to connect MQ7, buzzers and lights to Arduino. And one buzzer will make sound when gas reaches high level and another buzzer will beep when gas level is very low.. High gas amount will lead to red light glow and very low gas will lit green light.. HOW TO EXECUTE ??

sender: assistant

body:
Easy, this is one of the simple projects used as an introduction to Arduino programming.  You will find many versions of free code out there.  below is an example and a total newbie step-by-step.

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

Download Arduino IDE.  Buy an MQ7, an Arduino or NodeMCU, a breadboard, a LED and some jumper wires and you are in business.  Use [the sketch below][2] or google "MQ7 arduino sketch".

    /* MQ-7 Carbon Monoxide Sensor Circuit with Arduino */

 const int AOUTpin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino
 const int DOUTpin=8;//the DOUT pin of the CO sensor goes into digital pin D8 of the arduino
 const int ledPin=13;//the anode of the LED connects to digital pin D13 of the arduino

 int limit;
 int value;

 void setup() {
   Serial.begin(115200);//sets the baud rate
   pinMode(DOUTpin, INPUT);//sets the pin as an input to the arduino
   pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
 }

 void loop() {
   value= analogRead(AOUTpin);//reads the analaog value from the CO sensor's AOUT pin
   limit= digitalRead(DOUTpin);//reads the digital value from the CO sensor's DOUT pin
   Serial.print("CO value: ");
   Serial.println(value);//prints the CO value
   Serial.print("Limit: ");
   Serial.print(limit);//prints the limit reached as either LOW or HIGH (above or underneath)
   delay(100);
   if (limit == HIGH){
     digitalWrite(ledPin, HIGH);//if limit has been reached, LED turns on as status indicator
   } else {
     digitalWrite(ledPin, LOW);//if threshold not reached, LED remains off
   }
 }

original sketch published by [Learning About Electronics][3]

  [1]: https://i.stack.imgur.com/m0QMU.png
  [2]: http://www.learningaboutelectronics.com/Articles/MQ-7-carbon-monoxide-sensor-circuit-with-arduino.php
  [3]: http://www.learningaboutelectronics.com/


message:
How to send and receive unsigned int from one arduino to another arduino

I'm trying to send some big numbers ranging from 0-62000 from one arduino to another via serial communication. I'm using unsigned int to hold values from 0 to 65535. And I'm using serial.print() and serial.write () to send numbers and serial.read()-'0' ; to receive numbers, but I'm unable to send and receive numbers above 9. Please help me.

Here is my code -

(For master)

    const int Button_1 = 2;
    unsigned int s =0;
    void setup ()
    {
       Serial.begin(115200) ;
       pinMode(Button_1,INPUT);
    }
    void loop()
    {
      if (digitalRead(Button_1))
      {
         s = 61805;
         Serial.write(highByte(s)) ;
         Serial.write(lowByte(s));
         delay (5);
         s=0;
      }
      else
      {
         s = 60005;
         Serial.write(highByte(s)) ;
         Serial.write(lowByte(s));
         delay (5);
         s=0;
      }
    }

(code for slave)

    unsigned int upperByte, lowerByte, r=0,p=0;
    void setup()
    {
      Serial.begin(115200);
      pinMode(LED_BUILTIN, OUTPUT) ;
    }
    void loop ()
    {
      If (Serial.available()>1)
      {
         upperByte = Serial.read();
         lowerByte = Serial.read();
      }
        r = (upperByte << 8) + lowerByte ;

       while (r==61805)
        {
            digitalWrite(LED_BUILTIN, HIGH) ;
        }
        while (r==60005)
        {
            digitalWrite(LED_BUILTIN, LOW) ;
        }
    }

body:
Try something like this to send and receive/recombine two bytes:

Send side:

    Serial.write (highByte (your unsigned int));
    Serial.write (lowByte (your unsigned int));

Receive side:

    if (Serial.available() >1){ // two byte received
    upperByte = Serial.read();
    lowerByte = Serial.read();
    }
    newInt = (upperByte <<8) + lowerByte;


body:
There are 2 ways to transmit data over serial: As byte data or in ASCII codes

1. **Byte data:** Everything, that is digitally stored or processed, is a series of 0s and 1s (bits) (electrically HIGH and LOW level), which are grouped into bytes (8 bits). So all data is just numbers at low level. The different datatypes (like numbers, Strings, executable code) are only reached by different interpretation of the byte data. You can take the number value of a byte directly. A byte like `0b00000101` for example is equivalent to the decimal value `5`. So every byte can hold numbers between 0 and 255. (Google the binary system for more information). To hold bigger numbers, more bytes are put together. For example an integer consists of 2 bytes (16 bits) and can hold numbers between 0 and 65535. Note: These are the unsigned types. There are also signed types, that also can hold negative values. To understand this, google binary two's complement. To transmit such a bigger type over serial (which is byte based), you need to seperate the bytes of the type, send them consecutively and put them back together at the receiving side. You can do this with the following code:

        unsigned int number = 54321;
        Serial.write(number & 0xFF); //getting the lower byte of the number by using bitwise AND
        Serial.write(number >> 8); // getting the high byte of the number by shifting the bits of the value 8 bits to the right

    There are macros defined for Arduino, that can do this for you:

        Serial.write(lowByte(number));
        Serial.write(highByte(number));

    In long term, you should learn, how the bitwise operators work. They are often needed. To put the data back together, you can look at CrossRoads answer.

    Note: `Serial.write()` will send the byte data unchanged, while `Serial.print()` will convert the data to ASCII before sending. They are not equal.

2. **ASCII Data:** One interpretation of byte data is the ASCII standard (which is really old). Every byte value between 0 and 127 get's a corresponding ASCII value, meaning characters of the alphabet, digits, some special characters and some control characters. Numbers, that are transmitted as ASCII data, consist of multiple bytes, one for each digit. Thats, what you tried. Since the receiver has to seperate the different numbers to process them correctly, you have to mark the end of each number. This is commonly done with the newline character `\n` (optionally preceeded by the carriage return character `\r`, windows style). You add this at the end of every number. `Serial` has an extra function for that: `Serial.println()` will print the parameter as ASCII and will add a carriage return and newline character. On the receiving side you read the bytes into a buffer, until you see this delimiter sequence. After that, you process the whole buffer. If you want to know, how this Serial communication is done in code, look at the `SerialEvent` example, that comes with the Arduino IDE.

What way you use for transmitting data, is up to you and depends on your needs. If you only want to transmit number data, nothing else, you can use byte data. For complex or diverse data types, you can use the ASCII representation.

---

EDIT: I have described above, that - when using ASCII data - you can use one or more special characters to delimit one message/number. The receiver can then distinguish between the numbers in that row of digits. This is just some kind of protocol, that you impose on the data. You state, that every message is ended with this special character, much like very sentence in the english language is ended with a dot.

An important requirement is, that the special character does not occure inside of a message/number. So cannot use the character `'1'` as delimiter, since it will also occur inside of your numbers and you would chop the numbers in the wrong way.

The same principle can be imposed as protocol onto a byte stream. For example: You define, that every message/number will be ended with a special byte sequence, so that the receiver always can say: "This is the whole data of a number and not just a part of it." As above, the special byte sequence must not occur inside of the valid data. You wrote, that your numbers are always in the range of 0 to 62000. This means, that the value 65535 will never occur as valid data, thus you can use it as delimiter. In hex 65535 is written als `0xFFFF`, which means, that you send two bytes with every bit set to 1 (each byte having a decimal value of 255). In your code everytime, that you are receiving something, you can check, if you have got 2 consecutive bytes with the value 255 (or written as `0xFF`). If not, write the data into a buffer. If yes, that means, that you can process the data inside the buffer to a number.

For sending that would look like this:

    Serial.write(lowByte(number));
    Serial.write(highByte(number));
    Serial.write(0xFF);
    Serial.write(0xFF);

Note: This protocol will make sure, that sender and receiver cannot get out of sync. But still the first reading after a transmission problem (for example that a byte got send before the receiver was ready) will be garbage. That will happen very very rarely, so for most people it's not a problem. There are more principles, that you can use in your protocol to mitigate those problems, if you want to. For example you can define another special byte sequence as the start of a message/number. Or you can calculate a checksum of the number and only use messages/numbers, that fit to that checksum.


message:
Use Arduino to turn fan on / off

I have a simple fan.
When I plug it to GND and Vin it spins.
I'd like to have the ability to turn it on / off with code.
Any example will do, as long as it gets it to spin.
I have a NodeMCU board, if that helps.

body:
Depending of the type of fan you are using, two solutions exist.

- First one, use a MOSFET to drive the FAN from you nodemcu
- Second one, use a relay to drive the FAN from your nodemcu

Things to consider :

- The mosfet allow you to drive the fan without mechanical part moving.
- The relay require some transistor and feedback diode to be driven by your µc.


body: So I didn't have a transistor to do a MOSFET, but I did have a motor driver which I ended up using. From there it was just finding example code to use the motor driver, connecting it up and using it.


message:
Arduino programming with multiple loops

I was trying to program my Arduino (along with a connected motor controller) to switch from cycle to cycle with this program.  It doesn't seem to work however.  There's still plenty of storage space and dynamic memory, so those aren't the issue.  This is the program:

    int EnablePin1 = 8;
    int duty;
    int period;
    int cycle;

    int PWMPinA1 = 11;
    int PWMPinB1 = 3;
    int PWMPinA3 = 6;
    int PWMPinB3 = 5;

    const byte CPin1 = A0;

    int CRaw1;
    void setup() {

        Serial.begin(9600);

        pinMode(EnablePin1, OUTPUT);

        pinMode(PWMPinA1, OUTPUT);
        pinMode(PWMPinB1, OUTPUT);
        pinMode(PWMPinA3, OUTPUT);
        pinMode(PWMPinB3, OUTPUT);

    }

    void loop() {
        digitalWrite(EnablePin1, HIGH); //enable the board
        for (duty = 0; duty <= 255; duty += 15)
        {

            analogWrite(PWMPinB1, 0); //Set pinB to 0, when speed is written to pinA

            analogWrite(PWMPinA1, 255);
            delay(850);
            if (PWMPinA1 == 11)
            {
                PWMPinA1 = 3;
                PWMPinB1 = 11;
            }
            else
            {
                PWMPinA1 = 11;
                PWMPinB1 = 3;
            }
       }
       analogWrite(PWMPinA1,0);//end at max speed
       analogWrite(PWMPinB1,0);
       CRaw1 = analogRead(CPin1);

       Serial.println("Feedback");

       Serial.print(CRaw1);

       delay(2000);
       //analogWrite(PWMPinB3, 0);
       for (duty = 255; duty >= 0; duty -= 51) // ramp down speed
       {
           //analogWrite(PWMPinA1, duty);
           analogWrite(PWMPinB3, 0);
           analogWrite(PWMPinA3, 255);
           delay(period);
           //delay(cycle);
           if(PWMPinA3 == 6)
           {
               PWMPinA3 = 5;
               PWMPinB3 = 6;
               //period = 850;
           }
           else
           {
               PWMPinA3 = 6;
               PWMPinB3 = 5;
              //period = 2500;
           }
       }
       analogWrite(PWMPinA3, 0); //set to 0 speed
       analogWrite(PWMPinB3, 0);
       delay(2000);

       digitalWrite(EnablePin1, LOW);// Toggle enable to reset the power chips           if we have had an overcurrent or overtemp fault

       for (cycle = 1000; cycle < 9000; cycle += 4000)
       {
           //cycle=period;
           period=cycle;
       }

     /*for (cycle = 2000; cycle <= 3000; cycle += 1000)
       {
           //cycle=period;
           period=10000;
       }*/
       for (cycle = 9000; cycle >= 1000; cycle -= 8000)
       {
           period=0;
       }

       //delay(2000);  // Swap pins to make the motor change direction

    }//end main loop

I've also tried having the cycle loops be this:

     for (cycle = 0; cycle < 9000; cycle += 3000)
     {
         //cycle=period;
         period=cycle;
     }
     for (cycle = 9000; cycle >= 0; cycle -= 9000)
     {
         //cycle=period/3;
         period=cycle;
     }

But that didn't do anything (I can see what PWM pins are powered through LEDs, and the first attempt, the LEDs only lit up for 1 second and the 2nd, they didn't light up at all.

body:
## First things, try to use multiple function and call it from the loop()

You can use some code magic for dealing with multitasking on Arduino.
It's a bit tricky to understand but it's working.

Here is an example :
~~~

const int BROCHE_LED_1 = 13;
const int BROCHE_LED_2 = 12;
const int BROCHE_LED_3 = 11;

const unsigned long BLINK_INTERVAL_1 = 1000;
const unsigned long BLINK_INTERVAL_2 = 500;
const unsigned long BLINK_INTERVAL_3 = 2000;

void setup() {

  pinMode(BROCHE_LED_1, OUTPUT);
  pinMode(BROCHE_LED_2, OUTPUT);
  pinMode(BROCHE_LED_3, OUTPUT);

  digitalWrite(BROCHE_LED_1, LOW);
  digitalWrite(BROCHE_LED_2, LOW);
  digitalWrite(BROCHE_LED_3, LOW);
}

void loop() {

  task_led1();
  task_led2();
  task_led3();
}

void task_led1() {
  static unsigned long previousMillisLed1 = 0;
  static byte etatBrocheLed1 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed1 >= BLINK_INTERVAL_1) {

    previousMillisLed1 = currentMillis;

    etatBrocheLed1 = !etatBrocheLed1;
    digitalWrite(BROCHE_LED_1, etatBrocheLed1);
  }
}

void task_led2() {
  static unsigned long previousMillisLed2 = 0;
  static byte etatBrocheLed2 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed2 >= BLINK_INTERVAL_2) {

    previousMillisLed2 = currentMillis;

    etatBrocheLed2 = !etatBrocheLed2;
    digitalWrite(BROCHE_LED_2, etatBrocheLed2);
  }
}

void task_led3() {
  static unsigned long previousMillisLed3 = 0;
  static byte etatBrocheLed3 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed3 >= BLINK_INTERVAL_3) {

    previousMillisLed3 = currentMillis;

    etatBrocheLed3 = !etatBrocheLed3;
    digitalWrite(BROCHE_LED_3, etatBrocheLed3);
  }
}
~~~

## Second things, Try to use Real time operating system

You can try to use FreeRTOS, it's work with most arduino and you got lot of infos on the web.

It make multi tasking way more easy than the previous example.

Here is the [Docs i've found][1]

  [1]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc


message:
How to read high voltage (40-65v) from a Solar Battery bank

I would like to monitor the battery voltage of a 48v solar battery system. The **expected voltage range is 40-65v**.

I have tried creating a voltage divider with 2 resistors but with all values I have tried one resistor almost melts as soon as you connect to battery.

Also, using a voltage divider creates a (small) drain which I would like to avoid.

Can anyone suggest a way of reading high DC voltage (40-65v) with and Arduino (really I'm using an ESP8266)?

**If Voltage Divider**

please suggest resistor types (e.g. 1/4watt or 1-2% etc, I'm new here but know there are many types) and values that I could read with A0 (analog pin, max 5v)

Can I use a MOSFET to connect the voltage divider just before reading the voltage? How?

**or another way**

like a circuit (from AliExpress) or using some other component that would be greatly appreciated.

So far this article has been helpful, it talks about a voltage divider with a opamp to get more accuracy, but I need a bit more advice from someone that knows more than myself.

https://openenergymonitor.org/forum-archive/node/11011.html

Thanks in advance for any help.

body:
It sounds as if you have tried using far too small a value resistors. For example, if you used resistors totaling , say, 1,000 ohms across a 50V supply then they would dissipate V^2/R watts = 2.5W. Standard 1/4 watt resistors are going to melt when overloaded 10 times.

So it boils down to picking a pair of resistors that

1) Are working within their wattage rating.

2) Give a convenient scaling factor.

3) Draw an insignificant amount of current relative to the ratings of the solar panels.

The design of any voltage divider also depends on the input impedance or load imposed by the ESP8266. Referring to the [ESP8266 Community Forum][1] the analog input imposes a 50nA load, but they also state that the maximum input voltage is only 1V (equivalent to 20 M ohm impedance). The [Adafruit forum][2] also suggests that 1V is the maximum. Maybe the board you have has different built in scaling.

For the sake of argument, let us assume the following

Voltage range to be measured = 40 - 65V

Maximum input voltage of pin A0 = 1V

Pin A0 can draw 50nA and this should not effect the measurement by more than 1 in 2048 (half the least significant bit of the ADC).

The current through the voltage divider should therefore be at least 2000 * 50nA = 0.1 mA. This almost certainly meets the requirement of not significantly loading the battery.
So based on the low end of the voltage range the divider chain should total in the region of 45V / 0.1mA = 450K ohms. The two resistors need to be in the ratio 64:1 in order to drop a 65V input to 1V. Referring to standard resistor values, 360K and 5K6 in series will be very close to 64:1 (64.28:1). They will draw a maximum of 65V/(360K + 5K6) = 0.18mA and the 360K resistor will dissipate about 10mW.

So standard quarter watt E24 series 1% resistors should be suitable.
  [1]: https://www.esp8266.com/viewtopic.php?f=160&t=13435
  [2]: https://forums.adafruit.com/viewtopic.php?f=19&t=90062


body:
**You need a voltage divider with resistors that have large values.**

> ...but with all values I have tried one resistor almost melts as soon as you connect to battery.

This suggests that you have been using values that are too low.

So lets go through the calculations to select good resistor values.

1/4 Watt resistors are common and easily available so I will base my calculations on that. These calculations will also be suitable for 1/2 Watt and 1 Watt resistors.

I am also going to add some margin above the 65V max that the solar panel can output (plus it makes the math easier)

Max Voltage = 100V

----------

The voltage Divider:

[![Voltage Divider][1]][1]

Let's simplify. Almost all of the current will be going from your source, through the resistors (R1 & R2) to ground. Let's simplify by initially calculating the resistance required if R1 & R2 were combined into a single resistor:

From V = I x R
And P= V x I

Minimum resistor = V^2 / P

R = 75^2 / 0.25

R = 22500 Ω minimum

I would go further and say double that because I never like operating a resistor right on its maximum power rating. ie  the minimum that R1 + R2 should equal is 50kΩ.

Lets play it safe and say that R1 + R2 is 100kΩ. The ESP8266 ADC pin input voltage range is 0 to 1V. Input is 0-100 V (which covers the required 40-65V range). Now all we have to do is calculate for R1.

**Note:** Most ESP8266 development boards come with an internal voltage divider. For these boards the input range is 0 to 3.3V.

**Edit:** The OP tells me that they get a max analog reading at 3.0V not 3.3V. Adjust the below calculations for an input voltage of 3.0V not 1V.

The formula to calculate the output voltage is:

![Formula][2]

Vout / Vin = R2 / (R1 + R2)

1 / 100 = R2 / 100kΩ

0.01 = R2 / 100k

Therefore R2 = 1k Ω

R1 = 100k - R2 = 99kΩ

I would up R1 to 100kOmega; as it will only result in a 1% error.

So R1 = 100kΩ and R2 = 1kΩ

----------

Values of R1 = 49.5kΩ and R2 = 500Ω would also work.

In this case R1 could be made up of 2-3 resistors in series:
47KΩ
2.2KΩ
300Ω or 330Ω (optional)

----------

The raw ADC input on the ESP8266 chip is 0-1V with a high input impedance (~20M). This means an op-amp buffer is not needed.

However, if you are interested, a op-amp circuit can be built from a 741 IC (among others) and is configured like this:

[![Op-amp][3]][3]

  [1]: https://i.stack.imgur.com/HweJQ.png
  [2]: https://i.stack.imgur.com/RBYmH.png
  [3]: https://i.stack.imgur.com/xnlP7m.png


message:
creating HTTP persistent connection, to create 'smooth' data over GSM sending

**Project goals**

 - Send data over GSM to firebase
 - Fast sampling - need to send 16 bytes every half second to firebase
 - Send data using GET or POST to server with PHP script, that redirect data to firebase

**Problems --
Extremely low data rate!**

 - Using standard GET or POST request from client(arduino) side, is impossible to achieve second (2) project goal.
 - **To send data correctly I need to close connection with server, so next data package unfortunately waits(2-6 seconds) for establishing a new connection.**

  Is this quite nonsense? I'm using ArduinoHttpClient library.

**My actual Nonsense Connection and fully useless, but works**
<!-- language-all: lang-cpp -->

    while(1){

    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    http.stop(); //closing connection with server

    //next instruction take over 5 second to establish new connection :(

    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    http.stop(); //closing connection with server, whyyy?
    }
 Data are send once per 2 - 6 seconds, this is not even funny. NEED to send data every 0.5 seconds!

So I decided to create super solution, which not works :C

    while(1){
        http.post("/test.php","application/x-www-form-urlencoded","data=0");
        delay(xxx);
    //no connection closing, no wasting time for establishing new one :)
    }

Just tell my why this connection is not "Keep-Alive", also used with

> http.sendHeader("Connection: Keep-Alive"); or
> http.connectionKeepAlive();

    //First run
    http.post(blabla);// returns value: 0 & data are logged into firebase
    //Second run
    http.post(blabla);// returns value: -2 & data are not logged in firebase

**my test.php file**

    <?php
    require_once 'firebaseLib.php';
    $url = 'https://czujniki-aa5ca.firebaseio.com/';
    // --- Use your token from Firebase here
    $token = ':-CCCCCCCCCCCCCCCCCCCCCCC';

    $arduino_data_post = $_POST['data'];
    $firebasePath = '/';

    $fb = new fireBase($url, $token);
    $response = $fb->push($firebasePath, $arduino_data_post);
    sleep(2);

body:
The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.

The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.

In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.


message:
Connecting multiple RS485 together

I am trying to build communication across multiple Arduino using RS485. When i am trying to connect 3 Arudino nano together using breadboard my code doesn't reach slave where as if i just if i do direct connection between 2 RS485 without breadboard it works but i use breadboard for 2 it doesn't work. Am i missing any setup here?

Breadboard connection - A & B are connected to + & - of both RS485.

Working connection - A & B of first RS485 connected to A & B of 2nd RS485.

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

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

body:
It is possible you have too many resistors on the RS485 bus. From the [RS485 wikipedia page][1] there is this quote:

> Ideally, the two ends of the cable will have a termination resistor
> connected across the two wires.

This may explain why you can use 2 of your RS485 interfaces but not 3.  Consider removing the resistors from the RS485 board in the middle if possible.

  [1]: https://en.wikipedia.org/wiki/RS-485


message:
How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?

How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?

I am a beginner and I need help on how to control two 12 V motors using the Pololu dual MAX 14870 Motor Drive Shield for Arduino Uno.

body:
I had attached the screenshot for this[![enter image description here][1]][1]

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

This picture tells you about the Arduino Connection with the with the SHIELD.

 1. `EN (Enable Pin)` is used to enable and disable the motor drivers. As it is inverted `SET this PIN HIGH` will Disable the Motors and vice versa.
 2. `DIR pinS` is used direction of rotation. It highly depends upon your connection, setting this `PIN HIGH LOW` will make the motor rotation from `CLOCKWISE & ANTI CLOCKWISE` or vice versa depends upon your hardware connection.
 3. `PWM pins` are used to control the rotation speed of the MOTOR. `Driving PWM signal` on this pin will adjust your rotational speed. `MAX PWM frequency suggested is 50Hz`.
 4. `Fault` is the `INPUT PIN to Arduino` with `ACTIVE LOW` signal indicating some kind of fault is there.


message:
Controlling multiple 12v solenoids with 5v relay modules (Arduino Reset Issue)

I have 4 12V(1A) [solenoids][1] running on a 12V(4.16A) power supply.
Each solenoid circuit is controlled by a 5V [relay module][2] connected to the Arduino Uno (powered by USB).

The solenoids actuate properly but eventually the Arduino resets, typically when multiple solenoids are turned on/off in fast succession. This is accompanied by random character artifacts on the LCD display (connected to the Uno) during operation but before the reset.

From what I've gathered there are back EMF surges occurring when the solenoids lose their charge. Here are some possible remedies I've found:

 1. Add a flyback diode (IN4004) to each solenoid circuit. (Redirect the surge)
 2. Add a capacitor (4700 - 10,000 uF) to the 5v supply (from the Uno) for the relays. (Filter the surge)
 3. Provide a separate 5v power source to the relay modules instead of using power from the Uno. (Isolate the surge)

Any input on which solution(s) should be applied or other possible causes for the Uno reset and LCD distortion is appreciated.

  [1]: https://www.amazon.com/gp/product/B00HR8H38A/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/Youngneer-Raspberry-Arduino-Channel-Opto-Isolated/dp/B07M88JRFY/ref=pd_ybh_a_3?_encoding=UTF8&psc=1&refRID=5NSHB73CTBAAGVPN2E96

body:
## Here is another path to explore :

- Try to use separate rail for the 5v relays
- Use a transistor or darligton array (such as ULN2003) for controling your 5v relay.
- ALWAYS put a feedback diode when you use an inductive load it can break your Arduino !!

## My analyse :

- Arduino and many other µc have limited output current on IO, be sure to not overload these value by using transistor or darligton array.
- The voltage regulator on the Arduino can provide around 200 mA of power. I you are overloading the value use an external power supply for your circuit.
- The solenoid can draw lot of current of the power supply, try to measure if a voltage drop occur on loads. It can cause the arduino to reset due to low voltage.


body:
Some of those 5V "digital" relays can be wired using a separate power supply for the relays and the Arudino. You have to move a jumper to use separate power supplies.

My guess is that you're powering both your Arudino and your relay coils from the same 5V supply, and when you energize all 4 relays at the same time you draw too much current and the Arduino doesn't get enough voltage and resets.

Read up on your relay modules, and either re-wire them using 2 different 5V supplies, or switch your 5V supply to a higher current supply. (and possibly adding a filtering capacitor to the Arduino to smooth out the power fluctuations as the relays energize and de-engergize)

I used a 4-channel relay unit in a project of mine that has optical isolation of the relay control lines, and can be wired to use separate power supplies for the Arudino and the relay power. When wired with separate power supplies, the relay's control lines just draw CMOS logic levels to control the different relay channels, and get the power for the coils independently from the microcontroller's power.


message:
Mega <> esp8266 comms sending baffling data

I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <WebSocketsServer.h>

    const char* ssid     = "SKYNET";
    const char* password = "yourdogsfavouriteauntysmaidenname";

    WebSocketsServer webSocket = WebSocketsServer(81);

    void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

        //Serial.printf("[%u] get Message: %s\r\n", num, payload);

        switch(type) {
            case WStype_DISCONNECTED:
                break;

            case WStype_CONNECTED:
                {
                  IPAddress ip = webSocket.remoteIP(num);
                  Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
                }
                break;

            case WStype_TEXT:
                {
                  String _payload = String((char *) &payload[0]);
                  Serial.print(_payload);
                }
                break;

            case WStype_BIN:
                {
                  hexdump(payload, lenght);
                }
                // echo data back to browser
                webSocket.sendBIN(num, payload, lenght);
                break;

        }
    }

    void setup() {

      // Set up serial comms
      Serial.begin(115200);

      // Set up WiFi
      WiFi.begin(ssid, password);
      while(WiFi.status() != WL_CONNECTED) {
         Serial.print(".");
         delay(200);
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

      delay(500);

      // Set up web socket
      Serial.println("Start Websocket Server");
      webSocket.begin();
      webSocket.onEvent(webSocketEvent);
    }

    void loop() {
      webSocket.loop();
    }

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial <> ESP comms).

I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...

    // Input buffer from ESP8266
    String temp;

    void setup() {
      // Set up serial comms
      Serial.begin(115200);   // Debug to Serial Monitor
      Serial3.begin(115200);  // From ESP8266
    }

    void loop() {
      while (Serial3.available()) {
          Serial.println(".......");
          Serial.println("In from ESP8266");
          temp = Serial3.readString();
          Serial.println(temp);
          Serial.println(".......");
      }
    }

So now I get 2 one time messages to the serial monitor..

    .......
    In from ESP8266
    [WS-Server] Server Started.

    .......
    .......
    In from ESP8266
    pm open,type:2 0

    .......

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.

Any idea what's going on here?

**Edit 1:** Addition info asked for in comments (or at leat I think this is what was asked for)

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

**Edit 2:**

DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON

DIP switch settings ESP > serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)

DIP switch settings for ESP > Mega > serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)

**Edit 3** I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.

**Edit 4** Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.

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

body:
The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.

On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.

The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (`--after no_reset` in `tools.esptool.upload.pattern` before `write_flash`)


message:
Wifi stopped connecting (Wemos D1 Mini)

I am stumped.  I have a few Wemos D1 Mini boards that were working on the local WiFi yesterday, yet today none of them will connect.  More puzzling is that I can flash Tasmota on them and they all connect to the WiFi, but none with this code that was working yesterday.  Any tips would be appreciated.
<!-- language-all: lang-cpp -->

    void setup_wifi() {
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(wifi_ssid);

      //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
      WiFi.mode(WIFI_STA);
      WiFi.begin(wifi_ssid, wifi_password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.print(F("WiFi connected, "));
      Serial.print(F("IP address: "));
      Serial.println(WiFi.localIP());
    }

body:
Solved.  (sort of).  This is a working workaround.

I have determined that if I use ESP8266WiFi library Version 2.5.0 or later, all I get from WiFi.status() is WL_NO_SSID_AVAIL.

By reverting to ESP8266WiFi library Version 2.4.2, I can get a connection with the same sketch.

(Juraj's comments pushed me in the direction of trying older library versions.)


body:
Assuming that it's not something silly and accidental like the password or ssid being changed in your code, there are two things you may be running in to:

 1. The WiFi.begin() function is technically not needed more than once. Values written with it are stored in a separate part of flash memory that is not overwritten by any sketch uploads. Since it's stored persistently, it may start connecting before your connection code is called. This causes a race condition that triggers a bug in the library that is, to my knowledge, still present, and can break the WiFi subsystem. If this has happened, the reason that the other firmware might work is if it fixes the error or somehow uses a different method.
You can work around this by waiting a few seconds and then trying to connect if it's not currently connected.
Try this fix: https://github.com/kentaylor/EraseEsp8266Flash to see if that's the problem. Alternatively, you can try some of the options in the first link of my next item to see if those work for this purpose.

 2. Remember how I said that the functions persist data in flash? That has a limited write count, and no, that partition has no wear-leveling. After so many writes (and, since begin() is called in setup, it does so every time the device starts or wakes!) it will fail to hold the correct values. The endurance can be quite poor on some cheaper flash devices (and cheaper boards). But, if you want to keep using begin() to set up the WiFi (rather than set it once the normal way and then make sure begin() isn't called again by your code), delete the stored parameters (https://arduino.stackexchange.com/questions/52059/does-the-esp8266-somehow-remember-wifi-access-data) and then turn off persistence (https://arduino.stackexchange.com/questions/63187/esp8266-advertising-ap-even-when-flashed-with-custom-firmware). I also suggest running the following code fragment to turn off persistence and then **stop** turning it off (since THAT change persists too!):

    if (WiFi.getPersistent()) {
      WiFi.persistent(false);
    }

This latter case is known to break Arduino projects, but NOT nodeMCU Lua ones. If the Tazmota firmware uses a different method, it could also ignore this issue but your code might experience it. To test this, try running the code on a different board (can be the same type, just so long as it's not the same one).


body:
Fixed.
My router is ancient and does not support WPA.  As of ESP8266WiFi library Version 2.5.0, WPA is is the preferred mode.  The solution is to get a better router, or add WiFi.enableInsecureWEP(); before calling WiFi.begin().

    WiFi.enableInsecureWEP();
    WiFi.begin(wifi_ssid, wifi_password);


message:
Arduino components

I’m teaching and learning coding with MicroBit and was wondering if these components are compatible with MicroBit. The specific kits labeled for MicroBit are twice the price but the components look similar. Just trying to save a few bucks. Would [this kit][1] work with my MicroBit?

  [1]: https://www.amazon.com/Freenove-Processing-Oscilloscope-Voltmeter-Components/dp/B0721B8228/ref=sxbs_sxwds-stvp?keywords=microbit&pd_rd_i=B0721B8228&pd_rd_r=8042ad3a-014d-4732-955a-47ac3cebe6f7&pd_rd_w=uZE9o&pd_rd_wg=t1Lip&pf_rd_p=d006b618-5fac-44e6-850d-a0fdd19f7847&pf_rd_r=0B91ZE63AWRZKGC4MCGJ&qid=1558567791&s=gateway

body:
It looks like the MicroBit runs on 3.3V versus 5V for most Arduino boards. You'd need to use 3.3V components.

It looks like the kit you linked to is built for (and includes) a 5V Arduino, so those accessories would not work with your MicroBit.

There are other Arduino boards that run on 3.3V. Look for 3.3v accessories. Those should work.

## EDIT:

------

I assume that the MicroBit is capable of I2C interfacing. If so, you should look at the SparkFun Qwiic system. It's a setup with 3.3V I2C serial interface in a 4-wire ribbon cable with a standard connector. You can easily daisy-chain Qwiic devices by just plugging Qwiic cables between them, and they are reasonably priced. I bought some of them thinking I could use them with my Arduino projects, only to discover that they use 3.3V, so I can't use them without I2C voltage translation interfaces, which makes them much less appealing.


message:
Code with if multible conditions

My project has 4 float switches, 2 valves and 3 pumps. I created a sketch and uploaded it. But my project keep all "OUTPUT" at "HIGH" all the time. I couldn't find what the problem, can you help?

This is my sketch:
<!-- language-all: lang-cpp -->

    #include <DS3231.h>
    #include <Wire.h>
    #include <LiquidCrystal.h>
    DS3231  rtc(SDA, SCL);

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    int x = 45;
    int y = 47;
    int z = 41;
    int w = 43;

    int WaterIn =  40;
    int WaterOut = 42;

    int Pump1 = 25;
    int Pump2 = 24;
    int Pump3 = 27;

    void setup()
    {
      rtc.begin();
      lcd.begin(16,2);
      // Start the I2C interface
      Wire.begin();
      // Start the serial interface
      Serial.begin(9600);
      //rtc.setDOW(TUESDAY);     // Set Day-of-Week to SUNDAY
      //rtc.setTime(1, 15, 0);     // Set the time to 12:00:00 (24hr format)
      //rtc.setDate(6, 6, 2017);   // Month, Day, Year

     //Setup FLoat Switch Pins
      pinMode (x, INPUT);
      pinMode (y, INPUT);
      pinMode (z, INPUT);
      pinMode (w, INPUT);

     //Setup Irrigation Valves
      pinMode(WaterIn, OUTPUT);  //irrigation "in" valve
      pinMode(WaterOut, OUTPUT);  //irrigation "out" valve

    //Setup Pumps
      pinMode(Pump1, OUTPUT);
      pinMode(Pump2, OUTPUT);
      pinMode(Pump3, OUTPUT);
    }  // end of setup

    void Calendar(){

     lcd.setCursor(0,0);
     lcd.print("Real Time Clock  ");
     lcd.setCursor(0,1);
     lcd.print("Time: ");
     lcd.print(rtc.getTimeStr());
     delay(1000);
     lcd.setCursor(0,1);
     lcd.print("Date: ");
     lcd.print(rtc.getDateStr());
     delay(1000);
     lcd.setCursor(0,1);
     lcd.print("Day: ");
     lcd.print(rtc.getDOWStr());
     lcd.print("           ");
     delay(1000);
     lcd.setCursor(0,1);
     lcd.print("Temp: ");

     lcd.print(rtc.getTemp());
     lcd.print(" C");
     lcd.print("          ");
     delay(1000);
    }  // end of setup

    void Valves(){
        int pinToTurnHigh = 24;
        if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))  //Condition 1
        {
            pinToTurnHigh = WaterIn;
            pinToTurnHigh = Pump1;
            pinToTurnHigh = Pump2;
            pinToTurnHigh = Pump3;
        }
        if ((x == LOW) && (y == LOW) && (z == HIGH) && (w == HIGH))  //Condition 2
        {
           pinToTurnHigh = WaterOut;
        }
        resetAllPumpValve();
        digitalWrite(pinToTurnHigh, HIGH);
    }  // end of setup

    void resetAllPumpValve(){
         digitalWrite(WaterIn, LOW);
         digitalWrite(Pump1, LOW);
         digitalWrite(Pump2, LOW);
         digitalWrite(Pump3, LOW);
         digitalWrite(WaterOut, LOW);
    }  // end of setup
    void loop()
    {
        Calendar();
        Valves();
        resetAllPumpValve();
    }  // end of loop

body:
It is not clear, what the code actually should do (what behaviour you are trying to achieve), so I will only look into the obvious programming problems.

1. The following declarations at the global scope seem to be pin numbers:

        int x = 45;
        int y = 47;
        int z = 41;
        int w = 43;

        int WaterIn =  40;
        int WaterOut = 42;

        int Pump1 = 25;
        int Pump2 = 24;
        int Pump3 = 27;

    But in the `Valves()` function yout treat them as they were representing the value of that pins. That is not the case. If you want to read the state of a pin, you cannot do

        if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))

    You are just comparing the pin number with `HIGH`, which is defined as `1`. That cannot work. You have to actually read the pin using it's pin number, which looks like this:

        if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)

    And that can be shortened to:

        if( digitalRead(x) && digitalRead(y) && digitalRead(z) && digitalRead(w) )

2. Inside of the mentioned if statements you set a variable multiple times without doing anything with it. Any consecutive write to this variable will overwrite the previous value. After the code block

        pinToTurnHigh = WaterIn;
        pinToTurnHigh = Pump1;
        pinToTurnHigh = Pump2;
        pinToTurnHigh = Pump3;

    The variable `pinToTurnHigh` is 27 (Pump3). The values, that you assigned right before that line, are lost. You actually have to do something with the variable, or the first 3 lines of that block makes no sense.

3. In most cases it is not a good idea, to use variables with changing values to handle pin numbers, since that will make the code difficult to understand. The circuitry is mostly hardwired, it will not change. So there is no need to assign pin numbers to a changing variable. Instead you can directly do, what you need to do with a constant pin number. (Actually the code optimizer, that comes with the compiler, can optimize the not-changing pin-number variables out, so that you wrote them in your code, but the actually code might not have them.) Here it seems, that you want to write a `HIGH` value to all the mentioned pins. You can do that directly:

        digitalWrite(WaterIn, HIGH);
        digitalWrite(Pump1, HIGH);
        digitalWrite(Pump2, HIGH);
        digitalWrite(Pump3, HIGH);

    Here it is important to understand, that `digitalWrite()` is only working on 1 single pin at a time. If you want to set multiple pins with it, you have to call it multiple times with the according pin numbers.

4. Now the timing of your code: The `Calendar()` function will block the rest of the code for about 4s, because you used that much of `delay()`. During that time the Arduino cannot react to anything. The switches will not do anything either (since the Arduino is busy waiting in the `delay()` instead of checking the switches). The code, that is called after the `Calendar()` function, contains no `delay()`s, so it will run very fast. In the `Valves()` function you first reset all the pumps and valves to `LOW`. Then you write `HIGH` to one pin (as mentioned above I assume, that you wanted to write them all on condition). After that the program will go back to the `loop()` function and execute the `resetAllPumpValve()` function again, which will set all the outputs to `LOW`.

    All in all that means, that the Arduino is fiddling thumbs inside the `Calendar()` function, without doing anything else. Then he will reset, set and reset the pins again. Since there is not timing code in there, this will happen very fast. So the pins have to be `LOW` most of the time and being turned on about every 4s for a tiny amount of time (a low number of milliseconds, since that is about the time to execute `digitalWrite()` or it's siblings). The motors or values will hardly have time to move with that.

    For solving this you might want to look into the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It shows a non-blocking coding style, that will only do something, if it is the time to do it. Much like when you bake a pizza. You will not sit in front of the oven and wait patiently, until the pizza is fully baked. You will put it into the oven and regularly (maybe every 5 min) look, if the pizza is ready to eat. In the meantime you would do other things. Thats what is done there by using the `millis()` function, that will return the number of milliseconds passed since the programs startup. You can look into the example and google about it to learn more. It has been covered numerous times throughout the internet.

That's it for now. To really help you with the logic of the program, you will first have to get these parts right.

Have fun while learning :-)


body:
I would add to Chrisl's answer by saying that, if you wanted to make the code more compact, you could represent the 4 boolean variables by a single byte,

e.g. w HIGH + x HIGH + y LOW + z LOW = 1100.
e.g. w HIGH + x HIGH + y LOW + z HIGH = 1101.

Then it would be easier to implement a `switch` statement instead of `if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)` etc.

For example:

    byte state;

    void setup(){}

    void loop(){
     // insert code to read state
     switch (state)
     {
         case 1:
             // insert code to be run if state = 0b0001;
         break;

         case 13:
             // insert code to be run if state = 0b1101;
         break;

         default: // code to be run if state doesn't match any cases
     }
     // insert other code
    }

If you were willing to use the ATmega's digital 30-37 pins then you could use the AVR's port command `PINC` to read all of the HIGH/LOW states at once, using a single instruction.  I leave this as an exercise for you to try!


body:
chrisl made an excellent analysis of your program and the problems
therein. I would just want to add a point about how to handle the
`Calendar()` function. You have been given the suggestion to look at the
[Blink Without Delay][] Arduino tutorial, and I second that suggestion.
This is indeed the first thing you should do.

However, once you have studied that tutorial and you try to apply it to
your specific problem, you will notice that yours is somewhat harder
than blinking an LED. The reason it is harder is that you have to manage
a more complex system state. The LED has only two states, and it
periodically transitions between them as:

* `LOW` → `HIGH` → `LOW`

Your display routine will instead have four states and make the following
transitions:

* `SHOW_TIME` → `SHOW_DATE` → `SHOW_DAY` → `SHOW_TEMP` → `SHOW_TIME`

The relevant programming concept for dealing with this kind of system is
called a “finite state machine” and I suggest you also study this
[finite state machine tutorial][fsm]. This tutorial proposes a very
generic `switch`/`case` control structure for programming an FSM.
However, if there is some behavior common to all states (in your case:
the fact that each one lasts for exactly one second), you can factor that
behavior out of the `switch`/`case` construct.

Here is what I would propose as a non-blocking `Calendar()`. First, put
this near the top of the program, along with the other constants:

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

    const LCD_DISPLAY_TIME = 1000;  // display each item for 1,000 ms

Then, is `setup()`, right after initializing the LCD:

    lcd.setCursor(0, 0);
    lcd.print("Real Time Clock ");

As a general rule, `setup()` is the right place for anything that only
needs to be done once, at the start of the program.

And finally, the `Calendar()` function to be called from `loop()`:

    void Calendar()
    {
        // Do nothing unless it's time to refresh the display.
        static uint32_t last_change = -LCD_DISPLAY_TIME;
        if (millis() - last_change < LCD_DISPLAY_TIME) return;
        last_change += LCD_DISPLAY_TIME;

        // Switch to the next item: Time -> Date -> Day -> Temp -> Time
        lcd.setCursor(0, 1);
        static enum { SHOW_TEMP, SHOW_TIME, SHOW_DATE, SHOW_DAY } state;
        switch (state) {
        case SHOW_TEMP:
            lcd.print("Time: ");
            lcd.print(rtc.getTimeStr());
            state = SHOW_TIME;
            break;
        case SHOW_TIME:
            lcd.print("Date: ");
            lcd.print(rtc.getDateStr());
            state = SHOW_DATE;
            break;
        case SHOW_DATE:
            lcd.print("Day: ");
            lcd.print(rtc.getDOWStr());
            state = SHOW_DAY;
            break;
        case SHOW_DAY:
            lcd.print("Temp: ");
            lcd.print(rtc.getTemp());
            lcd.print(" C");
            state = SHOW_TEMP;
            break;
        }
        lcd.print("           ");  // pad
    }

[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[fsm]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


message:
Switch Control Between Two Different Techniques

I have implemented PID control of a generator governor to maintain a constant RPM using an Arduino Uno. It works pretty well, but there is a tradeoff between stabilty and response time. Using PID values that allow it to respond without oscillation is also about half as fast as the old mechanical governor.

I came up with a plan to use a CT to sense the AC amps and have the Uno rapid the throttle servo to a known value determined manually. Either using a lookup table or an interpolation algorithm, I haven't yet checked the linearity of the amps vs. throttle angle. The idea is to use a table (or interpolation) to get the governor close, and then let the PID fine tune it.

My hangup is that I'm not sure how to switch between lookup control and PID control as needed.

Pseudo-code:

analogRead(AMPS);
myservo.write(table_Val);
somehow_switch_to_PID;
myservo.write(PID_value);

body:
> the PID is looking at the RPMs and giving an output but that output is
> being ignored because another operation has servo control.

PID is not something, that happens somewhere in the background without you having any control. On the Arduino it is done in software, so you can totally control it. Why should you run a PID calculation, if you don't use the value? The solution is to simply only do the appropriate calculation depending on the RPM at any given time. No need to do 2 calculations at the same time. I will form that into a code with explanations:

You have 2 ways of calculating the needed servo values:

1. Your "getting close" method
2. The PID method

To switch between those methods you need to make a decision based on the RPM. If the RPM is outside of your interval, the first method is used. If it is inside, the second will be used. Decision/conditionals are often wrote with an `if else` statement. Look at this (not tested) code snippet:

    int target_rpm = 700;
    int half_interval = 20;
    int current_servo_pos = 0;

    void loop(){
        current_rpm = analogRead(AMPS);

        if(current_rpm > target_rpm - half_interval && current_rpm < target_rpm + half_interval){
            // Do the PID calculation here and save the result in current_servo_pos
        } else {
            // Do the "getting close" calculation here and save the result in current_servo_pos
        }

        myservo.write(current_servo_pos);
    }

I didn't go into detail about the actual calculation, since that is not important here. You may use any calculation, that you like there. For PID you can find libraries, that do the calculation for you, for example [here at github][1].

The code will simply decide based on the RPM, what calculation should be used. If the RPM goes out of the interval for some reason (maybe is was disturbed and lost some speed), it will automatically use the "getting close" method until it is again inside of the interval.

Note: The numbers, that I used here, are arbitrary. You should change them to what ever you need.

  [1]: https://github.com/br3ttb/Arduino-PID-Library


message:
expected unqualified id-before '/' token ------ can someone help, please

/* Multiple State Handling
    * 05-22-2019
    */

    #define button 3                        //Push button on D3
    #define lowbeam 5                       //Low Beam on D5
    #define highbeam 6                      //High Beam on D6
    #define gate 7                          //Gate on D7

    /------------------------------------------------------------------------

    int state = 0;                          //integer to hold current state
    int old = 0;                            //integer to hold last state
    int buttonPoll = 0;                     //integer to hold button state
    /-------------------------------------------------------------------------

    void setup() {
      pinMode(button,INPUT);                //button set as input
      pinMode(lowbeam,OUTPUT);              //relays set as outputs
      pinMode(highbeam,OUTPUT);
      pinMode(gate,OUTPUT);

      digitalWrite(lowbeam,LOW);            //initial state as off
      digitalWrite(highbeam,LOW);           //initial state as off
      digitalWrite(gate,LOW);               //initial state as off

    }
    /-------------------------------------------------------------------------
    void loop() {

                                            //debouncing routine to read button
      buttonPoll = digitalRead(button);     //poll state of button
      if(buttonPoll == 1){                  //check if it has been pressed
        delay(50);                          //wait 50msec
        buttonPoll = digitalRead(button);   //poll button again
        if(buttonPoll == 0){                //if it is 0 consider 1 press
          state = old +1;                   //increase state by 1
        }}
      else{                                 //if button has not been pressed
      deley(100);                           //wait 100ms
      }
      switch (state) {                      //react to button press & state
        case 1:                             //if state is 1
          digitalWrite(lowbeam,HIGH);       //lowbeam relay on
          digitalWrite(highbeam,LOW);       //highbeam relay off
          digitalWrite(gate,LOW);
          old = state;                      //set old state as current state
          break;
        case 2:
          digitalWrite(lowbeam,LOW);
          digitalWrite(highbeam,HIGH);
          digitalWrite(gate,LOW);
          old = state;
          break;
        case 3:
          digitalWrite(lowbeam,LOW);
          digitalWrite(highbeam,LOW);
          digitalWrite(gate,HIGH);
          old = state;
          break;
        default:                            //if state if no 1,2,3
          digitalWrite(lowbeam,LOW);        //all relays off
          digitalWrite(highbeam,LOW);
          digitalWrite(gate,LOW);
          old = 0;                          //reset to all off/state 0
          break;
      }
    }

body:
OK, you just had a couple of minor typos.

It's nice to break up your code for readability, but single-line comments comments start with a double slash `//`, rather than a single.

Also, you had mis-spelled 'delay' in your loop.

<hr>

This should compile without errors:

    /* Multiple State Handling
    * 05-22-2019
    */

    #define button 3                        //Push button on D3
    #define lowbeam 5                       //Low Beam on D5
    #define highbeam 6                      //High Beam on D6
    #define gate 7                          //Gate on D7

    //------------------------------------------------------------------------

    int state = 0;                          //integer to hold current state
    int old = 0;                            //integer to hold last state
    int buttonPoll = 0;                     //integer to hold button state
    //-------------------------------------------------------------------------

    void setup() {
      pinMode(button,INPUT);                //button set as input
      pinMode(lowbeam,OUTPUT);              //relays set as outputs
      pinMode(highbeam,OUTPUT);
      pinMode(gate,OUTPUT);

      digitalWrite(lowbeam,LOW);            //initial state as off
      digitalWrite(highbeam,LOW);           //initial state as off
      digitalWrite(gate,LOW);               //initial state as off

    }
    //-------------------------------------------------------------------------
    void loop() {

                                            //debouncing routine to read button
      buttonPoll = digitalRead(button);     //poll state of button
      if(buttonPoll == 1){                  //check if it has been pressed
        delay(50);                          //wait 50msec
        buttonPoll = digitalRead(button);   //poll button again
        if(buttonPoll == 0){                //if it is 0 consider 1 press
          state = old +1;                   //increase state by 1
        }}
      else{                                 //if button has not been pressed
      delay(100);                           //wait 100ms
      }
      switch (state) {                      //react to button press & state
        case 1:                             //if state is 1
          digitalWrite(lowbeam,HIGH);       //lowbeam relay on
          digitalWrite(highbeam,LOW);       //highbeam relay off
          digitalWrite(gate,LOW);
          old = state;                      //set old state as current state
          break;
        case 2:
          digitalWrite(lowbeam,LOW);
          digitalWrite(highbeam,HIGH);
          digitalWrite(gate,LOW);
          old = state;
          break;
        case 3:
          digitalWrite(lowbeam,LOW);
          digitalWrite(highbeam,LOW);
          digitalWrite(gate,HIGH);
          old = state;
          break;
        default:                            //if state if no 1,2,3
          digitalWrite(lowbeam,LOW);        //all relays off
          digitalWrite(highbeam,LOW);
          digitalWrite(gate,LOW);
          old = 0;                          //reset to all off/state 0
          break;
      }
    }


message:
Why am I getting this error- "exit status 1 expected ';' before '{' token "

void setup()
    {

      pinMode{13, OUTPUT};

    }

    void loop() {

      digitalWrite{13, HIGH};

    }

body:
Try parentheses instead of curly braces:

    void setup() {

    pinMode(13, OUTPUT);

    }

    void loop() {

    digitalWrite(13, HIGH);

    }


body:
The solution is already give, but here an explanation:

`{` and `}` are used to group multiple statements together, either for a function, if, while, for loop and so on.

E.g.

    if (i == 1)
    {
      // Statement 1
      // Statement 2
    }

or a function

    void f()
    {
      // Statement 1
      // Statement 2
    }

`(` and `)` are used to specify parameters:

    void f(int a, int b)
    {
      ...
    }

A function with two parameters.

When calling this function, the following is used:

    f(1, 2);

Calls function `f` with `a = 1`, and `b = 2`.

So in general: `{` and `}` is for grouping statements, `(` and `)` for parameters.


body:
I made same mistake when I started working with C

you have

    pinMode{13, OUTPUT};

which should be

    pinMode(13, OUTPUT);

the curly brackets are basically for Start and End of a function.

Bill


message:
Servo not moving

I have connected my servomotor ([MG996R][1]) to my L293D motor shield, which is connected to an Arduino Uno R3 Board.

I use 4x AA 1.2V NiMH batteries to power the shield, and a regular 9V battery to power the Arduino separately. I've removed the jumper wire on the shield.

I've tried uploading all the example codes I could find, multiple times, yet none of them work. The servomotor simply doesn't move at all.

Is there anyway I could see if my servomotor is broken ?
Maybe the wiring is wrong, but I don't think so. Orange is for signal, Red is for + and Brown is for GND.

Could someone help troubleshoot the problem ? Thanks !

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

PS : here is the example code I use

~~~
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}
~~~

body:
You have two problems
Both of them is related to your power supply :

+ 1st, max. Voltage requirement for your servomotor is 6 volts, not 9 volts

+ 2nd، your batteries are weaker than servo's need.
Your servomotor need 2.5 Amps. In the max. Torque.

So, over-voltage and not enough current is your fault
(According to 996R servomotor datasheet).
Change your power supply by suitable one


message:
Problem in defining a variable as multiplication

I have a simplest code to turn on and off a led. The variable holding time definition is `onTime`, using Arduino Nano.

When it is written as: `onTime=1000*30`, all is good.

When `onTime` is greater than this, `if` loop does not return `true` value when needed ( see code below ).

BUT when writing it implicit as `onTime=60000`, and not `onTime=1000*60` code run OK.

I'm guessing that value of 30*1000 - has to be something with `int` value.

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

    int enbPin = 10;
    bool onState = true;
    unsigned long onPeriod = 60*1000; // <----
    unsigned long startTime = millis();
    void setup() {
      // put your setup code hee, to run once:
      Serial.begin(9600);
      pinMode(enbPin, OUTPUT);
      digitalWrite(enbPin, onState);
      Serial.println("START");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (millis() - startTime >= onPeriod ) {
        onState = !onState;
        startTime = millis();
        digitalWrite(enbPin, onState);
        Serial.println(onState);
      }
    }

body:
`unsigned long onPeriod = 60ul * 1000;`

`ul` makes 60 to unsigned long and then the calculation has place for result.

without `ul` the constants and the result are `int` and it overflows


body:
Juraj already told you how to fix this.

Some more info on why:

## (Edited)
By default, the C/C++ compiler uses the smallest size that can hold the specified value for integer constants, starting with the "native" integer size on the platform it's compiling for. For a 16 bit device like an AVR-based Arduino, an int is 16 bits. A signed 16 bit int can hold a value from -32768 to 32767.

(As pointed out by AnT in his comment, if you declare an integer constant of 60,000, the compiler automatically promotes it to the larger long int type.)

It evaluates expressions assuming int constants are of type int unless their value doesn't fit in an int. If you try to do math with an int and a long int, or store the results of int math into a long, the int gets "promoted" to the larger data type first.

In your expression:

    unsigned long onPeriod = 60 * 1000;

The compiler first evaluates the right side of the expression, `60 * 1000`, as `(int)60 * (int)1000)`. Since it treats both parts of that expression as 16 bit signed ints, it does the multiplication using 16 bit integer math. The result of the multiplication is 60,000, which is too large to store in a signed int, so the intermediate calculation overflows.

It then tries to store the result to an `unsigned long`. It promotes the now-overflowed value to an unsigned long and stores the (garbled, and thus wrong) result into the unsigned long destination.

By either expressing either or both values as an unsigned long constant, or casting one or both of them to an unsigned long type, the compiler then promotes both values to unsigned longs before doing the math on them, so the result doesn't overflow before being assigned to the destination variable.


message:
HD44780 DDRAM addressing on the second line

I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.

According to the [datasheet](https://www.sparkfun.com/datasheets/LCD/HD44780.pdf):

>  In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:

```
X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789
```

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

> However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display),
AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?

body:
Your confusion here is mixing "digit" and "byte". The two are not the same.

HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.

20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.

These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate.  There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.

For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.

Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.

If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the *pixel* address, which is 5x what the character address would be after the data has been generated from the internal character set):

    Line 1: 0x02 = 0b00000010
    Line 2: 0x42 = 0b01000010

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:

    Line 1: 0x02 = 0b00000010
    Line 2: 0x2a = 0b00101010

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.

It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".

So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.


message:
Use ATTiny as a battery-backed RAM?

So, I found an interesting article the other day, and I'm trying to build a project that could benefit from a battery-backed memory (no wear limits, but keeps data over power cycling). The article lists how an extremely small current from an LED (acting as a photocell in the lit room) accidentally powered the AVR during a RAM-endurance test.

But, what if this is done on purpose with a battery?

(Article here: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/)

The problem with this idea (since the RAM can already be backed up, as shown in the article, though the author does not seem to have considered this) is that **I need a way to keep an array of memory ignored by the C initializer**. It would be the height of hilarity to have the memory survive the power-off event only to be nuked by the chip's powerup reset code. The listed example at that article would work, for the first requirement, but would break almost anything else I might try to do (since it overrides the *entire* initializer). (Comment on the reset issue: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/#comment-598)

Also, assuming I tried this, would I simply damage the pin rather than provide power? I plan to use a pin continually set to `input` attached to the positive side of a lithium coin cell, with a common ground. In theory, powering the AVR (and I think at any voltage) through the VCC pin would cause the chip's diodes to disconnect the battery, but if it's unplugged, the core would receive enough power to keep the RAM alive.

Of course, my question is whether it would instead stupidly try to keep the core *running* when power is disconnected (in the original article, the nanowatts from the LED couldn't do that, so it's forced to shut down, but I don't know if this is solely due to power limits or if it would shut down the main systems if there's no connection over VCC). In this case, it might try to draw more than the 1mA rating over that parasitic supply, and try to power the entire chip when I don't want it to (thus frying the clamping diode or something equally bad).

I wonder if it would be possible simply to put a large resistor (10K? 1M?) in series with the battery in this case? That would automatically limit the supply to less than 1mA.

body:
Expanding on my previous comment...

> I need a way to keep an array of memory ignored by the C initializer

You can achieve this by instructing the compiler to store the array in
[the “.noinit” memory section][noinit]:

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

    int my_array[ARRAY_LENGTH] __attribute__((section(".noinit")));

Your array will end up sitting somewhere between the .bss and the heap
(if any), and will not be touched by the `__do_clear_bss` routine from
the C startup code.

> my question is whether it would instead stupidly try to keep the core
> _running_ when power is disconnected

Most likely. In order to avoid that, I suggest you enable the [brown-out
detection][bod] by setting the `BODLEVEL` fuses. This feature of the
ATtiny is specifically meant to prevent the CPU core from running if the
supply voltage is below some configurable threshold.

[noinit]: https://www.nongnu.org/avr-libc/user-manual/mem_sections.html#sec_dot_noinit
[bod]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=41


body:
For anyone wanting to know further how I implemented this, I did set the BOD fuse on my device. Still, not wanting that sort of fun (referring to having the chip try to actually _run_ via the backfed power) to happen at all, I wired a 1M resistor in series with the supply backfed through the pin (which was set to INPUT in all cases. HIGH would result in attempting to charge the backup battery, and LOW may well sink the input current and negate the benefits) in an effort to force the current to be high enough to power the RAM but too low for it to run. It also makes sure that too much current cannot flow through the pin.

My results were somewhat inconsistent, and it doesn't help that the device can actually end up powered by whatever indicator LED is added to show that it worked!

Still, there's a good chance that this can be used as an NVRAM if the code is written for it. As for that, just store an array with the values, and write onReceive and onRequest code to index that and send it back out!

Fair warning: If the power bus is connected to other components, the AVR won't keep its memory. Use a diode to prevent power from escaping.


message:
Understanding MOSFET parameters - Dimming/Switching LED strip

I'm trying to create a dimmable/ switchable 12v LED strip using an Arduino board and a MOSFET. Many tutorials can be found doing so such as [this youtube link][1].

I've bought a [LM317T][2] before I had any substantial knowledge regarding MOSFETs. Trying to understand using some tutorials ( each one used different MOSFET ) made it partialy clear what parameters to look for in such project mainly using [this link][3], **but** some left in the dark - and this is the reason for this post ( and to understand why my MOSFET is not suitable ).

I'll compare with one suggested, [FDC855N][4]

1) It has to be "Logic Level" MOSFET, meaning Vgs has to be 5v: from what I **understand**, 0v at the gate you get 0v at the drain and at 5v at the gate you get maximum Vsource. it is correct ?

1a) FDC855N Vgs's value is +/- 20v, how is it Logic Level ? will Vdrain @Vgs=5v will be different when @Vgs=17v ?

1b) Why in FDC855N Vgs have 2 values when Rds(on) is noted?  one is 10V and other is 4.5v ?

2) Vgs(th) stands for minimal voltage needed for current flow at to drain. it is correct ?

2a) why is it noted as @Vgs=Vds ?

3) why Rds(on) is important for ? only for power dissipation purposes ?

I'll be glad to have answers for those question in comparison to the 317T MOSFET, since 317T datasheet has a different terminology :(

Appreciate any help,
Guy

  [1]: https://www.youtube.com/watch?v=k-xC5lQWtGA
  [2]: https://www.onsemi.com/pub/Collateral/LM317T-D.PDF
  [3]: https://electronics.stackexchange.com/questions/36098/selecting-a-mosfet-for-driving-load-from-logic
  [4]: https://www.onsemi.com/pub/Collateral/FDC855N-D.pdf

body:
First of all, the LM317 and the are FDC855N different types of devices.  The LM317 is a voltage regulator whereas the FDC855N is a discrete MOSFET.

A MOSFET will act as a fast switch allowing you to control the LED's brightness using Pulse Width Modulation.

For what you're trying to do, you can think of the MOSFET as a voltage-controlled switch.  If the voltage between the gate and source (Vgs) is greater than the threshold (Vgs(th)), then the current will flow from the drain to the source (Ids).

1) Yes, anything over the typical Vgs(th) of 2.0V, will turn on the switch and cause *current* to flow; you need to provide a voltage across the drain and source (Vds).

1a) 20V is the maximum rating of Vgs, if you applying anything greater, you'll damage the device.

1b)  In reality, the MOSFET is more complicated than just an on/off switch.  The gate to source voltage (Vgs) determines how *hard* the switch is turned on, so increasing Vgs will turn the switch on harder and reduce the resistance (RDS(on)) between the gate and source.

2) Yes, this is essentially correct.  The relationship follows a curve and Vds(th) represents an inflection point.  This plot from page 3 in the datasheet shows the curve for different temperatures.  You can see that the 25C line is basically zero until Vgs reaches about 2.75 volts and then it increases rapidly.

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

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

3) RDS(on) is the resistance between the drain and source when the MOSFET is on.   You can treat the drain to source path like a resistor and use RDS(on) to determine the power dissipation.  For example if your RDS(on) were 0.1 ohm and the current through the drain is 1.5A, then you would be dissipating I^2*R = (1.5)^2*(0.1) = 0.225 , which is below the maximum allowable steady-state power dissipation of the device (Pd) of 0.8 W.


message:
Sizes of the original ESP32-DevKitC-32U Wifi board

I know that this topic does not apply to Arduino, but for me it is important to find a solution to the problem. I know the consequences.

I'm creating a pcb board into which the original ESP32-DevKitC-32U module will be inserted. I can not find the original dimensions of the board, in particular the distance between the contact rails. The site espressif has a small description.

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

27.9mm is indicated here. It is not clear to me, is this the full width of the board or the distance between the contacts?

What I want to do:

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

It is very important for me to find out the correct dimensions of the original board. Maybe someone has such a board and can measure this size?

  [1]: https://i.stack.imgur.com/LDYx9.jpg
  [2]: https://i.stack.imgur.com/GSSy9.jpg
  [3]: https://i.stack.imgur.com/lEHFE.jpg

body: The distance of the headers is breadboard and perfboard compatible for 0.1" (2.54 mm) pin standard. 25.4 mm is 10 rows.


body: I am taking a class and the instructor used a DEVKITC V4, which on a standard breadboard, plugged into columns b and i.  The DEVKITC that I ordered from Mouser plugs into columns b and j.  So one is a pin-to pin width of 25.4 mm and the other is 27.9 mm.  It seems that the newer DEVKITC V4 is 27.9 and is very difficult to work with on standard breadboard.  PITA!


message:
Split serial monitor output to only save part of the output

This is the output i get from the serial monitor from using a HM10 in . How could i go about splitting the data using arduino uno.  I only want to save the last 12 digits before the :- (4CAA0DE091B7) for it to then be in a format to send as an SMS using a GSM module
```
OK+Set:1OK+Set:1OK+RESETOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-042OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:-082
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-089OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-041OK+DISC:00000000:00000000000000000000000000000000:0000000000:56
OK+DISISOK+DISC:00000000:00000000000000000000000000000000:00000OK+DISISOK+DISCEOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-080OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-070OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:000
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-075OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-076OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-078OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-044OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:

```

body:
implement a circular buffer of say 30 characters.

clear the circular buffer

read into the circular buffer, char by char

when the last 13 characters in the buffer are: `:4CAA0DE091B7` Then the prior 12 characters are the data of interest


message:
NRF24 CE and CSN connections without I/O pins easily accessible

I want 2 Arduinos communicating to each other, but only in one direction.  Arduino A = tx  and Arduino B = rx.

I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library.  No problem.

Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:

Arduino A --- put CSN to GND  and put CE to 3.3V
Arduino B --- put CSN to 3.3V and put CE to 3.3V

As to why?  This would simply help me interface the NFR24 to existing custom PCB's I've made which have no ***easy*** access to I/O pins.  My PCB's do have easy access to MISO, MOSI, and SCK.

body:
It seems the CE pin is only used for TX, or to put it into standby. I think you can just connect it to VCC.

The CSN is required for SPI.

PS this [RF24 library](https://github.com/nRF24/RF24/blob/master/RF24.cpp#L18) supports using the same pin for both CE and CSN. You'd have to define `RF24_TINY` for this to work.


body:
No, you really do need the CE pin for both TX and RX modes.  See the following excerpts from the nRF24L01 datasheet.  They work practically the same for nRF24L01+:

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

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

  [1]: https://i.stack.imgur.com/QGxFU.png
  [2]: https://i.stack.imgur.com/qu7dI.png


message:
What type of power supply is the Arduino Due’s 5v pin and what is its current?

I’m looking to use a Futaba Servo with my arduino Due and was told it requires a “high current 5 volt supply” and I don’t know much about current so excuse my arrogance.
I know the arduino Due has a 5 volt pin. **But what type of power supply is it**? (Linear power supply, switching power supply, etc.) and **how much current does it provide**? If I get this information to my instructor he can tell me if it will suffice.

Thank you!

body:
An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, **OR** to the output of a step-down buck regulator converting the DC barrel jack to 5V.

None should be considered "high current" for servo or motor use.

Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.

The buck-converter controller chip is a [LM2434][1], whose datasheet specifies 1A maximum output current.

Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.

If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).

  [1]: http://www.ti.com/lit/ds/symlink/lm2734.pdf


message:
Adafruit Circuit Playground Express interrupt not working

I have interrupts attached to pins 4 and 5 which correspond to the left and right inbuilt buttons on the circuit playground express (https://learn.adafruit.com/adafruit-circuit-playground-express/pinouts). For some reason the right button interrupt works perfectly however the left interrupt doesn't even trigger. Here's the code:

    #include <Adafruit_Circuit_Playground.h>
    #include <Adafruit_CircuitPlayground.h>

    volatile bool leftState = false, rightState = false;

    void left()
    {
        if (CircuitPlayground.leftButton())
            leftState = !leftState;
    }

    void right()
    {
        if (CircuitPlayground.rightButton())
            rightState = !rightState;
    }

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

        attachInterrupt(digitalPinToInterrupt(4), left, CHANGE);
        attachInterrupt(digitalPinToInterrupt(5), right, CHANGE);
    }

    void loop()
    {
        Serial.print(leftState);
        Serial.print("\t");
        Serial.print(rightState);
        Serial.print("\n");
    }

body:
Pin 4 on Zero can't be used with attachInterrupt. It is pin PA08 of the SAMD21 and this has NMI as interrupt control function in EIC and can't be used as EXTINT.

Adafruit Circuit Playground maps PA28 to pin 4, but the description of the pin is left as for Zero and doesn't declare interrupt capability.

In file `arduino/hardware/samd/1.6.21/variants/circuitplay/variant.cpp` change the line for pin 4 to

      { PORTA, 28, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_8  },                           // GPIO D4 / Left Button

Packages are located in ~/.arduino15/packages/ on Linux and %userprofile%\AppData\Local\Arduino15\packages\ on Windows (AppData is a hidden folder).

Warning: In variant.cpp the overview comment's table describes Zero, not Circuit Playground.

Note: It is not beneficial to read a button with interrupt. You can only set some flag in interrupt and then handle it in the loop(). But then you can directlly check in loop the state of the pin, because it will be active many loops even if the user pushes it for a short time.


message:
Multiple defintion error, Linker error

Trying to create an elf file for two sets of files in different folders.

    LIDARBOT.h
    -----------
    #ifndef LIDARBOT_H_
    #define LIDARBOT_H_

    #include <avr/io.h>
    #include "drivers/motors.h"

    #endif

    LIDARBOT.C
    ----------
    #include "LIDARBOT.h"
    int main(){
      pwmtimersetup();
        while (1) {
        }
    }

    motors.h
    --------
    #ifndef MOTORS_H_
    #define MOTORS_H_

    #include <avr/io.h>

    void pwmtimersetup(void);

    #endif

    motors.c
    --------
    #include <avr/io.h>
    #include "motors.h"

    void pwmtimersetup(void){
      // Timer pre-scalar for ~490 Hz is 8
      TCCR0B &= ~((1<<CS02)||(1<<CS00));
      TCCR0B |=  (1<<CS01);
      // Set Compare Output Mode to Toggle PWM
      TCCR0A &= ~(1<<COM0A1);
      TCCR0A |=  (1<<COM0A0);
      // Waveform Generation Mode: WGM02 = 1, WGM01 = 1, WGM00 = 1
      TCCR0B |= (1<<WGM02);
      TCCR0A |= (1<<WGM01)||(1<<WGM00);
      OCR0A = 125;
      DDRD |= (1<<DDD4)||(1<<DDD2);
      PORTD |= (1<<PORTD4);
      PORTD &= (1<<PORTD2);
    }

I can make a consolidated object file but not an elf file to load onto my board. Output below:

    avr-gcc -g -Os -Wall -Werror -Wextra  -mmcu=atmega328p -DF_CPU=1000000UL -Wa,-ahlmns=LIDARBOT.lst -o objects/LIDARBOT.o \
    source/LIDARBOT.c \
    source/drivers/motors.c \
    -I/home/manu/C/Arduino/LIDARBOT/libraries/

    avr-gcc -g -Os -Wall -Werror -Wextra -mmcu=atmega328p -DF_CPU=1000000UL -o elf/LIDARBOT.elf objects/LIDARBOT.o
    objects/LIDARBOT.o: In function `__vector_22':
    (.text+0x7c): multiple definition of `__bad_interrupt'
    /usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.text+0x0): first defined here
    objects/LIDARBOT.o: In function `__vectors':
    (.text+0x0): multiple definition of `__vectors'
    /usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.vectors+0x0): first defined here
    collect2: error: ld returned 1 exit status
    make: *** [Makefile:191: elf] Error 1

I am kind of lost. What could be my mistake here? If I see an error like this how do i start to debug?

body:
You forgot the -c flag to your first command. That means you have first compiled your program into a full elf file. Then you try to link that elf file with the standard startup libraries again (it already contains them) into another new elf file.

And so you get duplicate entries in it.

Add -c to your first command, which means "compile only, don't link" to create object files not an elf file.


body: Thank you guys for your input, AnT and Majenko. I realized my issue which was trying to link a .o file into another one. So I corrected my make file by individually compiling but not linking the source files with the -c option. I then made my final elf file using the unlinked .o files.


message:
Sharing serial output from one to many arduinos (plus a computer) via USB hub

I am trying to send rotary encoder output from an UNO to seven Trinket M0s *and* a computer via a (powered) USB hub.

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

Currently the UNO → Laptop bit works great, serial monitoring works via the hub for everyone and I'm able to get a master/slave connection going between the UNO and a Trinket via Arduino's Wire library. But Wire uses pins, and I haven't had any luck finding a similar solution for USB. Thus far, the best leads seem to be around using something like `stty` in a bash script to [listen for what each port is up to](https://arduino.stackexchange.com/questions/19002/use-unix-terminal-instead-of-the-monitor-on-arduino-ide) but I'm so far in over my head at this point that that might just be wishful thinking.

I'm not looking for a solution here, just some suggestions as to where to head next. Specifically:

1. Is the Wire library useful for USB communication?  Is there something similar (master/slave-wise) that would be helpful?
2. Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like `$ echo $encoderVal > /dev/cu.usbmodem?????` to each one individually ... but that might be a completely noobish notion.)
3. i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?
3. Is this all completely nuts?

Anyways, thanks to everyone in advance.

# Update
Ok! Thanks to the advice of @Gerben and @chrisl I ended up routing everything around with [PySerial](https://github.com/pyserial/pyserial), and (for the extremely limited purposes of this little project) it works well! Here's what is currently working:

```lang-python
import serial
from time import sleep
import os

# Connect to each Arduino individually
serialUno = serial.Serial("/dev/cu.usbmodem141101", 9600, timeout=0)
serialTrinket1 = serial.Serial("/dev/cu.usbmodem1414401", 9600, timeout=0)
# (+ 6 more. serialTrinket2, serialTrinket3, etc)

# Open a text file to save the encoder value in
f = open("encoderVal.txt", "w")

while True:
  # Read encoderVal from the UNO
  data = serialUno.read(9999)
  if len(data) > 0:

    # Send data to each trinket
    serialTrinket1.write(data)

    # Save val to text file to Unity
    with open('encoderVal.txt', 'r+') as f:

      # Wipe the file so it's only the most recent value
      f.truncate()
      dataStripped = data.strip()

      # Return the last int in the data stream
      dataSplit = dataStripped.split('\n')
      f.write(dataSplit[-1])

  sleep(0.05)

# Close serial connections & file on interrupt
serialUno.close()
serialTrinket1.close()
f.close()
```
As for the laptop end of the equation, I abandoned the serial library that I _had_ been using in favor of [this Unity-to-Python tool](https://github.com/off99555/Unity3D-Python-Communication), which works perfectly.

The only issue thus far is that PySerial loses the occasional few bytes here and there, which outputs a wonky number ever 30 or so. That'll be tomorrow's project.  Thanks everyone for your help!

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

body:
First, read a bit about USB, it is an entire protocol, not just a hardware/pin based interface. It is actually quite involved. Then it will be clearer to you why a USB (from the Nano) solution will be... difficult.

Based on my understanding, I would use your #2 idea and what has been suggested, and do the following...

1. Setup the Uno as a USB slave, not a master.
2. Using the PC, connect to the Uno and the Trinkets.
3. When the PC gets data from the Uno have the PC "repeat" it to the Trinkets.

I think this will be the easiest and quickest solution.