body:
I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.

**Arduino Code:**

    void send_rec_data(){

        Serial.print(Kp);
        Serial.print(",");
        Serial.print(Kd);
        Serial.print(",");
        Serial.print(Ki);
        Serial.print(",");
        Serial.println(Theta_x);

        delay(20);

      if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

        str_data = Serial.readString();

        int firstCommaIndex = str_data.indexOf(',');

        cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

        param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

        Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

        blink_led(); // Blink LEDS if data is received from Raspberry Pi

      }

    }

**Python Code:**

    while 1:

        data = cont.get_serial_data(arduino)

        time.sleep(0.02)

        if data is not None:

            Kp, Kd, Ki, Theta_x = data

            print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

            cont.set_tunings(Kp, Kd, 0)

            Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

            ff = str(Output_scaled)+','+str(cont.error)

            arduino.write(ff.encode())

            print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

    arduino.close()

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.

Thanks.

title: Data transfer to and from Arduino to Raspberry Pi

Answers: 2

body:
Ok, without rewriting all your code, one thing I'm seeing here is a lot of *sloooow* string functions.

Pythons print function is extremely slow, for example. You should insert some timers in your code and see how long everything's taking. I think you will be surprised.

For a real-time application, which it sounds like this is, you need to be very careful and use timeouts and non-blocking code to make sure that everything doesn't grind to a halt unexpectedly.

You really need to re-write all this code, but I'll point out a few specific problems.

    delay(20);
    if (Serial.available()>0){
       ...
    }

This is sloppy. If your python code does not process and return data before the 20ms elapses everything is going to go out of sync.

    str_data = Serial.readString();

A look at the documentation reveals that this will only return on timeout, so this is guaranteed to block for 1s (I think that's the default), so there's another show-stopper problem. See [this question][1] for more info.

    cmd = str_data.substring(0, firstCommaIndex);
This is also not sufficient. There is no synchronization between the pi and the arduino, so you have no guarantee that you won't get half of a previous transmission tacked onto the front of your data string (or worse). You need to make your own buffer and parse for the datastring. Or do some careful buffer clearing and use generous timeouts.

  [1]: https://stackoverflow.com/questions/42863973/arduino-readstring-code-runs-slow

So TLDR; here's what you want to do (assuming you want to block while this exchange happens)

 1. Clear the arduino receive buffer.
 2. Send data packet from arduino.
 3. Start receiving. Add received bytes to a char buffer.
 4. Continuously search that buffer for your complete data packet.
 5. Timeout after x ms. Handle the lack of returned data somehow.
 6. If you do find the complete data packet, then process it.

On the Pi:

 1. Poll for serial data. Add it to a buffer as it comes in.
 2. Start deleting the oldest characters from the buffer if it's longer than 2x the longest data packet
 3. Continuously search the buffer for your data packet. If you find it then continue below.
 4. delete the data packet from the receive buffer.
 5. process the data.
 6. Send out return data packet to arduino.

body:
Thank you every one. I read through [this forum](http://forum.arduino.cc/index.php?topic=396450) and it also says the same things which you guys also suggested. I did the same thing and now everything is fast.

    Serial.readString()
is indeed the problem.


body:
I am following the instructions from this page to set up RS485 communication between two Arduinos.

https://arduino-info.wikispaces.com/SoftwareSerialRS485Example

My wiring varies slightly from the demo in that;

DI (data in)is Pin 18 (11 in the example)
RO (receive out) is pin 19 (10 in the example)
DE (data enable) and RE (receive enable) jumpered together and to pin 5

When I use the script, I can see the built in LED go dark when sending, but I don't get the echo back, nor do I see the LED on the remote blink for the receive.

Is there a fundamental problem with the pins I am using on the MEGA, or am I having difficulty with the script?

Thanks!

title: Arduino Mega RS485

Answers: 1

body:
I don't know what is wrong with your setup, but I suggest you start by
testing with a simpler program.

Below is a program that simply copies bytes from the USB link (the bytes
coming from the Arduino's serial monitor) to the RS-485 bus, or the
other way around depending on a `#define`. Both Arduinos should be
connected as follows:

    Arduino     transceiver
    --------------------------------
    GND         GND
    5V          VCC
    TX1 (18)    DI (driver input)
    RX1 (19)    RO (receiver output)

Additionally, connect:

* on the sending side:
  - the USB plug to your computer
  - the transceiver's DE (driver output enable) and RE (receiver output
    enable) to the Arduino 5V
* on the receiving side:
  - the transceiver's DE and RE to the Arduino GND

Make sure both Arduinos are powered and share a common ground.
Optionally, you can connect the receiving Arduino to your computer, if
you can manage to tell the USB links apart.

Then load the program below to both of them. Make sure you comment-out
the line `#define SENDER` before programming the receiver.

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

    // The "sender" copies bytes from the USB link (Serial) to the RS-485
    // bus (Serial1). The receiver copies them the other way around.
    // Comment-out this line for the receiver.
    #define SENDER

    #ifdef SENDER
    HardwareSerial &inputStream  = Serial;
    HardwareSerial &outputStream = Serial1;
    #else
    HardwareSerial &inputStream  = Serial1;
    HardwareSerial &outputStream = Serial;
    #endif

    void setup()
    {
        inputStream.begin(9600);
        outputStream.begin(9600);
        pinMode(LED_BUILTIN, OUTPUT);  // used to show activity
    }

    void loop()
    {
        // Copy input stream to output stream.
        if (inputStream.available()) {
            digitalWrite(LED_BUILTIN, HIGH);
            outputStream.write(inputStream.read());
            outputStream.flush();
            digitalWrite(LED_BUILTIN, LOW);
        }
    }

Now you can test sending strings through the serial monitor and
seeing whether both LEDs blink. If you connect both Arduinos to your
computer, you could use a terminal emulator (screen, putty, minicom...
depending on your OS) to get the characters back from the receiving
Arduino.

If all that fails, get a scope and look at all the signals along the
path.


body:
I am using the [rc-switch library](https://github.com/sui77/rc-switch) for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.

    send_string("Hello World!");
    ---------------------------

    void send_string(const char *str)
    {
    int i = 0;

    for (char *p = str; *p; p++ ) {
    mySwitch.send((i<<8) + *p, 16);
    i++;
    }
    mySwitch.send((i<<8) + 255, 16);
    }

And I am receiving is using this **Serial.print((char)mySwitch.getReceivedValue());** build in method. But I am getting this message.

    H
    H
    H
    e
    e
    e
    l
    l
    l
    l
    l
    l
    o
    o
    o

    W
    W
    W
    o
    o
    o
    l
    l
    l
    d
    d
    d
    !
    !
    !

Now how can I get my original message?

title: How to transmit string data using the rc-switch library?

Answers: 1

body:
The communication protocol used by this library is unreliable. Thus,
each code word is sent multiple times, [10 times by
default][setRepeatTransmit]. One solution around this problem is to send
a “byte number” along with each byte you transmit. You would then
transmit 16-bit words, where the MSB (most significant byte) is the byte
number, and the LSB is the actual byte you want to transmit. Something
like this:

    int i = 0;
    for (char *p = str; *p; p++) {
        mySwitch.send((i<<8) + *p, 16);
        i++;
    }

Oh, wait! That's exactly what you are already doing! So it appears that
you are already aware of this issue and you have even implemented a
solution. How come you are asking this question then?

OK, I'll assume in the following that you just forgot to tells us that
the code snippet above is not from you, and that you didn't even
understand what it is doing. And you also forgot to provide a link to
the source of that code. Please, next time read [How do I ask a good
question?][how-to-ask] before asking, and provide all the relevant
information right in the question.

So now the problem is in the reading side. You have to use those byte
numbers to remove the duplicates. One (untested) solution could look
like this:

    // Return a received byte, or -1 if none is available.
    int receivedValue()
    {
        if (!mySwitch.available())  // no byte available
            return -1;
        static uint8_t last_byte_number = 0xff;
        uint16_t code = mySwitch.getReceivedValue();
        uint8_t this_byte_number = code >> 8;
        if (last_byte_number == this_byte_number)  // this is a duplicate
            return -1;
        last_byte_number = this_byte_number;
        return code & 0xff;  // LSB is the byte to return
    }

And you could use it to print the data on the serial monitor like this:

    int c = receivedValue();
    if (c != -1)  // if we really got a new byte
        Serial.write(c);

[setRepeatTransmit]: https://github.com/sui77/rc-switch/blob/2.6.2/RCSwitch.cpp#L103
[how-to-ask]: https://arduino.stackexchange.com/help/how-to-ask


body:
I have been trying to construct a smart energy meter that can observe readings of 220v household. For now i am working on voltmeter. I have been following the circuit I attached. Transformer step down 220V to 6V. Zener diode is of 5V.
The output from the circuit( 5v max) is fed to arduino Mega 2560 A0 pin.
* I am powering arduino using a USB cable *
Arduino takes this voltage as input from pin A0 in form of analog values between 0 to 1023. 0 being 0 volt and 1023 being 5v.So any ran[![enter image description here][1]][1]dom analog value corresponds to X=(5/1023)*Y where Y is obtained analog value. X is then multiplied by a value obtained by hit and try method (165 in my case) to reach the exact reading of voltage in line observed via multimeter.
Now the problem is that, everything works fine when i calibrate it, but after some time when i switch circuit on the value is inaccurate by margin, and i have to calibrate it again and again every time I turn circuit on after some time.If i switch circuit on soon after switching it off, it gives almost accurate value. *I guess this issue is due to the capacitor, but i don't know anything about it or how to solve it* I have constructed the same circuit more than 5 times, soldering it 3 times and 2 times on bread board and i am sure there is no problem with my implementation, verified it many times.
this is my code:

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

    float V; // Voltage samples
    float V0;

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

    void loop() {
      for(int i=0; i<=20000; i++){
        V = V + analogRead(A0);
      }
      V = V / 20000;
      V = round(V);

      float V0 = V * (5.0 / 1023.0);
      I0 = I0 * 165; // has to be callibrated again and again each time circuit is switched on after a while

      Serial.print("Voltage = ");
      Serial.print(V0);
      Serial.println(" -------------- ");
      delay(1500);
    }

this is the link i am following
http://engineerexperiences.com/3-phase-smart-energy-meter-using-arduino.html

Any help would be appreciated, Thanks!
[1]: https://i.stack.imgur.com/kKhFd.jpg

title: Voltmeter using Arduino mega 2560 giving unexpected result after some time

Answers: 2

body:
With that circuit you can expect a roughly 10% variance in the output voltage depending on the exact moment at which you sample the voltage.

The basic circuit you have, and the waveforms generated, are like this:

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

That green waveform is the one you are reading. As you can see, exactly where you sample defines what the result will be.

Since you're trying to average over an undefined period (20,000 samples of how long per sample exactly?) you're not going to get a particularly well defined output.

You should change your sampling strategy to perform multiple samples over a well defined period to find the *maximum* value. That is the value you should then use in your calculations.

Ideally, you want to repeatedly sample for *at least* one entire waveform cycle. At 50Hz that's a period of 20ms (17ms for 60Hz).

For example:

    uint16_t maxval = 0;
    uint32_t ts = millis();
    while (millis() - ts < 20) {
        uint16_t val = analogRead(0);
        if (val > maxval) {
           maxval = val;
        }
    }

    // Use "maxval" in your calculations.

With this strategy, because you're looking for the *peak* value, you don't care about the impact that the capacitor has on the circuit (except that it will remain artificially high for a period if the voltage drops), so you could actually simplify the circuit and remove that capacitor completely.

  [1]: https://i.stack.imgur.com/TpDGN.gif

body:
I just wanted to add some points to what Majenko already said.

You are making a measurement device, so you need a precise reference. So why are you using the 5V reference?

Your 5V in your circuit is assumed to be stable. But is it? Maybe some time you are using the PC to power it, then you attach a lot of loads to the USB ports, then you use a wall USB power supply. Every time the 5V can change (see [here][1] for instance). A variation in the supply of +/-5% will be translated in a +/- 12V for a 240V input (I don't know if this is above or below your expected accuracy).

The solution is to use the internal reference, which is an internal peripheral used explicitely for measuring analog sources.

In your case (Arduino MEGA 2560) you have a 1.1V or a 2.56V internal references. Your transformer is a 240->6V transformer, which means the value you should read after it is around 8.5V (6Vrms has a peak of 6*1.415 = 8.5V). After the voltage divider, this becomes 1.53 V. Consequently you can use the 2.56V reference in this case. To do so write, in your setup function, `analogReference(INTERNAL2V56);`. Then your readings will be relative to 2.56V rather than 5.0V (so `float V0 = V * 2.56 / 1023.0;`).

(Note: the way to implement this was taken from [the arduino reference manual][2]; I never implemented it, so it may require tweaking)

  [1]: https://electronics.stackexchange.com/questions/12935/stability-of-usb-5v-output
  [2]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


body:
i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...

is this function sufficient to get a debounced state of the pressed button?

    byte buttonPressed(){
      byte btn = 0;
      if (digitalRead(30)==LOW) btn = 1; else
      if (digitalRead(9)==LOW) btn = 2; else
      if (digitalRead(31)==LOW) btn = 3; else
      if (digitalRead(8)==LOW) btn = 4;
      delay(20);
      return btn;
    }

any strictly necessary improvements are welcome...

title: minimal code for multiple buttons de-bouncing

Answers: 4

body:
No. Actually it just checks each button one by one. In addition only the last button is checked since it overwrites the btn variable.

The simplest way to use debouncing button 1 is:

    byte buttonPressed()
    {
        byte btn = 0;

        byte btn1Before = digitalRead(30);
        delay(50); // Wait 50 ms, or 100 depending on your debouncing time
        byte btn1After = digitalRead(30);

        if ((btn1Before == LOW) && (btn1After == LOW))
        {
            btn = 1;
        }
    }

You have to do similar as the others. You can use only one delay (just add 4 before and after variables and check them.

    byte buttonPressed()
    {
        byte btn = 0;

        byte btn1Before = digitalRead(30);
        byte btn2Before = digitalRead( 9);
        byte btn3Before = digitalRead(31);
        byte btn4Before = digitalRead( 8);

        delay(50); // Wait 50 ms, or 100 depending on your debouncing time

        byte btn1After = digitalRead(30);
        byte btn2After = digitalRead( 9);
        byte btn3After = digitalRead(31);
        byte btn4After = digitalRead( 8);

        if ((btn1Before == LOW) && (btn1After == LOW))
        {
           btn = 1;
        }
        else if ((btn2Before == LOW) && (btn2After == LOW))
        {
           btn = 2;
        }
        else if ((btn3Before == LOW) && (btn3After == LOW))
        {
           btn = 3;
        }
        else if ((btn4Before == LOW) && (btn4After == LOW))
        {
           btn = 4;
        }

        return btn;
    }

Note that this way the program will be unresponsive for 50 ms. If you do not want this, you have to use millis, but this makes it more complex. Check the debouncing example on the Arduino site.

body:
No - simply `delay()`ing after reading the button doesn't tell you whether the button is still bouncing or, more importantly, what its final state is. Debouncing requires you to know that the button

 - changed state;
 - has stopped changing state;
 - what state it has settled into.

You'll need to notice the current state doesn't match the last debounced state you saw; then either test it frequently until it doesn't change state again for some number of tests, or simply wait the known maximum time it takes to settle; then read, store, and return the final state.

body:
While @MichelKeijzers answer is a nice solution for simple querying in the main loop. This is not practicable for interrupts. Interrupts can block the entire MCU and interrupting an interrupt routinte can cause serious problems.

Depending on your requirements I'd suggest to take a look at using [capacitors and resistors for debouncing](https://electronics.stackexchange.com/questions/66764/how-does-the-capacitor-in-a-debouncing-circuit-work#66767). With that you achieve simpler code and no need for dealing with hardware issues in software. Of course at the expense of additional parts in your hardware setup.

If your MCU for example is using a pin as interrupt, that interrupt would be called only once as opposed to bouncing one.

body:
Yes, your code should work as the most basic debouncing, although the
debouncing time may be a little bit short. Note however that, in many
instances, one would like to have a little more that the most basic. One
may also want:

* _deglitching_: when the button is held down, your hand may make the
  contacts move a little bit, making spikes in the reading that are not
  associated with a real change in the button position; you don't want
  those spikes to read as "released and pressed again"
* _edge detection_: many times you are more interested in the button
  press event than in knowing whether the button is down or up; this can
  be handled by another function, but it can be convenient to integrate
  it with the debouncing
* _non blocking operation_: your program may have better things to do
  than wasting CPU cycles inside `delay()`.

Those are the reasons most debouncing codes are significantly more
complex. But it's often worth it.

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

**Edit 1**: In view of the comments, some clarification seems to be
needed. There are two kinds of glitches a mechanical button can
experience:

1. when the button is mechanically changing position, i.e. it is being
   depressed or released; this is called a _bounce_
2. when the button is being held down, especially if the pressure on the
   button is low and the finger applying that pressure is somewhat
   shaky.

Most debouncing libraries you can find actually address both kinds of
glitches. Thus, they do _more_ than just debouncing, they do what I
called “deglitching”. The previous answers implicitly assume that a
proper debouncing code _must_ address both kinds.

The code posted in the question only addresses the first kind of
glitches, i.e. the _bounces_ in the strict sense. That's why I wrote
that it does the “most basic debouncing”. It is however susceptible to
the second kind of glitches. So yes, with this code glitches can persist
even after debouncing.

**Edit 2**: As an example, consider the [Bounce 2][] library. It
provides edge detection, non blocking operation and, in the default
configuration, full deglitching. However, [it can be configured to use
an alternative debounce algorithm][algorithms] called “Lock-out
interval”, which is more responsive but does not protect against the
“type 2” glitches mentioned above: it “does not cancel noise”, as the
documentation puts it.

[Bounce 2]: https://github.com/thomasfredericks/Bounce2

[algorithms]: https://github.com/thomasfredericks/Bounce2/wiki#debounce-algorithms


body:
I've just started working with the Arduino UNO SMD edition and I'm also quiet new to electronics in general. Recently I wanted to try out this tutorial https://www.arduino.cc/en/Tutorial/Button and I ran into a problem with the pull-down resistor. In the tutorial they recommend a 10kOhm resistor but I've got only 460Ohms laying around. Obviously I could link dozens of them in series but I was wondering if it is possible to replace this 10k resistor with 460 Ohms. Would that be enough? I'm assuming, that the 5V Output can supply up to 500mA (datasheet) and the ground can take up to 500mA. Following Ohms Law I = U/R given 460Ohms there should be a current of 11mA flowing. Is it correct that the ground can take this amount of current?

Hope you can answer my question and may point out mistakes i made.

Greetings Tmirror

title: Minimum value of a pull-down resistor

Answers: 1

body:
Why are you messing with pulldown resistors at all? Use the internal pullup resistor instead.  Connect your button between the pin and Gnd so the pin goes low when pressed.

Here's a simple code example:

    byte inputPin = 2;

    void setup(){
        pinMode (inputPin, INPUT_PULLUP); // turns on internal pullup
        Serial.begin(9600);
    }

    void loop(){
        if (digitalRead(inputPin) == LOW){
            Serial.print ("button pressed");
        }

        else {
            Serial.print ("button open");
        }

        delay(200);  // limits reading to 5 times a second to avoid flooding the PC with messages

    }


body:
I am new to using SPI with an Arduino. But I'm trying to wrap my head around the "coding protocols"/syntax of the Arduino IDE code. I understand the basics of how SPI works conceptually, just not how to actually use it with an Arduino Mega 2560. Most examples on YouTube are about how to play with LEDs and the examples on the Arduino blogs are very specific for two specific examples.
Analog reading is incredibly easy (which is what I am used to doing).

I have an AllSensors DLHR-L05D 18 bit differential pressure sensor (SPI, not I2C) [Datasheet: https://www.allsensors.com/cad/DS-0350_Rev_B.PDF]. Page 5 has the commands needed. From my understanding, I need to somehow send from the Arduino to the sensor a "start" sequence (0xAA) and a "read" (0xF0 and 0x00) sequence, but I'm not sure what that looks like when coding it.

Any and all advice/direction on how to "code up" this SPI device would be greatly appreciated!

title: DLHR differential pressure sensor SPI

Answers: 1

body: Turns out, someone actually has a specific library to handle the I2C for this sensor, which helps tremendously: https://github.com/jeremycole/AllSensors_DLHR


body:
I have used `attachInterrupt()` to reset my program to the beginning. It actually interrupts while running the 3 states as shown below inside of the `if` statement but when I press the actual button it does not exit, it goes to the function and continuing to the next state. It only works (means exiting/resetting) after all three states have executed completely.

    if(buttoncount<2){
      originalstate();
      alertstate();
      evacuationstate();

I would like to make a button to stop the program while running in the middle and start again.

Code:

    // Declaring pins

    // Input pins
    const int sensor1button_pin = 6;
    const int sensor2button_pin = 3;
    const int sensor3button_pin = 4;
    const int sensor4button_pin = 5;
    const int sensor5button_pin = 2;
    const int sensor6button_pin = 15;
    const int sensor7button_pin = 15;

    // Output pins
    const int led1_pin = 8;
    const int led2_pin = 9;
    const int led3_pin = 10;
    const int led4_pin = 11;
    const int buzzerpin = 15;

    // Initialy buzzer at false mode
    boolean flag1;
    boolean flag2;
    int flag3 ;

    // for leds
    int ledState1 = LOW;   // Original
    int ledState2 = LOW;   // Alert
    int ledState3 = LOW;   // Evacuate
    int ledState4 = LOW;   // Isolate

    // Buttons
    int button1_state = LOW;
    int button2_state = LOW;
    int button3_state = LOW;
    int button4_state = LOW;
    int button6_state = LOW;
    int button7_state = LOW;
    int button5_state = LOW;

    // Other variables
    int buttoncount = 0;
    int reset_switch=0;

    void setup() {
      // INPUT pins
      pinMode(sensor1button_pin, INPUT);
      pinMode(sensor2button_pin, INPUT);
      pinMode(sensor3button_pin, INPUT);
      pinMode(sensor4button_pin, INPUT);

      pinMode(sensor5button_pin, INPUT_PULLUP);

      attachInterrupt(digitalPinToInterrupt(sensor5button_pin), clearreset, CHANGE);

      pinMode(sensor6button_pin, INPUT);
      pinMode(sensor7button_pin, INPUT);

      // OUTPUT pins
      pinMode(buzzerpin, OUTPUT);
      pinMode(led1_pin, OUTPUT);
      pinMode(led2_pin, OUTPUT);
      pinMode(led3_pin, OUTPUT);
      pinMode(led4_pin, OUTPUT);

      Serial.begin(9600);
    }

    void loop() {
      button1_state = digitalRead (sensor1button_pin);
      button2_state = digitalRead (sensor2button_pin);
      button3_state = digitalRead (sensor3button_pin);
      button4_state = digitalRead (sensor4button_pin);
      button5_state = digitalRead (sensor5button_pin);
      button6_state = digitalRead (sensor6button_pin);
      button7_state = digitalRead (sensor7button_pin);

      Serial.println(digitalRead (sensor5button_pin));

      if( button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
        delay(280);
        buttoncount = buttoncount + 1;
      }

      if (button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
        if(buttoncount<2){
          originalstate();
          alertstate();
          evacuationstate();
        }
      }
    }

    // LED lighting arrangements
    void originalstate() {
      digitalWrite(led1_pin, HIGH);
      digitalWrite(led2_pin, LOW);
      digitalWrite(led3_pin, LOW);
      digitalWrite(led4_pin, LOW);
      delay(1500);
    }

    void alertstate() {
      digitalWrite(led1_pin, LOW);
      digitalWrite(led2_pin, HIGH);
      digitalWrite(led3_pin, LOW);
      digitalWrite(led4_pin, LOW);
      delay(1500);
    }

    void evacuationstate() {
      digitalWrite(led1_pin, LOW);
      digitalWrite(led2_pin, LOW);
      digitalWrite(led3_pin, HIGH);
      digitalWrite(led4_pin, LOW);
      delay(1500);
    }

    void isolatestate() {
      digitalWrite(led1_pin, LOW);
      digitalWrite(led2_pin, LOW);
      digitalWrite(led3_pin, LOW);
      digitalWrite(led4_pin, HIGH);
    }

    // Clear or reset back to the begin

    void clearreset() {
     button1_state = LOW;
     button2_state = LOW;
     button3_state = LOW;
     button4_state = LOW;
     button5_state = LOW;
     button6_state = LOW;
     button7_state = LOW;

     digitalWrite(led1_pin, LOW);
     digitalWrite(led2_pin, LOW);
     digitalWrite(led3_pin, LOW);

     buttoncount = 0;
     exit;
    }

title: Using attachInterrupt() to make a reset button for my code?

Answers: 3

body:
You need non-blocking code in combination with a finite state machine:
 1. **Non-blocking code:** You should not use `delay()`, since it is just busy waiting. Instead use the `millis()` function to measure the time distance between the last execution of the code part and the current time. If it has reached a certain level (like 1500ms), execute the code and save the current time in a timestamp as a reference for the next execution. Refer to the `BlinkWithoutDelay` example of the Arduino IDE. There are also many tutorials for that on the internet, so I will not explain this further here.
 2. **Finite state machine:** Here your `loop()` function contains of a `switch` statement with a (mostly numerical) state variable as parameter. Every case contains only the code for its special case. To get from one state to another you would just change the state variable to the corresponding value. You can also do this in an ISR (if you set the state variable as `volatile`). If you non-blocking code as described above, the `loop()` function is executed very fast, so that the change of the state variable inside the ISR takes effect almost immediately (delay will not be sensable by a human). Something like this:

    volatile int state=0;

    void isr_function(){
        state++;
        if(state>1) state=0;
    }

    void loop(){
        switch(state){
            case 0: // state 0
                do_something();
                break;
            case 1: // state 1
                do_another_thing();
                break;
        }
    }

Note: Depending in your target you may want to add code for button debouncing, so that one button press is really sensed as one press, not more. This is relevant most times you have non-blocking code. Debouncing has been described many times in the internet, so just Google it

body:
You should enable verbose compilation in the IDE. You will then have a
chance to see this compiler warning:

    warning: statement is a reference, not call, to function ‘exit’
      exit;
          ^
    warning: statement has no effect

Naming a function without calling it is a way to get a pointer to the
function. It's equivalent to `&exit`. But since you do nothing with that
pointer, the statement has no effect, and that's exactly what the
compiler is warning you about.

You presumably want to _call_ the `exit()` function, like in:

    exit(0);

**Edit**: That being said, `exit()` is probably _not_ what you want.
This function just stops your program by putting it in an infinite loop.
If you want it to restart from scratch, you can first declare

    extern "C" void __init();

then, instead of `exit(0);` call `__init();`. This will send your
program to the beginning of the initialization code from the C runtime,
which is responsible of resetting the stack and initializing the memory
(.data and .bss sections). Note that this is _not_ equivalent to a
hardware reset because:

* doing this does not run the bootloader
* more importantly, it doesn't reset the IO registers of the peripherals
  to their default reset state.

body:
>  ... .any way, I can interrupt the program while running and change to any other function of the program. such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

Interrupt will not help you achieve your requirement. You want to 'reset the state' of your running sketch. But after the interrupt the MCU returns in the code where it was before interrupt and continues.

You should implement the 'reset of the state' in your algorithm. In a loop of a non-blocking sketch you can check the button and if it is pressed, then 'reset the state' of the sketch.


body:
**Problem:**

In short, the Arduino IDE won't compile a sketch for the Teensy 3.6. It gives the error:

    exec: "A:\\arduino-1.8.5\\hardware\\teensy/../tools/teensy_post_compile": file does not exist
    Error compiling for board Teensy 3.6.

**What I have tried**

-Re-installing teensyduino (And yes, I have it installed, along with a compatible Arduino IDE (version 1.8.5))

-completely wiping the IDE and re-installing

-using a different USB cable

**Other information**

The OS I'm using is Windows 10

A broken Teensy is not out of the question, as I have been doing some soldering on it and I may have slipped or something, although I don't think that's the problem

Thanks in advance.

title: Error compiling to teensy 3.6

Answers: 1

body:
I found a fix, it's not elegant or easy to use, but it works.

**Steps to take**

-Install a fresh version of teensyduino

-Make a copy of `[arduino directory]/hardware/tools` and save it anywhere as a backup (sometimes weird, buggy things happen)

-Make a copy of `teensy.exe` from the `tools` folder, and put it in the same directory as `arduino.exe`

-every time you run `arduino.exe` (don't double-click on a `.ino` file), first start `teensy.exe` and everything _should_ work.

Sometimes, the `tools` directory gets deleted (It just seems a bit buggy), if that happens copy the backup and paste it where it should be (`[arduino directory]/hardware/tools`)

Also occasionally `teensy.exe` gets deleted, so make sure to have a backup of that as well.


body:
I developed a code for uart based ISR with linear buffers, the problem is that it keep sending the last received char in Arduino IDE.

Here's the application code:

    #include "uart_new.h"

    void setup() {
    uart_init_new(103);
    DDRB = 0xff;
    }

    void loop() {
    uint16_t c;
    c = get_char();
    if (c & NO_DATA)
    {
      PORTB |= (1<<PB5);
      _delay_ms(500);
      PORTB &= ~(1<<PB5);
      _delay_ms(500);
    }
    else
    {
      put_char(c);
    }
    }

The header file:

    #ifndef uart_new_H_
    #define uart_new_H_

    #define NO_DATA     0x0100
    #define Buf_OF      0x0200
    #define FR_Er       0x0400
    #define DOR_Er      0x0800
    #define PARTY_Er    0x1000

    #define buf_s 32
    #define buf_mask Buf_s - 1
    #define baud_rate 9600

    void uart_init_new(uint16_t ubrr);
    void put_char(uint8_t data);
    uint16_t get_char(void);
    void put_s(uint8_t *str);

    #endif // uart_new_H_

The source code:

    #include <avr/io.h>
    #include <Arduino.h>
    #include "uart_new.h"

    /*******************************************
    If you want to prevent reading a string
    backwards then you need FIFO implementation
    *******************************************/

    static volatile uint8_t rx_buf[32],tx_buf[32];
    static volatile uint8_t rx_p,tx_p,rx_cnt,tx_cnt;
    static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

    void uart_init_new(uint16_t ubrr)
    {
        rx_p=0,tx_p=0,rx_cnt=0,tx_cnt=0;
        UBRR0H = (uint8_t)(ubrr>>8);
        UBRR0L = (uint8_t)ubrr;
        UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); //Enable Rx and Tx & Receive interrupt
        UCSR0C = (1<<USBS0)|(3<<UCSZ00);            //Set frame format: 8data, 2stop bit
    }

    uint16_t get_char(void)
    {
        if (rx_cnt == 0)
            return NO_DATA;
        else if (rx_p < rx_cnt)
            return rx_buf[rx_p++];
    }

    void put_char(uint8_t data)
    {
        if (tx_cnt < 32)                        // start count the input data
            tx_buf[tx_cnt++] = data;            // 1st input location tx_cnt

            UCSR0B |= (1<<UDRIE0);
    }

    void put_s(uint8_t *str)
    {
        while (*str)
            put_char(*str++);
    }

    ISR(USART_RX_vect)
    {
        if (rx_cnt < 32)                        // start count the received data
            rx_buf[rx_cnt++]=UDR0;              // 1st output location rx_cnt
        else
            rx_cnt = 0;                         // when the counter reached max value, reset it, overwrite everything

    if (!(UCSR0A & (1<<RXC0)))
            UCSR0B &= ~(1<<UDRIE0);
    }
    ISR(USART_UDRE_vect)
    {
        uint8_t i;
        if (tx_p < tx_cnt)                      // check if pointer < counted data
            UDR0 = tx_buf[tx_p++];
            else
            {
                for (i=0;i<tx_cnt;i++)
                    tx_buf[i]=0;
                tx_p = 0;                       // when the pointer reach max value, reset it
                tx_cnt= 0;                      // also reset counter for new transmission
                UCSR0B &= ~(1<<UDRIE0);         // disable empty data register interrupt
            }
    }

If the there's a received char, then ISR is executed, the function exit the LED blink loop, but when the receive stops and there're no more data it doesn't return the blink state and keeps sending the last received char. How to solve this problem?

title: How to stop sending the last received char of UART echo function?

Answers: 1

body:
There are many, many problems with this code. The most fundamental flaw
is that it uses linear buffers, where you should be using [circular
buffers][ring-buffer] instead. I'll come to this later. Now, if we look
at the details, in the header file:

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

    #define Buf_OF      0x0200

This, and a few other macros, serve no purpose. Do not put "TODO" items
in the code: put them in a TODO file, or as comments. Strive to always
have your code in a clean state. More so when you post it in a public
place.

    #define buf_mask Buf_s - 1

This is presumably intended to be used as a bit mask, but it will not
work reliably. For example, if you try to complement the mask as
`~buf_mask`, the preprocessor will expand that to `~Buf_s - 1`, and the
compiler will interpret it as `(~Buf_s) - 1`, which is **not** what you
want. You should always parenthesize any expression you use in a macro,
as

    #define buf_mask (Buf_s - 1)

Later,

    void put_s(uint8_t *str);

If you want to be able to issue calls like `put_s("Hello!");`, then you
should declare the function as:

    void put_s(const char *str);

Now, in the implementation, you have:

    static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

All those are unused. Remove them. Again, this is supposed to be a
program, not a TODO list.

Later,

    uint16_t get_char(void)
    {
        if (rx_cnt == 0)
            return NO_DATA;
        else if (rx_p < rx_cnt)
            return rx_buf[rx_p++];
    }

The compiler should have warned you about this: what if both conditions
are false? In this case the function will return by reaching its end,
with no specified return value. This is undefined behavior. You should
probably return `NO_DATA` in this case. But then, that's what you should
return every time you are not returning valid data, so the function can
be simply written as:

    uint16_t get_char(void)
    {
        if (rx_p < rx_cnt)
            return rx_buf[rx_p++];
        else
            return NO_DATA;
    }

Later, in `ISR(USART_RX_vect)`,

    if (rx_cnt < 32)
        rx_buf[rx_cnt++]=UDR0;
    else
        rx_cnt = 0;

If you set `rx_cnt` to zero without updating `rx_p`, then the subsequent
characters that you will put in the buffer will be ignored by
`get_char()` until you fill the buffer up to `rx_p`. Thus you presumably
want to set `rx_p` to zero also. And if you do this at the start if the
ISR, you ensure that _at least_ the current character is not lost:

    // when the counter reached max value, reset the buffer
    if (rx_cnt >= 32) {
        rx_p = 0;
        rx_cnt = 0;
    }
    rx_buf[rx_cnt++]=UDR0;

Further in the ISR:

    if (!(UCSR0A & (1<<RXC0)))
        UCSR0B &= ~(1<<UDRIE0);

This makes no sense: if you have no pending character in the _receive_
register (which you should not have, as you have just read that
register), then you disable the ISR that serves the _transmitter_. The
transmitter and the receiver should be able to work independently:
remove those lines.

Then, in `ISR(USART_UDRE_vect)`:

    for (i=0;i<tx_cnt;i++)
        tx_buf[i]=0;

This serves no purpose. If you handle your buffers properly, you should
_never_ access uninitialized data in them. Thus you will never read the
zeroes you are writing here. Again, remove those lines.

If you implement all the fixes above, you should end up with a code that
“kind of” works. There are still a couple of issues though:

**Race conditions**

If `get_char()` gets interrupted by `ISR(USART_RX_vect)`, you can get
what is known as a “race condition”, which can lead to incoherent
behavior or data corruption. For example, testing `rx_p<rx_cnt` is not
atomic: the CPU has to read `rx_cnt` from RAM, then read `rx_p`, then
compare them. If the interrupt fires between the two memory reads, the
ISR can set both values to zero, then the test will compare the old
`rx_cnt` with the new `rx_p` (which is now zero) and incorrectly assume
there is valid data to be returned.

There are other places where this can byte you. For example, `rx_p++` is
not atomic either, it's a read-modify-write sequence that can very well
be interrupted in the middle. And there are similar issues if
`put_char()` gets interrupted by `ISR(USART_UDRE_vect)`.

The fix for these issues is to disable interrupts while you are in the
“critical sections” that access data shared with the ISRs. This can be
done using `noInterrupts()`/`interrupts()` pairs or, if you prefer the
avr-libc style, with [atomically executed code blocks][atomic]. For
example:

    #include <util/atomic.h>

    uint16_t get_char(void)
    {
        uint16_t result = NO_DATA;
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
            if (rx_p < rx_cnt)
                result = rx_buf[rx_p++];
        }
        return result;
    }

A similar protection is needed in `put_char()`.

**Linear buffers**

This is the main flaw, because it will require you to rethink a
significant part of your code. Imagine what can happen if the UART
transmitter lags slightly behind your program calling `put_char()`. Say
you reach `tx_p` = 30 and `tx_cnt` = 32. Then your
buffer has 30 “empty” cells (from 0 to 29 the space is available, as
that data has already been sent) and two cells with bytes pending to be
sent (at positions 30 and 31). If you call now `put_char()` to send an
extra byte, that byte will be lost (because `tx_cnt<32` is false). This
is unacceptable: you should not loose data when the buffer is almost
empty!

The solution is to put the extra byte at position 0, the next one at
position 1, etc. But this creates a complication: now the pending bytes
are at positions 30, 31, 0, 1... At this point your buffer becomes a
[circular buffer][ring-buffer]. It's not a big deal, but you **must**
read about the subject before you try to implement it.

Note that the same issue applies to the receive buffer: both buffers
should be made circular.

[ring-buffer]: https://en.wikipedia.org/wiki/Circular_buffer

[atomic]: http://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html


body:
I'm trying to use an if statement to check when the time goes past a specific point and run a specific function. To do this I'm looking to convert time into a double and running something along the lines of `if(timeCurrent >= 8.30)`. I seem to however have an issue with the conversion part, normally I'm aware the standard practice in C++ would be to do the following:

    DateTime now = rtc.now();
    static char buffer[80];

    sprintf(buffer, "d.d", now.hour(), now.minute());
    String str(buffer);
    double timeCurrent = strtod(str);

However, this doesn't work for Arduino. What can be done to create the same desired function?

title: const char* to double

Answers: 1

body:
Don't do that. Converting a time to `double` is highly inefficient.
Moreover, your approach suffers from a rollover issue every 24h.

If you just want to compare the time of day with 8:30, you can do it in
a very straightforward way:

    if (now.hour() > 8 || (now.hour() == 8 && now.minute() >= 30))

If the long `if` annoys you, you can put the comparison logic inside a
`static inline` function. If you really want to combine hour and minute
into a single number, then convert to an integer rather than a double:

    if (now.hour() * 100 + now.minute() >= 830)

This can be made more efficient if you think in binary rather than
decimal: you can build a 16-bit number with one byte holding the hours
and the other byte holding the minutes:

    if ((now.hour() << 8) | now.minute() >= (8 << 8) | 30)

Again, you may encapsulate the `((a)<<8|(b))` in a macro or static
inline function if it helps with readability. If you want to compare to
an absolute time, your best option is to build a `DateTime` object
representing the deadline, and compare with `now` as:

    // Assume timeout should be today at 8:30.
    DateTime timeout(now.year(), now.month(), now.day(), 8, 30, 0);
    if (now.secondstime() >= timeout.secondstime())

Here the `secondstime()` method is used to convert the `DateTime` into a
scalar number (a 32-bit integer of type `time_t`) that can be easily
compared and is far more efficient than using floats.


body:
I have a brushed motor hooked up to a NodeMCU that moves a plate left (moveLeft) and right (moveRight). When a button (buttonOpen) is pressed, it turns to the left until the plate hits a limit switch (limit1), then the system stops and the motor driver goes to sleep. Then when a different button (buttonClose) is pressed, it moves the plate to the right, until a different limit switch (limit2) is pressed.

Now the thing is that I need the DC motor to brake once the limit switch is triggered, otherwise it will slowly roll over the switch (which is bad).

I noticed that I needed to apply the brake for at least a fraction of a second to get the motor to stop. If the brake is too short, the motor will continue to spin. That is why I created a loop that lasts 0.8 seconds (stopMotor)

The problem is that the brake is only being applied when the motor moves right. But when it moves left, it does not get applied and coasts to a stop. I can't figure this out for the life of me. I really need to to brake and stop in either direction.

Here's the code.

    const int IN1 = 13;
    const int IN2 = 12;
    const int Enable1 = 14;
    const int buttonOpen = 2; // Yellow
    const int buttonClose = 0; // Black
    const int limit1 = 5;
    const int limit2 = 4;

    void setup()
    {
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(Enable1, OUTPUT);
      pinMode(buttonOpen, INPUT);
      pinMode(buttonClose, INPUT);
      pinMode(limit1, INPUT);
      pinMode(limit2, INPUT);
    }

    void moveLeft()
    {
      digitalWrite(Enable1, HIGH); // wakes up driver
      digitalWrite(IN1, LOW); //
      digitalWrite(IN2, HIGH); // spins counter-clockwise
    }

    void moveRight()
    {
      digitalWrite(Enable1, HIGH); // wakes up driver
      digitalWrite(IN1, HIGH); //
      digitalWrite(IN2, LOW); // spins clockwise
    }

    void stopMotor() //brake motor for 0.1 seconds to avoid coasting then place             driver to sleep
    {
      int period = 80L;       // 0.08 seconds
      for( int tStart = millis();  (millis()-tStart) < period;  ){
        digitalWrite(IN1, HIGH); // brake
        digitalWrite(IN2, HIGH); // brake
      }
      digitalWrite(Enable1, LOW); // Sleep driver
    }

    void loop(){
      // Move motor right
      if (digitalRead(buttonOpen) == LOW){
        while(digitalRead(limit2) == HIGH){
          moveRight();
          yield();
        }
      }
      else
        (stopMotor());

      // Move motor left
      if (digitalRead(buttonClose) == LOW){
        while(digitalRead(limit1) == HIGH){
          moveLeft();
          yield();
        }
      }
      else
        (stopMotor());
    }

title: DC Motor Not Braking

Answers: 0


body:
I'm really new to coding for arduino.  My current project is a monitor for my terrarium using an arduino UNO board, a DHT11 and a DS3231 RTC, displaying Temperature(from both DHT (in the terrarium) and the RTC (outside)) as well as time and humidity.

The code was functional, but recently the IDE said there were some updates (which I ran) and now it won't verify. All this code was basically obtained through examples for the hardware I'm using.   Can someone please point me to what I need to correct?

The code as is ....

    #include <DS3231.h>

    #include <dht11.h>

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    DS3231  rtc(SDA, SCL);
    dht11 DHT;                        //Note:DHT on behalf of the temperature         and humidity sensor
    const int dht11_data = 6;
    int temp=0;
    int hum=0;

    #include "Wire.h"
    #define DS3231_I2C_ADDRESS 0x68
                                  // Convert normal decimal numbers to binary   coded decimal
    byte decToBcd(byte val)
    {
      return( (val/10*16) + (val) );
    }
                                  // Convert binary coded decimal to normal decimal numbers
    byte bcdToDec(byte val)

    {
      return( (val/16*10) + (val) );
    }

    void setup()
    {
      Wire.begin();
                                  // set the initial time here:
      // DS3231 seconds, minutes, hours, day, date, month, year
      // setDS3231time(30,42,21,4,26,11,14);
      rtc.begin();                    //Initialize the rtc object
      lcd.begin(16,2);                //Initialize LCD display
      lcd.print("Terrarium ");        //Splash Screen text line 1
      lcd.setCursor(0,1);             //Set Cursor Position for second line of Splash screen
      lcd.print("Monitor 1.3");       //Splash screen text line 2
      delay(3000);                    //Delay 3 seconds on Splash screen
      lcd.clear();                    //Clear LCD
    }

    void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
    dayOfMonth, byte month, byte year)

    {
      // sets time and date data to DS3231
      Wire.beginTransmission(DS3231_I2C_ADDRESS);
      Wire.write(0);                  // set next input to start at the seconds register
      Wire.write(decToBcd(second));   // set seconds
      Wire.write(decToBcd(minute));   // set minutes
      Wire.write(decToBcd(hour));     // set hours
      Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
      Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
      Wire.write(decToBcd(month));    // set month
      Wire.write(decToBcd(year));     // set year (0 to 99)
      Wire.endTransmission();
    }

    void readDS3231time(byte *second,byte *minute,byte *hour,byte     *dayOfWeek,byte *dayOfMonth,byte *month,byte *year)

    {
      Wire.beginTransmission(DS3231_I2C_ADDRESS);
      Wire.write(0); // set DS3231 register pointer to 00h
      Wire.endTransmission();
      Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
                                  // request seven bytes of data from DS3231       starting from register 00h
      *second = bcdToDec(Wire.read() & 0x7f);
      *minute = bcdToDec(Wire.read());
      *hour = bcdToDec(Wire.read() & 0x3f);
      *dayOfWeek = bcdToDec(Wire.read());
      *dayOfMonth = bcdToDec(Wire.read());
      *month = bcdToDec(Wire.read());
      *year = bcdToDec(Wire.read());
    }
    void displayTime()
    {
      DHT.read(dht11_data);
      temp=DHT.temperature;
      hum=DHT.humidity;

      lcd.clear();                    //clear display

      lcd.print("rH=");               //Display text rH= on LCD
      lcd.print(hum);                 //Display relative humidiy reading from    DHT11
      lcd.print("%");                 //Display Percent sign

      lcd.setCursor(9,0) ;            //set cursor position
      lcd.print("Ti=");               //display"Ti="
      lcd.print(temp);                //Displays temperature reading from     DHT11, designated is Internal Temperature
      lcd.write(0xDF);                //Display custom characters '°'
      lcd.print("C");                 //Display text "C" to designate Celsius     units

      byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

                                  // retrieve data from DS3231
      readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,  &year);
                                  // send it to the serial monitor

      lcd.setCursor(0,1);
      lcd.print(hour, DEC);           //Displays hours value on LCD
                                   // convert the byte variable to a decimal number when displayed
      lcd.print(":");                 //Displays ":" between hours and minutes
      if (minute<10)
      {
        lcd.print("0");
      }
      lcd.print(minute, DEC);         //Displays Minutes value on the LCD
      lcd.setCursor(9,1);
      lcd.print ("Te:");              //Displays text "Te:" on LCD
      lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

    }
    void loop()
    {
      displayTime();                  // display the real-time clock data on the Serial Monitor,
      delay(1000);                    // every second
    }

and the errors it is throwing are:

    > > Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"
    >
    > Terrarium_Monitor_1.3:8: error: no matching function for call to
    > 'DS3231::DS3231(const uint8_t&, const uint8_t&)'
    >
    >  DS3231  rtc(SDA, SCL);
    >
    >                      ^
    >
    > F:\Arduino Kit Stuff\my
    > sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:8:21: note:
    > candidates are:
    >
    > In file included from F:\Arduino Kit Stuff\my
    > sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:1:0:
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
    > note: DS3231::DS3231()
    >
    >    DS3231();
    >
    >    ^
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
    > note:   candidate expects 0 arguments, 2 provided
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
    > note: constexpr DS3231::DS3231(const DS3231&)
    >
    >  class DS3231 {
    >
    >        ^
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
    > note:   candidate expects 1 argument, 2 provided
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
    > note: constexpr DS3231::DS3231(DS3231&&)
    >
    > C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
    > note:   candidate expects 1 argument, 2 provided
    >
    > F:\Arduino Kit Stuff\my
    > sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
    >    'void setup()':
    >
    > Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named
    > 'begin'
    >
    >    rtc.begin();                    //Initialize the rtc object
    >
    >        ^
    >
    > F:\Arduino Kit Stuff\my
    > sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
    > 'void displayTime()':
    >
    > Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named
    > 'getTemp'
    >
    >    lcd.print(rtc.getTemp());       //Displays Temperature from DS3231
    > designated as "External Temperature"
    >
    >                  ^
    >
    > Multiple libraries were found for "LiquidCrystal.h"  Used: E:\Program
    > Files (x86)\Arduino\libraries\LiquidCrystal  Not used:
    > C:\Users\Ursinos\Documents\Arduino\libraries\arduino_136712 exit
    > status 1 no matching function for call to 'DS3231::DS3231(const
    > uint8_t&, const uint8_t&)'
    >
    > This report would have more information with "Show verbose output
    > during compilation" option enabled in File -> Preferences.

As I said, I was working when I uploaded it to my arduino on last changes a week ago (and it's still running on the board right now), but after doing the updates to the libraries and whatnot, it's now throwing all these errors.   I know the code isn't very elegant, I'm still learning.  Please help

edit:  After altering the line as advised in the answers, I now get the following errors.

    Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

    F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void setup()':

    Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named 'begin'

       rtc.begin();                    //Initialize the rtc object

           ^

    F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void displayTime()':

    Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named 'getTemp'

     lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

                 ^

    Multiple libraries were found for "LiquidCrystal.h"
     Used: E:\Program Files (x86)\Arduino\libraries\LiquidCrystal
     Not used: C:\Users\Ursinos\Documents\Arduino\libraries   \arduino_136712
    exit status 1
    'class DS3231' has no member named 'begin'

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Could this have anything to do with my Arduino IDE being version 1.8.3 instead of the newest version?

title: Code throwing errors after an IDE update

Answers: 2

body:
I found this online but I can not verify it.

http://www.instructables.com/topics/no-matching-function-for-call-to-DS3231DS3231const/

The relevant part for you I think is:

> I don't know where you get the syntax
>
> DS3231 rtc (SDA, SCL);
>
> My copy of the DS3231 library says you need only DS3231 rtc; //no
> arguments. BUT you need the Wire library.

So change your code and make sure you have the Wire library.

body:
Alright, so I figured it out by *gasp* going and reading the documentation for the DS3231 library I'm using.

It seems when the library updated, one of the keywords changed.

so, after removing the (SDA, SCL) from the one line, I had to remove the line

    rtc.begin();

and change

    lcd.print(rtc.getTemp());

to

    lcd.print(rtc.getTemperature());

thanks for the help :D


body:
I need to build an app that will display on browser data from 3 sensors.
My 3 sensors are: Humidity and temperature (DHT22), vibration sensor and distance sensor (HC-SR04).

I want to connect these 3 sensors to my WeMos D1 R1 and to send the data to be displayed on a webpage. Until now, I can locally (from Serial monitor of Arduino IDE) read the sensors one by one - I mean, I upload the code for each one... I don't know how to combine the 3 codes to work.

So my main question is how to combine these 3 codes into one and access the data from a webpage?

My codes are : vibration (I want to get rid of the LED, just to display the vibration value)

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

    int LED_Pin = D13;
    int vibr_Pin = D2;

    void setup(){
      pinMode(LED_Pin, OUTPUT);
      pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurement
      Serial.begin(9600); //init serial 9600
    }

    void loop(){
      long measurement =TP_init();
      delay(50);
      Serial.println(measurement);
      if (measurement > 4000){
        digitalWrite(LED_Pin, HIGH);
      } else {
        digitalWrite(LED_Pin, LOW);
      }
    }

    long TP_init(){
      delay(10);
      long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
      return measurement;
    }

DHT22 code:

    #include <SimpleDHT.h>

    // for DHT22,
    //      VCC: 5V or 3V
    //      GND: GND
    //      DATA: 2
    int pinDHT22 = D8;
    SimpleDHT22 dht22;

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

    void loop() {
      // start working...
      Serial.println("=================================");
      Serial.println("Sample DHT22...");

      // read without samples.
      // @remark We use read2 to get a float data, such as 10.1*C
      //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
      float temperature = 0;
      float humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT22 failed, err="); Serial.println(err);delay(2000);
        return;
      }

      Serial.print("Sample OK: ");
      Serial.print((float)temperature); Serial.print(" *C, ");
      Serial.print((float)humidity); Serial.println(" RH%");

      // DHT22 sampling rate is 0.5HZ.
      delay(2500);
    }

HC-SR04 CODE :

    // defines pins numbers
    const int trigPin = D5;
    const int echoPin = D6;
    // defines variables
    long duration;
    int distance_cm;
    int distance_in;
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }

    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(500);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(trigPin, LOW);
      /* Reads the echoPin, returns the sound wave
         travel time in microseconds */
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance_cm = duration / 58;
      distance_in = duration / 148;
      Serial.print("Distance: ");
      Serial.print(distance_cm);
      Serial.println(" centimeters");
    }

---

I managed to merge the 3 codes into 1. I still need to adapt it to send the information on a webpage. Up to now, the code for 3 sensors is:

    #include <SimpleDHT.h>

    // for DHT22,
    //      VCC: 5V or 3V
    //      GND: GND
    //      DATA: 2
    const int trigPin = D5;
    const int echoPin = D6;
    long duration;
    int distance_cm;
    int distance_in;
    int vibr_Pin = D8;
    int pinDHT22 = D2;
    SimpleDHT22 dht22;

    void setup() {
      Serial.begin(9600);
      pinMode(vibr_Pin, INPUT);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    }

    void loop() {
      // start working...
      Serial.println("=================================");
      Serial.println("TEMPERATURE & HUMIDITY");

      // read without samples.
      // @remark We use read2 to get a float data, such as 10.1*C
      //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
      float temperature = 0;
      float humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT22 failed, err=");
        Serial.println(err);delay(2000);
        return;
      }

      Serial.print("Temperature & Humidity: ");
      Serial.print((float)temperature); Serial.print(" *C, ");
      Serial.print((float)humidity); Serial.println(" RH%");

      // DHT22 sampling rate is 0.5HZ.
      delay(2500);
      Serial.println("=================================");
      Serial.println("VIBRATION");
      long measurement =TP_init();
      delay(50);
      Serial.print("measurement = ");
      Serial.println(measurement);
      Serial.println("=================================");
      Serial.println("DISTANCE");
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(500);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(500);
      digitalWrite(trigPin, LOW);
      /* Reads the echoPin, returns the sound wave
         travel time in microseconds */
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance_cm = duration / 58;
      distance_in = duration / 148;
      Serial.print("Distance: ");
      Serial.print(distance_cm);
      Serial.println(" centimeters");
    }

    long TP_init(){
      delay(10);
      long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
      return measurement;
    }

So, in the serial monitor of Arduino IDE, we will see the values displayed for our 3 sensors. I would really appreciate if somebody can help me to integrate this code to an IoT platform.

title: 3 sensors and wemos d1 r1 and web

Answers: 1

body:
I would suggest using [thinger.io](https://thinger.io).  It has a library that is insanely simple to use.

This is code for a greenhouse monitor that I wrote using their library. It exposes the temperature and humidity from a DHT22, the time the unit has been running, and when it was last programmed. And all with OTA support as well.

    #include <ESP8266WiFi.h>
    #include <dht.h>
    #include <ThingerESP8266.h>
    #include <ArduinoOTA.h>
    #include <Average.h>

    dht dht22;

    Average<float> temperature(10);
    Average<float> humidity(10);

    ThingerESP8266 thing("myaccount", "thisunit", "somekey");

    void getSample() {
        static uint32_t ts = 0;
        if (millis() - ts < 10000) {
            return;
        }
        ts = millis();

        dht22.read22(D6);
        int samples = 0;
        while (
            (dht22.temperature < -100) ||
            (dht22.temperature > 200) ||
            (dht22.humidity < -100) ||
            (dht22.humidity > 200))
        {
            delay(10);
            dht22.read22(D6);
            samples++;
            if (samples > 10) {
                return;
            }
        }
        temperature.push(dht22.temperature);
        humidity.push(dht22.humidity);
    }

    void setup() {
        WiFi.hostname("Greenhouse");
        thing.add_wifi("MyWiFiSSID", "MyWiFiPSK");

        thing["temperature"] >> [](pson& out) {
            getSample();
            out = temperature.mean();
        };
        thing["humidity"] >> [](pson& out) {
            getSample();
            out = humidity.mean();
        };
        thing["uptime"] >> [](pson& out) {
            out = millis() / 1000.0;
        };
        thing["compiled"] >> [](pson& out) {
            out = __DATE__ " " __TIME__;
        };

        ArduinoOTA.setHostname("Greenhouse");
        ArduinoOTA.setPassword("MyOTAPassword");
        ArduinoOTA.begin();
    }

    void loop() {
        thing.handle();
        ArduinoOTA.handle();
    }

It's a little more complex that you may need, since I do averaging and filtering of the sampled data to clean it up a little. All the magic of when to take samples and how to deal with the data is done on the thinger.io website. But the code, as you can see, is insanely simple.


body: I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?

title: Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno

Answers: 1

body:
As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).

Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.

In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the **tops** of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.

I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).


body:
In my circuit I have a relay that will turn on some light bulbs this is my circuit:

[![Circuit][1]][1]
The switch over the 5V is in fact my Arduino. A HIGH will turn on the relay and a LOW will turn it off.

This is working fine, but because of security measures I need to add a mechanical switch to be able to turn on and off whenever needed. This is the circuit I'm using for this configuration:

[![Circuit][2]][2]

This circuit also works fine, the lamp is turned on and off by changing either switches but the Arduino loses track of the status of the lamp. The only thing it knows is if the relay is on or off.

Is there a simple way to tell when the lamp is on?

  [1]: https://i.stack.imgur.com/tMFDl.png
  [2]: https://i.stack.imgur.com/BZtW9.png

title: Relay with mechanical fallback

Answers: 2

body:
If you add an optical sensor appropriate for the lamp (UV, IR, visible light?) and add a test line to your code, the Arduino would "know" if the light is on. Your second circuit could remain as presented, while the sensor would provide a status of the light.

If the light failed for an unknown reason, the code for your Arduino would not know the difference between that and a manually opened override switch.

body:
I got the terminology wrong in my comment. My suggestion is not to use
what is commonly called a “three way switch”, but instead a [single pole
triple throw
switch](https://electronics.stackexchange.com/a/299197/174547). This is
not available in the schematic editor, so I had to improvise. Imagine
that the switch labeled “SP3T” below has three contacts on its left
side:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/n0rda.png)

<!-- End schematic -->

* The top contact connects to nothing: this is the OFF position
* the middle contact connects the controlled circuit with the relay:
  this is the AUTO position where the Arduino is in charge
* the bottom contact closes the controlled circuit: this is the ON
  position


body:
I am having a problem. I designed obstacle robot with ultrasonic sensor. But the problem i'm facing is one that no one discussed ever. I kept on searching it on internet and found no solution for it. So, i decided to ask it here:

Firstly, I used one ultrasonic sensor to avoid obstacle alongwith servo motor using **newping** library. But it failed badly due to an elevation of the sensor so it doesn't detect any lower height object.

Second time, i used three ultrasonic sensors to check for the side's obstacles and front obstacle as well. In most of the cases what no one ever showed in video there are some places and times when it get stuck (due to design and even sonar limitation).

What i want to do is to add some features to the code that can detect stuck motor or stopped robot at one place. Once detected this condition it moves backward and turn the other way if again stuck then move backward and turn the other way.

I hope i could make you understand the problem i'm facing. I'll appreciate the solution and it may help others to find solution for it. I don't know how to attach the code here (it may create mess for the reader). So, please tell me if i need to send or attach here. Thanks.!

title: Arduino Obstacle Avoidance (Problem)

Answers: 0


body:
Here is the code I used to get BPM from pulse sensor.

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

    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most
    acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground
    Library.
//  Variables

    const int PULSE_SENSOR_COUNT = 2;
    const int PulseWire = A0;
    const int PulseWire2 = A1;
    const int LED13 = 13;
    int Threshold = 550;

    void setup() {
      Serial.begin(9600);
      pulseSensor.analogInput(PulseWire, 0);
      pulseSensor.analogInput(PulseWire2, 1);
      pulseSensor.blinkOnPulse(LED13);
      pulseSensor.setThreshold(Threshold);
      if (pulseSensor.begin()) {
      }

      void loop() {
        int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".

        if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
          //Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
          Serial.print("BPM1: ");                        // Print phrase "BPM: "
          Serial.println(myBPM);                        // Print the value inside of myBPM.
        }
        delay(20);                    // considered best practice in a simple sketch.
      }

I wish to separate display the BPM that get from A0 wire and A1 wire. Serial could print something like this: `BPM1(A0):75, BPM2(A1):80`.
I don't know how to do that, can anyone help me with it?

title: How to get separate BPM readings from two pulse sensors using one Arduino

Answers: 1

body:
Change "#define USE_ARDUINO_INTERRUPTS **true**" to "#define USE_ARDUINO_INTERRUPTS **false**".

>If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
>
>  #define USE_ARDUINO_INTERRUPTS false
>
>  #include <PulseSensorPlayground.h>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h


body:
I’m working on a robot with a club at my school. So far, our team has an H-bridge shield (https://www.freetronics.com.au/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.WwI9omh_WEc) to drive motors in a toy tank. The H-bridge is powered by 6 AA batteries and the arduino is powered through the H-bridge shield with these batteries also.
 When everything is connected up and  code uploaded to make the motors run forward, nothing happens - the motors don’t run. So far to debug, I’ve used a multimeter to check the voltages being output to the H-bridge from the arduino controller. These are all as expected. I’ve touched the motors to the positive and negative terminals of the battery and they run as expected. Lastly, I’ve substituted the H-bridge shield for a known working one. This did not fix the problem. I disconnected the motors and tested the voltage being output, which measured as +6V for both terminals of the motor relative to the negative terminal of the battery as well as relative to the ground pin. I also disconnected the jumper powering the arduino from the H-bridge shield and instead powered the arduino from my laptop. This did not fix the problem either. This seems completely contradictory. Any ideas on what the problem could be? Thanks so much ❤❤

title: No potential across output of H-bridge

Answers: 1

body:
It sounds either (i) like your motor driver is broken or (ii) your code does not operate the H bridge properly.  Check which digital outputs pins of the Arduino control the H bridge and make sure that they do not short out the H bridge.

If you want to try another H bridge, this one is suitable for your application: https://www.pololu.com/product/2990 .  I have worked with this before and it's very easy to use.


body:
Also posted at: https://forum.arduino.cc/index.php?topic=549672.0

is there anyone who experienced similar problem or knows a solution to it?

The problem is that after uploading the code Arduino Pro Micro hangs (and RX led is constantly on).

The problem occurs instantly after turning on the microcontroller even if I put "delay(10000);" at the begining of the code trying to see at which point the error occurs.

The problem can be "fixed" by adding '**Serial.print("aa");**' at random place within the code...
Which results in the following output during upload:

    Sketch uses 18318 bytes (63%) of program storage space. Maximum is 28672 bytes.
    Global variables use 1814 bytes (70%) of dynamic memory, leaving 746 bytes for local variables. Maximum is 2560 bytes.

Suprisingly, using '**Serial.print("a");**" instead does not fix the problem. It results in the following output during upload:

    Sketch uses 18314 bytes (63%) of program storage space. Maximum is 28672 bytes.
    Global variables use 1810 bytes (70%) of dynamic memory, leaving 750 bytes for local variables. Maximum is 2560 bytes.

It seems very weird to me that adding serial print instruction with certain length (at seemingly random place) can solve such problem...

Another circumstance which seems to be solving the problem is commenting out one of the 2 lines (does not matter which):

    sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
    sprintf(at_pin_cmd, "AT+PIN%s\0", pin);

It's a spaghetti code so I doubt anyone will analyse it but just in case if anyone wanted to check it for some more or less obvious characteristic (e.g. F()/eeprom/memory extensive use or something...) then here it is: [Hastebin - link][1]

I'm using "Arduino Pro Micro 5V" and Arduino IDE 1.8.5 with "Arduino Leonardo" board setting

  [1]: https://hastebin.com/oyarezebiv.cpp

title: Weird sketch size/memory/compiler (?) related issue (hanging, RX led on)

Answers: 0


body:
I'm trying to use the [TTGO TS 1.0 display][1] with a demo app from a different source. The demo app wants the following to be configured:

    #define PIN_NUM_MISO 17  // SPI MISO
    #define PIN_NUM_MOSI 23  // SPI MOSI
    #define PIN_NUM_CLK  5  // SPI CLOCK pin
    #define PIN_NUM_CS   26  // Display CS pin
    #define PIN_NUM_DC   17  // Display command/data pin
    // ** If you want to use them, set them to some valid GPIO number
    #define PIN_NUM_RST  0   // GPIO used for RESET control

According to the TTGO readme the following wiring is used:

CS:16
DC:17
SDA:23
SCK:5
RST:9

My guess is:

    PIN_NUM_MISO ?
    PIN_NUM_MOSI 23
    PIN_NUM_CLK  5
    PIN_NUM_CS   16
    PIN_NUM_DC   17

How to update the demo app to match with this? Reset is optional in the demo and there is 1 additional pin there as well which I can't figure out...

  [1]: https://github.com/LilyGO/TTGO-TS-V1.2

title: Using TTGO TS 1.0 TFT display

Answers: 1

body:
If it is, as I think it may be now I have dug into the code a little, simply an SPI interface with no MISO (which is quite common for TFT screens) you just map the pins 1:1 and ignore MISO.

* PIN_NUM_MISO => Ignore
* PIN_NUM_MOSI => SDA
* PIN_NUM_CLK => SCL
* PIN_NUM_CS => CS
* PIN_NUM_DC => DC
* PIN_NUM_RST => RST or Ignore

If the demo code insists on there being a MISO pin you can just assign that to any unused GPIO pin. You don't need to connect it to anything.

The majority of TFT and OLED driver code only ever writes to a screen and never reads from it, so MISO is not needed to actually control the screen.


body:
Currently to use TimedAction for a function a program would look like so:

    #include <TimedAction.h>
    void functionX();
    TimedAction funtionTimed = TimedAction(1000, functionX);

    void setup()
    {

    }

    void loop()
    {
    functionTimed.check();
    }

    void functionX()
    {
     //run function
    }
My question is say I have an object class with some functions I would like to use with this TimedAction library. How would this be written?

title: Can the TimedAction library be used to call functions of an object

Answers: 1

body:
You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).

You have to call a normal function which then calls the class function, or you have to have your class function as `static` so it doesn't include the class in the function prototype.

    class foo {
        public:
            static void runMe() {
                // blah blah
            }
    };

    TimedAction funtionTimed = TimedAction(1000, foo::runMe);

However, TimedAction is pretty simplistic and you don't really need it.  You can just write a function to only run every so often:

    class foo {
        private:
            uint32_t _runMeTimestamp;
        public:
            void runMe() {
                if (millis() - _runMeTimestamp < 1000) return;
                _runMeTimestamp = millis();
                // blah blah
            }
    };

    foo myFoo;

    void loop() {
        myFoo.runMe();
    }

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.


body:
I'm struggling with the following problem:

I have an inverted pyramid, supported in four points, filled with maize up to 600KG.

I want to keep track of the level of maize inside the inverted pyramid.

I've thought about using a load cell but this can be expensive and I need a cheap solution to implement. I also thought about using a sensor centred on top of the inverted pyramid.

The problem here is that I really dont't know what kind of sensor can be used to get correct values.
Can ultrasonic sensors give me bad values? The pyramid form is tricky...

PS: Theoricly can mill be too reflective and influence the result of measures?

I'm sorry for the English :P. I'm still learning.

If anyone can help I really appreciate.

Best Regards

title: Sensor to measure distance on inverted pyramid filled with maize

Answers: 2

body:
The surface of corn is hard enough to reflect sound from an ultrasonic sensor. It reflects from fabric, skin and of course, plastic, and corn fits into the realm of reflectivity.

An Arduino with an ultrasonic sensor may scatter a good bit of the reflection, but some of it will get back to the receiver in sufficient condition to be registered.

The components necessary to test this are low enough cost to suggest a prototype. A simple pail or bucket filled with the grain and attached to a rope and pulley will give you distance information, and that would be for a relatively small surface area.

Ultrasonic sensors typically have a minimum distance and of course, a maximum distance. If your concern is for both full and empty conditions, dual sensors placed a sufficient distance apart with suitable range considerations are likely to work. The code would be written to avoid cross-pulse readings, which is likely to be trivial, as these devices operate at the speed of sound.

Lasers are point devices and may not necessarily reflect to the sensor for reading.

I have constructed a DME (distance measuring equipment) that displayed passing vehicles within a range of ten feet (~3 meters) down to slightly less than three feet (<1 meter) with good results. There was tremendous lag in the reading, but that's due to code ignorance, not hardware problems. I suspect the depth finder is not going to have much lag in determining its value to this application.

body:
You can let the sensor "sense" 20 times and let your Arduino figure out the average.
More on [Using the HC-SR04 Ultrasonic Distance Sensor with Arduino][1].

Maybe the ultrasound also scares rodents. I am using IR sensor Sharp GP2Y0A02YK which reaches from 20-150 cm

  [1]: https://dronebotworkshop.com/hc-sr04-ultrasonic-distance-sensor-arduino/


body:
I am trying to write a code to read the current position of a flex sensor when a button is pushed and use that data to pulse a piezo. I set it up to read the flex sensor and to alarm when it gets 100 or below, that works! So what I want to do is integrate a button where you push it to set the current state of the flex sensor and then when its moved and is less than the number logged when the button was pressed then it alarms. I used to write in Basic and quick basic and am now (many years later in life) trying to learn C and am struggling. I'm using a NANO ATmega328p - here is my code so far:

    int flexSensorPin = A0;//analog pin 7= tiny2=A1
    const int Piezo = 3; //digital pin 3 = tiny0
    const int inPin = 2; // Push Button to set current Bend Status
    void setup() {
      pinMode (Piezo, OUTPUT);
      pinMode(inPin, INPUT);    // declare pushbutton as input
      Serial.begin(9600);
    }
    void loop() {
      int val = 0;
      val = digitalRead(inPin);
      int flexSensorReading = analogRead(flexSensorPin);
      Serial.println(flexSensorReading);
      if (flexSensorReading < 100) {
        Serial.println("Alarm! Set Angle Exceeded");
        digitalWrite(Piezo, HIGH);
        delay(100);
        digitalWrite(Piezo, LOW);

      }
      delay(250);
    }

title: Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p

Answers: 1

body:
You will need to add this at the start of your code.

    int LoggedPosition=100;

Change this line

    if (flexSensorReading < 100) {

To this

    if (flexSensorReading < LoggedPosition) {

and add this at just before the delay, at the end of the `loop()` function

    if(digitalRead(inPin)){
        LoggedPosition=flexSensorReading;
    }


body:
I am trying to understand how the serial ports are configured on the due board. Please correct me if i'm wrong, but to my understanding, the due has:

- Four separate serial ports ("serial", and "serial 1-3"), each with SX and TX pin functions
- A USB port paired with serial, simultaneously sending and receiving data from the serial function via USB protocol

I'm currently sending MIDI data over serial1 with the required baud rate of 31250. I want to configure another serial function (assumingly with a different baud rate to match the IDE serial monitor) in order to monitor Serial.print messages simultaneously for debugging.

In setup():

    Serial1.begin(31250);  //MIDI baud rate
    Serial.begin(115200);

and then, in a for loop i want to monitor each value i in the array loop1[i]):

    Serial.print(String(loop1[i]) + " ");

However, i can't seem to make it work... My question is, is it possible to transmit the MIDI data via serial, in parallel with serial.print data with a separate serial function?

title: Utilizing two different serial ports simultaneously on a due

Answers: 1

body: You can't use MIDI on `Serial` and use `Serial.print` at the same time. You can though use MIDI on `Serial1` and use `Serial.print` at the same time (or `Serial2` etc).


body:
I am trying to use the [CMDmessanger](https://playground.arduino.cc/Code/CmdMessenger) library on my Arduino uno, and am facing an issue.

My issue starts right from the [ArduinoController.ino](https://github.com/thijse/Arduino-CmdMessenger/tree/master/examples/ArduinoController) example.

When i send the frequency command

    3,1;
The led starts blinking correctly, once per second.

But when I send a wrong command (basically a command without an argument)

    3;
The led just stops blinking. The state of the led depends on which state it was in when I sent the command.

I realised that, when I send the wrongly formatted command, it takes the frequency as 0.

Is there any method by which I can make sure that the command is received in the right format, before it is executed? Ideally I would love it if there is a method to know how many arguments were received, and I could call the readBoolArg, or other equivalent functions to retrieve the argument data.

I am planning on using this library for quite a few projects, and I don't want to be in a situation where things went wrong because there was not formatting check.

Thanks in advance.

title: CMDmessenger library

Answers: 1

body:
The example code uses `cmdMessenger.readFloatArg();` ([source](https://github.com/thijse/Arduino-CmdMessenger/blob/master/CmdMessenger.cpp#L454)) to read an argument.

    void OnSetLedFrequency()
    {
      // Read led state argument, interpret string as boolean
      ledFrequency = cmdMessenger.readFloatArg();
      // Make sure the frequency is not zero (to prevent divide by zero)
      if (ledFrequency < 0.001) { ledFrequency = 0.001; }
      // translate frequency in on and off times in miliseconds
      intervalOn  = (500.0/ledFrequency);
      intervalOff = (1000.0/ledFrequency);
      cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
    }

That function will set `ArgOk` to `false` if there was no next argument.

    float CmdMessenger::readFloatArg()
    {
     if (next()) {
      dumped = true;
      ArgOk = true;
      //return atof(current);
      return strtod(current, NULL);
     }
     ArgOk = false;
     return 0;
    }

Thus you should try to use public function

    bool isArgOk();

    /**
     * Returns if the latest argument is well formed.
     */
    bool CmdMessenger::isArgOk()
    {
     return ArgOk;
    }

of the `CmdMessenger` object (which will return `ArgOk`) to check if the read argument was okay. You could e.g. modify the code as follows

    void OnSetLedFrequency()
    {
      // Read led state argument, interpret string as boolean
      ledFrequency = cmdMessenger.readFloatArg();

   //Did we just read garbage because the argument wasn't there?
   if(!cmdMessenger.isArgOk()) {
          //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
    Serial.println("You didn't supply a correct argument! Error.");
    return; //goodbye
   }

      // Make sure the frequency is not zero (to prevent divide by zero)
      if (ledFrequency < 0.001) { ledFrequency = 0.001; }
      // translate frequency in on and off times in miliseconds
      intervalOn  = (500.0/ledFrequency);
      intervalOff = (1000.0/ledFrequency);
      cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
    }


body:
What will happen, if I try to measure voltage higher than ARef?
For example, my ref is 3.3V, and I try to measure 4.5V. Will it damage adc?

title: What will happen if I set ARef to 3.3V and try to use adc connected to 5V

Answers: 2

body:
The datasheet of the Atmega328P does not give a direct answer to this, but

> Single ended channels that exceed V REF will result in codes close to
> 0x3FF.

(Datasheet Chapter 24.5.2)

sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found [another side][1], where this is also stated. They linked to the Arduino forum, where a similar question is handled in [this thread][2].

So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).

---

As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can.

  [1]: https://www.element14.com/community/thread/37358/l/5v-on-adc-that-is-set-to-a-reference-of-33v-what-happens?displayFullThread=true
  [2]: http://forum.arduino.cc/index.php/topic,119109.0.html

body:
Contrary to what @chrisl says, the datasheet *does* give a direct answer to this:

* Voltage on any Pin except RESET with respect to Ground: -0.5V to VCC+0.5V

So when running at 5V anything up to 5.5V is safe - regardless of what VRef has fed into it.

The VRef just sets the range of the ADC when comparing the incoming voltage to a DAC generated voltage, so anything over the VRef voltage will just read as "max" (1023).


body: I am a newbie. I would like to kno whether the original Atmega328 on Arduino Uno, programmed with my own sketch, can be removed from an Arduino Uno board and used  on my customised PCB?

title: Removing and using programmed Atmega 328 of Arduino UNO on customised PCB

Answers: 3

body:
Yes, it can. Your board will need to provide +5v and ground, a reset signal, and a crystal for the chip's programmed clock frequency (unless you reprogrammed it to use its internal clock). The power and clock signals will need filter capacitors. You can even re-program it on the board with an FTDI (USB-TTL Serial) cable.

There are lots do-it-yourself instructions to build an Arduino board, which is a good place to start, even if what you eventually want is a larger system board with an Arduino integrated into it. [This is one][1] I can vouch for; I built Mr. Alves' Version-1 as my only Uno-like board and have been using it for several years.

  [1]: https://jpralves.net/pages/cseduinoworld.html

body:
Yes. Just need a few components:

10K reset pullup resistor.

0.1uF or 100nF ceramic caps:

1 to bring in DTR signal  from an FTDI Basic if you plan to reprogram the '328P, or to have a serial interface for debugging

1 on the Aref pin for analog voltage reference decoupling

1 on the VCC pin

1 on the Avcc pin. Avcc also connect to Vcc.

Crystal and two 22pF caps as noted already, or a 3-pin resonator, at 16 MHz.
Alternately, you can use the internal 8 MHz circuit for the clock, but the clock source fuses will need to be re-Programmed (using a Programmer).

If you will using a Reset switch, then a diode across the 10K pullup resistor (cathode to the 5V supply, anode to the Reset pin) can also prevent any high voltage glitches on the Reset signal from looking like a High Voltage programming pulse and making the chip look hung up as it waits for the programming sequence to begin.

body:
Yes  I did it. Making the board was not so difficut but took quite some time to solder all the components the others mentioned (chrystals,capacitors, resistors and connectors. However,I found the Nick Gammon site very useful, particularly for the programming

part.http://www.gammon.com.au/forum/bbshowpost.php?bbtopic_id=123


body:
This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:

    #define Water_Level_A 5;
    #define Water_Level_B 6;

    boolean Water_Level_Check_A(){
    boolean Result = digitalRead(Water_Level_A);
    return Result;
    }
    boolean Water_Level_Check_B(){
    boolean Result = digitalRead(Water_Level_B);
    return Result;
    }

    void setup() {
        Serial.begin(9600);
        pinMode(Water_Level_A,INPUT);
        pinMode(Water_Level_B,INPUT);
        }

    void loop() {
    if (Water_Level_Check_A() == LOW){
    --> Water Pump A
    }
    if Water_Level_Check_B() == LOW{
    --> Water Pump B
    }
What's the best way to simplify this code so that I only need one `Water_Level_Check` function so that the distinction between A and B and Water_Level_A and Water_Level_B is made within the function and the loop part looks like this:

    void loop() {
    if (Water_Level_Check_(A) == LOW){
    --> Water Pump A
    }
    if Water_Level_Check_(B) == LOW{
    --> Water Pump B
    }

title: Merging of two functions

Answers: 2

body:
Functions like

    boolean Water_Level_Check_A(){
       boolean Result = digitalRead(Water_Level_A);
       return Result;
    }

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to

    boolean Water_Level_Check_A(){
       return digitalRead(Water_Level_A);
    }

Or just the expression

    digitalRead(Water_Level_A)

whenever you need it.

So all you're doing is calling `digitalRead()` on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a `true` from this function means that some action needs to be done.

    boolean Water_Level_Check(int sensorPin){
       return !digitalRead(sensorPin);
    }

And then call it as

    void loop() {
       if (Water_Level_Check(Water_Level_A)){
           //--> Water Pump A
       }
       if (Water_Level_Check(Water_Level_B )){
           //--> Water Pump B
       }
    }

body:
I think what you're asking for is something like this:

    boolean Water_Level_Check(uint8_t level_pin){
       boolean Result = digitalRead(pin);
       if( level_pin == Water_Level_A ){
          // manage pump A here
       }
       else if( level_pin == Water_Level_B ){
          // manage pump B here
       }
       else {
          Serial.println("Water_Level_Check: unknown pin number.");
          // or some other way of dealing with a bad-pin-number bug.
          return -1;
       }

       return Result;
    }
for the level testing function, which will simplify you loop function to:

    void loop() {
       (void)Water_Level_check(Water_Level_A);
       (void)Water_Level_check(Water_Level_B);
    }

The `(void)` expression before each call is a "cast to void", telling the the compiler to consider the function's boolean return value to have been intentionally "voided", i.e. you *intended* not to read it, and not to give an error message.